diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 584d37a828..09453608b0 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 created-roster wire messages and closed Common value checks are present. Created snapshot storage, selected-character owner reads and Game Session consumer composition remain separate implementation work; this contract and transport foundation does not register or enable those owner paths. + 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). @@ -59,10 +61,11 @@ curl http://localhost:8080/ping - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. - `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – target `PRESEEDED_ONLY` pre-admission wire contract described in [Implementation Status](#implementation-status). Source models and manually composed certificate-guarded handler, peer-interceptor, client, and read-adapter source definitions are present; none of these or callers is registered. The result is discovery evidence, not actor admission or a session-binding shortcut. +- `CanonicalGameplayRosterService.ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter` – distinct, unregistered, non-admitting `PLAYER_CREATED` owner reads defined in [Player-created roster and selected character](#player-created-roster-and-selected-character). Created storage, owner composition and the Game Session consumer remain separate implementation work at this prerequisite. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. - `QueryInventory(QueryInventoryRequest) returns (QueryInventoryResponse)` – the current response is an unpaged repeated `InventoryItem items[]` projection. The live handler emits `item_id`, `item_name`, `item_description`, and `quantity`, and conditionally emits `container_instance_id`, `item_instance_id`, and `visible_ref` when those values are present. This projection does not establish complete instance-aware identity or stack/concurrency safety: rich pagination, complete holder-local stack uniqueness, find-then-create concurrency, and explicit-family duplicate handling remain target/proof gaps documented in [Runtime and Data](./runtime-and-data.md#implementation-status). -- `ListCharactersByAccount` (broader target-state policy/descriptor/template/namespace behavior) – the eventual policy-aware roster contract returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates account-to-character ownership; account identity is ownership evidence, not controller identity. The target response includes the exact published v1 entry policy and only its applicable versioned identity: descriptor/version for `PLAYER_CREATED`, template/version for `AUTO_PROVISIONED`, neither for `PRESEEDED_ONLY`; it echoes namespace/scope and returns an immutable roster snapshot identity/digest for the exact target, policy/version, and ordered roster. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results follow policy-specific next actions; a roster is discovery evidence, not admission authority. The separate `CanonicalGameplayRosterService` wire above currently specifies only the `PRESEEDED_ONLY` branch. `PLAYER_CREATED` and `AUTO_PROVISIONED` remain later-owned target branches, and the legacy numeric `ListCharactersByAccount` method is not trusted for canonical gameplay. Current handlers do not prove these target contracts. +- `ListCharactersByAccount` (broader target-state policy/descriptor/template/namespace behavior) – the eventual policy-aware roster contract returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates account-to-character ownership; account identity is ownership evidence, not controller identity. The target response includes the exact published v1 entry policy and only its applicable versioned identity: descriptor/version for `PLAYER_CREATED`, template/version for `AUTO_PROVISIONED`, neither for `PRESEEDED_ONLY`; it echoes namespace/scope and returns an immutable roster snapshot identity/digest for the exact target, policy/version, and ordered roster. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results follow policy-specific next actions; a roster is discovery evidence, not admission authority. The separate `CanonicalGameplayRosterService` wire above specifies both the `PRESEEDED_ONLY` and `PLAYER_CREATED` branches; the created-roster owner, storage and Game Session consumer implementation remain separate work at this prerequisite. `AUTO_PROVISIONED` remains a later wire target, and the legacy numeric `ListCharactersByAccount` method is not trusted for canonical gameplay. Current handlers do not prove these target contracts. - `AutoProvisionCharacter` (target-state) – after explicit entry, idempotently provisions at most one actor from the published realm template using the trusted `{tenantId, accountId, playableStateNamespaceId}` as the at-most-one uniqueness tuple. The request carries explicit `entryPolicy=AUTO_PROVISIONED`, the unchanged discovered-entry object and `discoveredEntryDigest`, the applicable exact template identity/version, a caller-stable `autoProvisionRequestId` that is stable and unique only within that exact `{tenantId, accountId, playableStateNamespaceId}` target scope, canonical `mutationDigest`, and an explicit absent-creation-input marker following ADR 0140's fixed-position presence encoding. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks it against the canonical snapshot and applicable template identity/version. Entity recomputes the mutation digest over the immutable trusted target, `entryPolicy`, exact template identity/version, and absent-input marker, and durably guards the operation by `{tenantId, accountId, playableStateNamespaceId, autoProvisionRequestId}` separately from the at-most-one-actor constraint; these operation-guard and actor-uniqueness constraints remain distinct. An actor-uniqueness race between distinct request IDs has one winner; each loser transactionally rereads and validates the exact target, policy, template provenance, and digest, durably stores its own guard result, and returns/replays the same actor only on exact match. A loser with mismatched provenance or digest stores a terminal `IDEMPOTENCY_CONFLICT` outcome and never replaces or allocates another actor. `playableStateScope` is only server-validated routing/authorization-fence evidence and is not an alternate key; `gameInstanceId` is the replaceable active-runtime fence. The same target-scoped guard with the same digest exact-replays the persisted actor, including under concurrent delivery; the same scoped guard with a changed digest-bound intent returns `IDEMPOTENCY_CONFLICT` before allocation. A different tenant, account, or namespace selects a different target-scoped guard and must not conflict solely because the text request ID is reused; no global request registry is implied. The current surface and proof are not implemented. - `QueryActorState` – returns gameplay-attested actor resources and active conditions for a scoped character. - `ApplyActorCondition` – **target-state request:** applies a gameplay-attested active condition or transient action state for a scoped character. The canonical target request carries a dedicated operation-unique `effectId`, separate source provenance, optional expiry, and the exact release-pinned typed effect declaration/reference and digest resolved by the server-side gameplay path; caller-defined effect JSON is not mutation authority. The target mutation persists the frozen definition/release and its server-resolved typed applied-effect snapshot and digest, never a caller-supplied payload. The current request still accepts transitional `effectPayloadJson`, so this typed-plan/no-caller-payload boundary is not live enforcement yet. @@ -79,6 +82,18 @@ For `DROP` and `PICKUP`, Entity is the holder-mutation participant in the canoni grpcurl -plaintext localhost:6565 entity_management.v1.EntityManagementService/Ping ``` +## Player-created roster and selected character + +`CanonicalGameplayRosterService.ListPlayerCreatedRoster(CanonicalPlayerCreatedRosterRequest)` and `ReadSelectedPlayerCreatedCharacter(CanonicalSelectedPlayerCreatedCharacterRequest)` are distinct non-admitting Entity owner reads. They require the exact authenticated same-namespace Game Session workload over mTLS and a closed `PlayerExecutionContext` whose operation, account, session, tenant, realm, playable namespace/scope and runtime instance agree with the request and full target. Listing has no selected actor; selected readback requires `context.character_id` to equal the requested actor. Entity independently obtains and compares the complete current published `PLAYER_CREATED` source, descriptor, policy, canonical version and `SHARED` target before local work. Missing, changed or unsupported source evidence fails closed. `ListPreseededRoster` and `ReadSelectedPreseededAssignment` remain strictly `PRESEEDED_ONLY`; `AUTO_PROVISIONED` is unsupported by these roster methods. + +The request carries the exact expected source identity: schema version 1, canonical non-nil descriptor UUID and revision UUID, descriptor digest, authored-binding UUID and authored-binding digest. Both digests use `sha256:` followed by 64 lowercase hexadecimal characters. The response retains that source identity and an ordered projection of persisted eligible actors with an immutable Entity snapshot UUID and digest. Zero actors is a valid empty snapshot and allocates none. The created digest uses domain `firemud.entity.player-created-roster.v1` and binds the canonical account, complete canonical target, exact source identity and ordered actor UUID/display-name pairs; it does not replace or recompute retained preseeded digests. The owner-issued policy digest remains distinct from authored projection content digests. Source identity and parsed wire values are comparison evidence, not peer authentication or an Account, membership, creation or admission capability. + +Selected readback names the same original Game Session operation UUID and retained menu/selection, account, session, complete target, source identity, frozen chosen actor UUID and snapshot UUID/digest. Entity requires that actor to occur exactly once in the original immutable roster and revalidates its actual persisted creation provenance. It returns the original `COMMITTED` `CHARACTER_CREATE` operation UUID, unchanged mutation digest and complete original terminal in `CanonicalSelectedPlayerCreatedCharacterResponse`; it never returns an assignment UUID or invents a replacement operation. Original creation runtime-instance/pointer/catalog counters are not durable actor identity and are not rewritten to the current route. Selected readback allocates no actor and requires the existing local admission nonce and original receipt. + +Source and original-owner RPCs run outside Entity SQL transactions. Capture and readback join the existing admission/original-operation and shared roster fences; exact retained operation replay returns the original full created receipt, and a changed binding or unknown outcome remains protected. The existing local retention and fence architecture belongs to [Runtime and Data](./runtime-and-data.md#sealed-canonical-roster-retention); created storage and owner composition remain implementation work. Recovery preserves the distinct created roster receipt without converting it into a preseeded response or dropping its source identity; closure and retirement retain the existing reference/hold protections. + +The created request bound is 16 KiB, source identity 4 KiB and complete roster receipt 66 KiB. The full creation terminal remains bounded to 192 MiB and selected-character response to 193 MiB. These are purpose-specific bounds; they do not widen the old preseeded messages or grant transport custody. Complete selected evidence must survive the original-reference and retirement paths within their declared purpose limits, without truncation or removal of opaque owner protection bytes. Common validation checks exact value bindings only; authenticating the source and consumer remains the owning service's responsibility. + ## Character creation owner protection The approved passive common-platform-core `CHARACTER_CREATE/1` model, codec, and bounded authored-source projection are present. The standalone parent check completed 233 tasks and 372 common-platform-core tests with zero failures, errors, or skips; this does not establish an authenticated producer, owner protections, or Entity terminal composition. The fixed ordered family and raw/normalized limits are owned by the [CHARACTER_CREATE/1 action schema](./character-create-action-schema.md), using ADR 0047's unchanged byte grammar. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 512a9c5e54..dfbe47c268 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,6 +8,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +Closed created-receipt wire checks and mandatory bounded production server registration are present. Created selection persistence, Entity client and owner-retirement composition remain separate implementation work. The transport foundation does not enable the created owner or establish player admission. + The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). The source-first owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. `RunOwnedCanonicalLaunchPreparationOwner` exposes canonical fresh-association, catalog and `STARTING` creation with independent owner readback only through an explicit preparation call; it has no scheduler. The published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap and existing `GameInstanceServiceImpl` behavior remain until coherent canonical adoption, so this source-first path is not evidence that the current scheduled runtime allocates that canonical launch. Game Design source keys and Game Session's allocated private tenant/runtime keys remain separate. The published numeric fixture path has not been removed by this source-only split. This explicit canonical path establishes no canonical World materialization/activation, canonical first-`OPEN`, or canonical admission result. @@ -102,6 +104,12 @@ Entity reserves a local admission nonce before its owner RPC, binds its snapshot Entity durably records that authenticated response before confirming delivery. Confirmation is bound to the same request and receipt. A confirmation repeated after qualified compact-receipt cleanup is only a no-op and cannot create acknowledgement or release authority. Required inventory, finite receipt retention, pending-transfer protection and owner-local cleanup belong to [Game Session runtime/data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership); Entity's local atomic observation and outbox rules belong to [sealed roster retention](../entity-management-service/runtime-and-data.md#sealed-canonical-roster-retention). Both transfer handlers retain the existing unregistered original-reference owner dependency and do not enable admission or production activation. +#### Player-created original roster consequences + +Game Session consumes Entity's distinct [player-created roster and selected-character contract](../entity-management-service/api-contracts.md#player-created-roster-and-selected-character) only after independently resolving the current published `PLAYER_CREATED` source and matching the complete route, policy, descriptor and source identity. It retains the exact typed created-roster and selected-character receipts on the original operation, preserves the original menu and ordinal/frozen actor choice, and revalidates the current route around owner reads. Original-operation reservation, returned-roster qualification and selected-reference qualification require independent current published-source observations, including their Game Design, World and published-policy evidence. An earlier observation cannot be cached across those authority boundaries to remove their freshness checks. These receipts provide no membership, session-binding or gameplay-admission authority. The two created roster and selected-character client RPCs use a finite twenty-second outer deadline so the nested five-second current-source and ten-second original-owner calls retain their bounded budgets under the inherited gRPC context. Request and response validation outside those calls remains part of the caller operation; this deadline is not a production latency guarantee. The existing preseeded route remains a separate strict branch; a Common parser validates values without establishing authenticated custody. + +The created reference response retains the complete selected payload within its 194 MiB purpose envelope, and retirement-observation requests retain it within the 195 MiB created-ACK envelope with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within its existing recovery purpose bound. These purpose-specific limits preserve complete owner bytes and the existing preseeded bounds. The shared server transport retains the framework 4 MiB deframing default. The existing `spring.grpc.server.max-inbound-message-size` setting may explicitly select a different positive finite ceiling no larger than the closed policy maximum for the created-retirement confirmation envelope; the policy maximum does not automatically enlarge the deployment limit. A deployment using the default rejects larger requests even on the two eligible created-retirement methods. Mandatory request marshalling at the canonical server-registration boundary checks the raw uncompressed request length before invoking any protobuf parser: only the exact generated acknowledgement and confirmation method descriptors receive their existing purpose bounds; every other method, including future or unlisted methods, retains the 4 MiB default or a smaller owning bound. Caller metadata cannot select a larger budget. Missing or duplicate admission configuration and unwrapped service registration fail closed. Semantic policy bounds, response bounds and workload authentication remain independent checks. When explicitly configured above the default, the shared transport can buffer more than 4 MiB before method admission rejects a request; method admission does not establish a 4 MiB network-memory ceiling. Before live created-owner activation, that larger configured mode requires production resource, concurrent-request memory and latency qualification. Controlled large-payload proof does not establish production capacity or select a per-connection concurrency budget. The corresponding local storage consequences belong to [Runtime and Data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership). + #### Canonical gameplay roster owner read The internal `CanonicalGameplayRosterOwnerReadService.GetCanonicalGameplayRosterOwnerRead` method is an Entity-only point-in-time source read. It requires the exact same-namespace Entity Management mTLS workload and no authenticated caller context; the request retains its exact caller-observed pointer-version and World-epoch preconditions. The route-reader composition is disabled unless `firemud.canonical-gameplay-roster-owner-read.enabled=true`; the bearer-check allowlist does not enable its source beans. The read returns source evidence only and does not create actors, bind sessions, or activate `PLAY` or `LOOK`. diff --git a/dev-tools/tests/test_telnet_session_driver.py b/dev-tools/tests/test_telnet_session_driver.py index 1b901894f0..274f293770 100644 --- a/dev-tools/tests/test_telnet_session_driver.py +++ b/dev-tools/tests/test_telnet_session_driver.py @@ -1031,13 +1031,24 @@ def handler(connection): session.connect() session.send_command("SAY \u00ff") session.send_command(f"LOGIN demo@example.com {secret}") - wait_for( + records = wait_for( session.store, lambda rows: any( - row.get("text") == "LOGIN demo@example.com [REDACTED]" + row.get("direction") == "inbound" + and row.get("event") == "received" + and row.get("text") == "LOGIN demo@example.com [REDACTED]\r\n" for row in rows ), ) + self.assertTrue( + any( + row.get("direction") == "outbound" + and row.get("event") == "command" + and row.get("text") == "LOGIN demo@example.com [REDACTED]" + for row in records + ), + "the local command marker must not satisfy the inbound echo wait", + ) session.close("iac_escape_complete") server.close_and_check() diff --git a/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto b/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto index 2013af10ad..811c09313e 100644 --- a/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto +++ b/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto @@ -29,5 +29,7 @@ message CanonicalGameplayRosterRecoveryResponse { string target_fence_uuid = 5; // Exact locally retained original receipt, if capture won before nonce closure. Absence is // positive fenced no-capture evidence only in this authenticated closed-admission response. + // PRESEEDED_ONLY; mutually exclusive with the distinct PLAYER_CREATED receipt. bytes canonical_roster_receipt = 6; + bytes canonical_player_created_roster_receipt = 7; } diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index eda2eb2236..d84b267aa7 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -5,6 +5,7 @@ package entity_management.v1; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; import "shared/v1/player_execution_context.proto"; +import "entity-management/v1/entity_character_create_service.proto"; option java_package = "net.firedevops.firemud.entitymanagement.v1"; option java_multiple_files = true; @@ -37,11 +38,12 @@ service EntityManagementService { returns (ValidateEntityUpgradeMappingsResponse); } -// Canonical gameplay roster discovery is a pre-admission, non-admitting boundary. Both methods -// are restricted to PRESEEDED_ONLY; other policy values are non-authorizing and fail with -// FAILED_PRECONDITION. This wire contract does not authorize the legacy numeric -// ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster response may -// contain zero actors; that is a successful lookup. These RPCs use canonical non-OK gRPC statuses +// Canonical gameplay roster discovery is a pre-admission, non-admitting boundary. The two +// preseeded methods below remain restricted to PRESEEDED_ONLY; other policy values are +// non-authorizing and fail with FAILED_PRECONDITION. The PLAYER_CREATED methods are a separate +// source-bound read contract and do not authenticate their unsigned context or authorize the +// legacy numeric ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster +// response may contain zero actors; that is a successful lookup. These RPCs use canonical non-OK gRPC statuses // rather than in-response errors: malformed requests are INVALID_ARGUMENT, stale snapshots or // selections not present in the bound snapshot are FAILED_PRECONDITION, unauthorized callers are // UNAUTHENTICATED or PERMISSION_DENIED as applicable, and unavailable dependencies are @@ -67,6 +69,59 @@ service CanonicalGameplayRosterService { // selected_character_uuid. The target policy must be PRESEEDED_ONLY. rpc ReadSelectedPreseededAssignment(CanonicalGameplayRosterSelectedAssignmentRequest) returns (CanonicalGameplayRosterSelectedAssignmentResponse); + + // Reads the source-bound persisted PLAYER_CREATED roster. The unsigned execution context is + // equality evidence only; peer authentication remains a server responsibility. + rpc ListPlayerCreatedRoster(CanonicalPlayerCreatedRosterRequest) + returns (CanonicalPlayerCreatedRosterResponse); + // Reads the exact selected actor from the original source-bound snapshot and returns the + // persisted creation terminal. This carrier does not authenticate that terminal. + rpc ReadSelectedPlayerCreatedCharacter(CanonicalSelectedPlayerCreatedCharacterRequest) + returns (CanonicalSelectedPlayerCreatedCharacterResponse); +} + +message CanonicalPlayerCreatedRosterSourceIdentity { + uint32 schema_version = 1; + string descriptor_uuid = 2; + string descriptor_revision_uuid = 3; + string descriptor_digest = 4; + string authored_binding_uuid = 5; + string authored_binding_digest = 6; +} + +message CanonicalPlayerCreatedRosterRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + CanonicalGameplayRosterTarget expected_target = 3; + shared.v1.PlayerExecutionContext player_execution_context = 4; + CanonicalPlayerCreatedRosterSourceIdentity expected_source = 5; +} + +message CanonicalPlayerCreatedRosterResponse { + CanonicalGameplayRosterResponse roster = 1; + CanonicalPlayerCreatedRosterSourceIdentity source_identity = 2; +} + +message CanonicalSelectedPlayerCreatedCharacterRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget expected_target = 4; + CanonicalGameplayRosterSnapshotReference expected_snapshot = 5; + shared.v1.PlayerExecutionContext player_execution_context = 6; + CanonicalPlayerCreatedRosterSourceIdentity expected_source = 7; +} + +message CanonicalSelectedPlayerCreatedCharacterResponse { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget target = 4; + CanonicalGameplayRosterSnapshotReference snapshot = 5; + CanonicalPlayerCreatedRosterSourceIdentity source_identity = 6; + string creation_operation_uuid = 7; + string mutation_digest = 8; + EntityCharacterCreateTerminal terminal = 9; } message CanonicalGameplayRosterRequest { diff --git a/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto index 3c3e6726c1..3c2ead5848 100644 --- a/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto +++ b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto @@ -100,6 +100,8 @@ message GetCanonicalGameplayRosterReferenceRequest { string session_uuid = 4; string target_namespace = 5; bytes canonical_target = 6; + // Canonical CanonicalPlayerCreatedRosterSourceIdentity bytes, required only for PLAYER_CREATED. + bytes canonical_player_created_source_identity = 7; } enum CanonicalGameplayRosterReferenceState { @@ -116,6 +118,7 @@ message GetCanonicalGameplayRosterReferenceResponse { CanonicalGameplayRosterReferenceState state = 3; // Canonical Entity snapshot response bytes, present only after receipt binding. Recording a // receipt does not release its retained selection/session/recovery/restore dependencies. + // PRESEEDED_ONLY receipt; mutually exclusive with the PLAYER_CREATED carrier below. bytes canonical_roster_receipt = 4; CanonicalGameplayRosterSelectionInput selection_input = 5; string selected_character_uuid = 6; @@ -130,6 +133,10 @@ message GetCanonicalGameplayRosterReferenceResponse { string retirement_proof_digest = 15; // Owner-local recovery fence: normal reads/writes cannot restart this original operation. string recovery_uuid = 16; + // Canonical typed PLAYER_CREATED roster and selected original creation terminal receipts. + // PRESEEDED_ONLY roster/assignment fields must be absent for this distinct policy branch. + bytes canonical_player_created_roster_receipt = 17; + bytes canonical_selected_player_created_character_receipt = 18; } // Original selection input is frozen before any Entity roster read. A later ordinal choice is a diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 6cb1980995..6f1d4950ea 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -33,4 +33,6 @@ dependencies { testFixturesApi(platform(libs.spring.boot.dependencies)) testFixturesApi("tools.jackson.core:jackson-databind") testFixturesApi(libs.grpc.stub) + testFixturesApi(libs.protobuf.java) + testFixturesCompileOnly(libs.spotbugs.annotations) } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java new file mode 100644 index 0000000000..5ba13301fc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.common.config; + +import io.grpc.BindableService; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.grpc.server.autoconfigure.ConditionalOnGrpcNativeServer; +import org.springframework.boot.grpc.server.autoconfigure.ConditionalOnGrpcServerEnabled; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.util.LambdaSafe; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Bean; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.ServerBuilderCustomizer; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.GrpcServiceConfigurer; +import org.springframework.grpc.server.service.GrpcServiceDiscoverer; + +/** Owns the shared production registration boundary; alternate factories fail startup. */ +@AutoConfiguration( + beforeName = + "org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration") +@ConditionalOnClass({GrpcServerFactory.class, NettyServerBuilder.class}) +@ConditionalOnBean(BindableService.class) +@ConditionalOnGrpcServerEnabled +@EnableConfigurationProperties(GrpcServerProperties.class) +public class CommonGrpcRequestBoundsAutoConfiguration { + @Bean + @ConditionalOnMissingBean(GrpcRequestBytePolicy.class) + GrpcRequestBytePolicy ordinaryGrpcRequestBytePolicy() { + return GrpcRequestBytePolicy.ordinary(); + } + + @Bean + @ConditionalOnGrpcNativeServer + BoundedGrpcServerFactory boundedGrpcServerFactory( + GrpcServerProperties properties, + GrpcRequestBytePolicy policy, + GrpcServiceDiscoverer discoverer, + GrpcServiceConfigurer configurer, + ObjectProvider bundles, + ObjectProvider> builderCustomizers, + ObjectProvider factoryCustomizers) { + KeyManagerFactory keys = null; + TrustManagerFactory trust = null; + if (properties.getSsl().determineEnabled()) { + String bundleName = properties.getSsl().getBundle(); + if (bundleName == null || bundleName.isBlank()) { + throw new IllegalStateException("A gRPC SSL bundle is required"); + } + SslBundle bundle = bundles.getObject().getBundle(bundleName); + keys = bundle.getManagers().getKeyManagerFactory(); + trust = + properties.getSsl().isSecure() + ? bundle.getManagers().getTrustManagerFactory() + : InsecureTrustManagerFactory.INSTANCE; + } + // Preserve the framework's 4 MiB default; policy maxima only constrain explicit opt-in. + int transportMaximum = Math.toIntExact(properties.getMaxInboundMessageSize().toBytes()); + List> customizers = + List.of( + builder -> configureProperties(builder, properties), + builder -> + applyBuilderCustomizers(builder, builderCustomizers.orderedStream().toList())); + BoundedGrpcServerFactory factory = + new BoundedGrpcServerFactory( + properties.determineAddress(), + customizers, + keys, + trust, + properties.getSsl().getClientAuth(), + policy, + transportMaximum); + factoryCustomizers.orderedStream().forEach(customizer -> customizer.customize(factory)); + discoverer + .findServices() + .forEach(service -> factory.addService(configurer.configure(service, factory))); + return factory; + } + + @Bean + @ConditionalOnMissingBean(GrpcServerLifecycle.class) + GrpcServerLifecycle boundedGrpcServerLifecycle( + BoundedGrpcServerFactory factory, + GrpcServerProperties properties, + ApplicationEventPublisher publisher) { + return new GrpcServerLifecycle(factory, properties.getShutdownGracePeriod(), publisher); + } + + @Bean + SmartInitializingSingleton requireOnlyBoundedGrpcServerFactory(ApplicationContext context) { + return () -> { + var factories = context.getBeansOfType(GrpcServerFactory.class); + if (factories.size() != 1 + || factories.values().iterator().next().getClass() != BoundedGrpcServerFactory.class) { + throw new IllegalStateException( + "Production gRPC requires exactly one bounded server factory"); + } + }; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void applyBuilderCustomizers( + NettyServerBuilder builder, List> customizers) { + LambdaSafe.callbacks(ServerBuilderCustomizer.class, customizers, builder) + .invoke(customizer -> customizer.customize(builder)); + } + + private static void configureProperties( + NettyServerBuilder builder, GrpcServerProperties properties) { + var keepAlive = properties.getKeepAlive(); + duration(keepAlive.getTime(), builder::keepAliveTime); + duration(keepAlive.getTimeout(), builder::keepAliveTimeout); + duration(keepAlive.getMaxIdle(), builder::maxConnectionIdle); + duration(keepAlive.getMaxAge(), builder::maxConnectionAge); + duration(keepAlive.getMaxAgeGrace(), builder::maxConnectionAgeGrace); + duration(keepAlive.getPermitTime(), builder::permitKeepAliveTime); + builder.permitKeepAliveWithoutCalls(keepAlive.isPermitWithoutCalls()); + builder.maxInboundMetadataSize( + Math.toIntExact(properties.getMaxInboundMetadataSize().toBytes())); + } + + private static void duration(Duration duration, BiConsumer apply) { + if (duration != null) { + apply.accept(duration.toNanos(), TimeUnit.NANOSECONDS); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshaller.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshaller.java new file mode 100644 index 0000000000..cdc5810b49 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshaller.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.ForwardingServerCall; +import io.grpc.ForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.SequenceInputStream; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.Enumeration; + +/** Raw stream marshalling paired with admission before the original protobuf parser. */ +final class BoundedGrpcRequestMarshaller implements MethodDescriptor.Marshaller { + private static final int CHUNK_BYTES = 64 * 1024; + + private BoundedGrpcRequestMarshaller() {} + + static ServerServiceDefinition rawMessages(ServerServiceDefinition service) { + // Unlike useInputStreamMessages, this public adapter does not add a prefetching buffer. + return ServerInterceptors.useMarshalledMessages(service, new BoundedGrpcRequestMarshaller()); + } + + @Override + public InputStream stream(InputStream message) { + return message; + } + + @Override + public InputStream parse(InputStream message) { + return message; + } + + static ServerCallHandler guard( + ServerCallHandler next, int maximum) { + if (maximum <= 0 || maximum == Integer.MAX_VALUE) { + throw new IllegalArgumentException("A finite positive request byte bound is required"); + } + return (call, headers) -> { + var state = new CallState(); + ServerCall observedCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void close(Status status, Metadata trailers) { + state.closed = true; + super.close(status, trailers); + } + }; + // The public stream adapter invokes the existing intercepted handler here. Its + // authentication, Contexts listener wrappers and response marshaller remain intact. + var delegate = next.startCall(observedCall, headers); + return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(delegate) { + @Override + public void onMessage(InputStream message) { + if (stopped()) { + return; + } + Deque admitted = new ArrayDeque<>(); + int admittedBytes = 0; + try { + // Neither available(), compressed wire length nor caller metadata grants admission. + // Retain bounded chunks without flattening the whole request into a second array. + while (admittedBytes <= maximum) { + int requested = Math.min(CHUNK_BYTES, maximum - admittedBytes + 1); + byte[] chunk = message.readNBytes(requested); + if (chunk.length == 0) { + break; + } + admitted.addLast(chunk); + admittedBytes += chunk.length; + if (chunk.length < requested) { + break; + } + } + } catch (IOException failure) { + reject( + Status.INTERNAL + .withDescription("Unable to read bounded gRPC request") + .withCause(failure)); + return; + } catch (RuntimeException failure) { + Status status = Status.fromThrowable(failure); + reject( + status.getCode() == Status.Code.UNKNOWN + ? Status.INTERNAL + .withDescription("Unable to read bounded gRPC request") + .withCause(failure) + : status); + return; + } + if (admittedBytes > maximum) { + reject( + Status.RESOURCE_EXHAUSTED.withDescription( + "gRPC request exceeds method byte bound")); + return; + } + if (!stopped()) { + // Only this replay reaches the stream adapter's original protobuf parser. + super.onMessage(replay(admitted)); + } + } + + @Override + public void onHalfClose() { + if (!stopped()) { + super.onHalfClose(); + } + } + + @Override + public void onReady() { + if (!stopped()) { + super.onReady(); + } + } + + @Override + public void onCancel() { + if (!state.terminal) { + state.terminal = true; + state.closed = true; + super.onCancel(); + } + } + + @Override + public void onComplete() { + if (!state.terminal) { + state.terminal = true; + state.closed = true; + super.onComplete(); + } + } + + private boolean stopped() { + return state.closed || call.isCancelled(); + } + + private void reject(Status status) { + if (!stopped()) { + // Close explicitly: exceptions escaping marshaller.parse become UNKNOWN on the wire. + observedCall.close(status, new Metadata()); + } + } + }; + }; + } + + private static InputStream replay(Deque chunks) { + return new SequenceInputStream( + new Enumeration<>() { + @Override + public boolean hasMoreElements() { + return !chunks.isEmpty(); + } + + @Override + public InputStream nextElement() { + // Drop consumed chunks as the original parser advances, without a whole-message copy. + return new ByteArrayInputStream(chunks.removeFirst()); + } + }); + } + + private static final class CallState { + private volatile boolean closed; + private boolean terminal; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactory.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactory.java new file mode 100644 index 0000000000..3ef97f15d7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactory.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.HandlerRegistry; +import io.grpc.Server; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.TlsServerCredentials; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import org.springframework.grpc.server.ServerBuilderCustomizer; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; + +/** The production factory admits every method before protobuf parsing. */ +public final class BoundedGrpcServerFactory extends ShadedNettyGrpcServerFactory { + private static final HandlerRegistry CLOSED_FALLBACK = + new HandlerRegistry() { + @Override + public ServerMethodDefinition lookupMethod(String methodName, String authority) { + return null; + } + }; + private final Set> guardedMethods = + Collections.newSetFromMap(new IdentityHashMap<>()); + private final GrpcRequestBytePolicy policy; + private final int transportMaximum; + + public BoundedGrpcServerFactory( + String address, + List> customizers, + KeyManagerFactory keys, + TrustManagerFactory trust, + TlsServerCredentials.ClientAuth clientAuth, + GrpcRequestBytePolicy policy, + int transportMaximum) { + super(address, customizers, keys, trust, clientAuth); + if (transportMaximum <= 0 || transportMaximum > policy.transportMaximumBytes()) { + throw new IllegalArgumentException("Transport bound exceeds the closed gRPC request policy"); + } + this.policy = policy; + this.transportMaximum = transportMaximum; + } + + @Override + protected void configureServices( + NettyServerBuilder builder, List services) { + policy.requireRegistered(services); + List guarded = + services.stream().map(service -> policy.guard(service, transportMaximum)).toList(); + guardedMethods.clear(); + guarded.forEach(service -> guardedMethods.addAll(service.getMethods())); + super.configureServices(builder, guarded); + } + + @Override + protected void configure(NettyServerBuilder builder, List services) { + super.configure(builder, services); + // Customizers cannot leave an alternate mutable lookup or widen the finite ceiling. + builder.fallbackHandlerRegistry(CLOSED_FALLBACK); + builder.maxInboundMessageSize(transportMaximum); + } + + @Override + public Server createServer() { + Server server = super.createServer(); + try { + for (ServerServiceDefinition service : server.getServices()) { + for (ServerMethodDefinition method : service.getMethods()) { + // A descriptor or marshaller alone cannot prove its handler still enforces admission. + if (!guardedMethods.contains(method)) { + throw new IllegalStateException( + "Unguarded gRPC method registered: " + + method.getMethodDescriptor().getFullMethodName()); + } + } + } + return server; + } catch (RuntimeException failure) { + server.shutdownNow(); + throw failure; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcRequestBytePolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcRequestBytePolicy.java new file mode 100644 index 0000000000..12710266b3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcRequestBytePolicy.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.MethodDescriptor; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import java.io.InputStream; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; + +/** Closed, server-owned generated-descriptor exceptions to ordinary raw request admission. */ +public final class GrpcRequestBytePolicy { + public static final int ORDINARY_MAXIMUM_BYTES = 4 * 1024 * 1024; + private final Map, Integer> exceptions; + + record MethodBound(MethodDescriptor method, int maximumBytes) { + MethodBound { + Objects.requireNonNull(method); + if (maximumBytes <= 0 || maximumBytes == Integer.MAX_VALUE) { + throw new IllegalArgumentException("A finite positive method byte bound is required"); + } + } + } + + GrpcRequestBytePolicy(List bounds) { + exceptions = new IdentityHashMap<>(); + Set names = new HashSet<>(); + for (MethodBound bound : bounds) { + if (!names.add(bound.method().getFullMethodName())) { + throw new IllegalArgumentException("Duplicate gRPC request bound"); + } + exceptions.put(bound.method(), bound.maximumBytes()); + } + } + + public static GrpcRequestBytePolicy ordinary() { + return new GrpcRequestBytePolicy(List.of()); + } + + public static GrpcRequestBytePolicy createdRosterRetirement() { + return new GrpcRequestBytePolicy( + List.of( + new MethodBound( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod(), + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES), + new MethodBound( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getConfirmCanonicalGameplayRosterRetirementAcknowledgementMethod(), + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES))); + } + + public int transportMaximumBytes() { + return Math.max( + ORDINARY_MAXIMUM_BYTES, + exceptions.values().stream() + .mapToInt(Integer::intValue) + .max() + .orElse(ORDINARY_MAXIMUM_BYTES)); + } + + void requireRegistered(List services) { + Set> found = + java.util.Collections.newSetFromMap(new IdentityHashMap<>()); + for (ServerServiceDefinition service : services) { + service.getMethods().forEach(method -> found.add(method.getMethodDescriptor())); + } + if (!found.containsAll(exceptions.keySet())) { + throw new IllegalStateException( + "Configured gRPC request bound has no exact registered descriptor"); + } + } + + ServerServiceDefinition guard(ServerServiceDefinition service, int transportMaximum) { + ServerServiceDefinition raw = BoundedGrpcRequestMarshaller.rawMessages(service); + ServerServiceDefinition.Builder result = + ServerServiceDefinition.builder(raw.getServiceDescriptor()); + for (ServerMethodDefinition method : service.getMethods()) { + MethodDescriptor original = method.getMethodDescriptor(); + int maximum = + Math.min(transportMaximum, exceptions.getOrDefault(original, ORDINARY_MAXIMUM_BYTES)); + ServerMethodDefinition rawMethod = + streamMethod(raw.getMethod(original.getFullMethodName())); + result.addMethod( + rawMethod.withServerCallHandler( + BoundedGrpcRequestMarshaller.guard(rawMethod.getServerCallHandler(), maximum))); + } + return result.build(); + } + + @SuppressWarnings("unchecked") + private static ServerMethodDefinition streamMethod( + ServerMethodDefinition method) { + // rawMessages uses the public adapter with InputStream request and response marshallers. + return (ServerMethodDefinition) method; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java index 3e0fe61df4..fa84ae9712 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java @@ -2,9 +2,11 @@ import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; /** @@ -47,6 +49,9 @@ public static CanonicalGameplayRosterRecoveryResponse response( long ownerFence, UUID targetFence, CanonicalGameplayRosterResponse receipt) { + requireRequest(request); + if (created(request)) + throw new IllegalArgumentException("PRESEEDED_ONLY recovery response factory required"); var result = CanonicalGameplayRosterRecoveryResponse.newBuilder() .setSchemaVersion(1) @@ -58,6 +63,32 @@ public static CanonicalGameplayRosterRecoveryResponse response( return requireResponse(request, result.build()); } + public static CanonicalGameplayRosterRecoveryResponse playerCreatedResponse( + CanonicalGameplayRosterRecoveryRequest request, + UUID admission, + long ownerFence, + UUID targetFence, + CanonicalPlayerCreatedRosterResponse receipt) { + requireRequest(request); + if (!created(request)) + throw new IllegalArgumentException("PLAYER_CREATED recovery response factory required"); + var result = + CanonicalGameplayRosterRecoveryResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setAdmissionUuid(admission.toString()) + .setOwnerFence(ownerFence) + .setTargetFenceUuid(targetFence.toString()); + if (receipt != null) result.setCanonicalPlayerCreatedRosterReceipt(receipt.toByteString()); + return requireResponse(request, result.build()); + } + + private static boolean created(CanonicalGameplayRosterRecoveryRequest request) { + return CanonicalGameplayRosterReferenceEvidence.target(request.getOriginalSelection()) + .getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED; + } + public static CanonicalGameplayRosterRecoveryResponse requireResponse( CanonicalGameplayRosterRecoveryRequest expected, CanonicalGameplayRosterRecoveryResponse response) { @@ -73,12 +104,21 @@ public static CanonicalGameplayRosterRecoveryResponse requireResponse( } CanonicalGameplayRosterReferenceEvidence.uuid(response.getAdmissionUuid()); CanonicalGameplayRosterReferenceEvidence.uuid(response.getTargetFenceUuid()); - if (!response.getCanonicalRosterReceipt().isEmpty()) { - // Reuse the canonical original-receipt parser and exact target/account binding. - CanonicalGameplayRosterReferenceEvidence.receipt( + boolean created = created(expected); + if ((created && !response.getCanonicalRosterReceipt().isEmpty()) + || (!created && !response.getCanonicalPlayerCreatedRosterReceipt().isEmpty())) { + throw new IllegalArgumentException( + "Recovery receipt changed its explicit roster policy branch"); + } + if (!response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + // Exact validated projection only; this does not authenticate an Entity response. + CanonicalGameplayRosterReferenceEvidence.snapshotReceipt( GetCanonicalGameplayRosterReferenceResponse.newBuilder() .setRequest(expected.getOriginalSelection()) .setCanonicalRosterReceipt(response.getCanonicalRosterReceipt()) + .setCanonicalPlayerCreatedRosterReceipt( + response.getCanonicalPlayerCreatedRosterReceipt()) .build()); } return response; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java index bec97c97b1..23be502f67 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java @@ -1,23 +1,44 @@ package net.firedevops.firemud.common.world; import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.InvalidProtocolBufferException; -import java.util.Arrays; +import com.google.protobuf.MessageLite; +import java.io.IOException; +import java.io.OutputStream; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; /** Closed original-operation carrier. Neither RESERVED nor RECORDED is retirement authority. */ public final class CanonicalGameplayRosterReferenceEvidence { public static final int MAX_REQUEST_BYTES = 4096; public static final int MAX_RECEIPT_BYTES = 64 * 1024; + public static final int MAX_SELECTED_ASSIGNMENT_BYTES = 8192; + public static final int MAX_RESPONSE_BYTES = 128 * 1024; + public static final int MAX_PLAYER_CREATED_RECEIPT_BYTES = + CanonicalPlayerCreatedRosterEvidence.MAX_ROSTER_RECEIPT_BYTES; + public static final int MAX_SELECTED_PLAYER_CREATED_BYTES = + CanonicalPlayerCreatedRosterEvidence.MAX_SELECTED_RECEIPT_BYTES; + public static final int MAX_PLAYER_CREATED_RESPONSE_BYTES = 194 * 1024 * 1024; + private static final int CANONICAL_COMPARISON_BUFFER_BYTES = 4096; private CanonicalGameplayRosterReferenceEvidence() {} @@ -27,6 +48,7 @@ public static GetCanonicalGameplayRosterReferenceRequest request( UUID session, String namespace, CanonicalGameplayRosterTarget target) { + requirePreseeded(target); return requireRequest( GetCanonicalGameplayRosterReferenceRequest.newBuilder() .setSchemaVersion(1) @@ -38,8 +60,35 @@ public static GetCanonicalGameplayRosterReferenceRequest request( .build()); } + public static GetCanonicalGameplayRosterReferenceRequest playerCreatedRequest( + UUID operation, + UUID account, + UUID session, + String namespace, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source) { + requireCreated(target); + return requireRequest( + GetCanonicalGameplayRosterReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setOperationUuid(operation.toString()) + .setCanonicalAccountUuid(account.toString()) + .setSessionUuid(session.toString()) + .setTargetNamespace(namespace) + .setCanonicalTarget(target.toByteString()) + .setCanonicalPlayerCreatedSourceIdentity( + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity(source).toByteString()) + .build()); + } + public static GetCanonicalGameplayRosterReferenceRequest requireRequest( GetCanonicalGameplayRosterReferenceRequest request) { + requireRequestTarget(request); + return request; + } + + private static CanonicalGameplayRosterTarget requireRequestTarget( + GetCanonicalGameplayRosterReferenceRequest request) { Objects.requireNonNull(request, "request"); if (request.getSerializedSize() > MAX_REQUEST_BYTES || !request.getUnknownFields().asMap().isEmpty() @@ -50,8 +99,14 @@ public static GetCanonicalGameplayRosterReferenceRequest requireRequest( uuid(request.getOperationUuid()); uuid(request.getCanonicalAccountUuid()); uuid(request.getSessionUuid()); - target(request); - return request; + CanonicalGameplayRosterTarget target = target(request); + if (isCreated(target)) { + playerCreatedSourceIdentity(request); + } else if (!request.getCanonicalPlayerCreatedSourceIdentity().isEmpty()) { + throw new IllegalArgumentException( + "PRESEEDED_ONLY original cannot carry PLAYER_CREATED source identity"); + } + return target; } public static CanonicalGameplayRosterTarget target( @@ -60,14 +115,17 @@ public static CanonicalGameplayRosterTarget target( CanonicalGameplayRosterTarget target = CanonicalGameplayRosterTarget.parseFrom(request.getCanonicalTarget()); if (!target.getUnknownFields().asMap().isEmpty() - || !Arrays.equals(target.toByteArray(), request.getCanonicalTarget().toByteArray()) + || !hasCanonicalEncoding(target, request.getCanonicalTarget()) || target.getCatalogRevision() <= 0 || target.getPointerVersion() <= 0 || target.getActiveWorldEpoch() <= 0 || (target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED && target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) - || target.getEntryPolicy() - != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY + || (target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY + && !isCreated(target)) + || (isCreated(target) + && target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) || !target.getWorldSlug().matches("[a-z0-9][a-z0-9-]{0,63}") || !target.getRealmSlug().matches("[a-z0-9][a-z0-9-]{0,63}") || !target.getPublishedPolicyDigest().matches("[0-9a-f]{64}") @@ -97,6 +155,7 @@ public static GetCanonicalGameplayRosterReferenceResponse response( long fence, UUID targetFence, CanonicalGameplayRosterResponse receipt) { + requirePreseeded(target(requireRequest(request))); var response = GetCanonicalGameplayRosterReferenceResponse.newBuilder() .setRequest(requireRequest(request)) @@ -114,6 +173,180 @@ public static GetCanonicalGameplayRosterReferenceResponse response( return requireResponse(request, response.build()); } + public static GetCanonicalGameplayRosterReferenceResponse playerCreatedResponse( + GetCanonicalGameplayRosterReferenceRequest request, + long fence, + UUID targetFence, + CanonicalPlayerCreatedRosterResponse receipt) { + requireCreated(target(requireRequest(request))); + var response = + GetCanonicalGameplayRosterReferenceResponse.newBuilder() + .setRequest(request) + .setOwnerFence(fence) + .setTargetFenceUuid(targetFence.toString()) + .setState( + receipt == null + ? CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RESERVED + : CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED); + if (receipt != null) response.setCanonicalPlayerCreatedRosterReceipt(receipt.toByteString()); + return requireResponse(request, response.build()); + } + + public static CanonicalPlayerCreatedRosterSourceIdentity playerCreatedSourceIdentity( + GetCanonicalGameplayRosterReferenceRequest request) { + requireCreated(target(request)); + try { + var bytes = request.getCanonicalPlayerCreatedSourceIdentity(); + if (bytes.isEmpty() + || bytes.size() > CanonicalPlayerCreatedRosterEvidence.MAX_SOURCE_IDENTITY_BYTES) { + throw new IllegalArgumentException( + "Complete canonical PLAYER_CREATED source identity required"); + } + var source = + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.parseFrom(bytes)); + if (!hasCanonicalEncoding(source, bytes)) { + throw new IllegalArgumentException( + "PLAYER_CREATED source identity bytes are not canonical"); + } + return source; + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("PLAYER_CREATED source identity is malformed", invalid); + } + } + + public static CanonicalPlayerCreatedRosterResponse playerCreatedReceipt( + GetCanonicalGameplayRosterReferenceResponse response) { + requireCreated(target(requireRequest(response.getRequest()))); + if (!response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalSelectedAssignmentReceipt().isEmpty()) { + throw new IllegalArgumentException("PLAYER_CREATED receipt cannot use PRESEEDED_ONLY fields"); + } + try { + var bytes = response.getCanonicalPlayerCreatedRosterReceipt(); + if (bytes.isEmpty() || bytes.size() > MAX_PLAYER_CREATED_RECEIPT_BYTES) { + throw new IllegalArgumentException( + "Complete bounded PLAYER_CREATED roster receipt required"); + } + var roster = CanonicalPlayerCreatedRosterResponse.parseFrom(bytes); + if (!hasCanonicalEncoding(roster, bytes)) { + throw new IllegalArgumentException("PLAYER_CREATED roster receipt bytes are not canonical"); + } + return CanonicalPlayerCreatedRosterEvidence.requireResponse( + createdRosterRequest(response.getRequest()), roster); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("PLAYER_CREATED roster receipt is malformed", invalid); + } + } + + /** Exact validated generic snapshot projection; this does not authenticate its producer. */ + public static CanonicalGameplayRosterResponse snapshotReceipt( + GetCanonicalGameplayRosterReferenceResponse response) { + return isCreated(target(response.getRequest())) + ? playerCreatedReceipt(response).getRoster() + : receipt(response); + } + + public static CanonicalSelectedPlayerCreatedCharacterResponse + selectedPlayerCreatedCharacterReceipt(GetCanonicalGameplayRosterReferenceResponse response) { + var roster = playerCreatedReceipt(response).getRoster(); + return selectedPlayerCreatedCharacterReceipt(response, roster); + } + + private static CanonicalSelectedPlayerCreatedCharacterResponse + selectedPlayerCreatedCharacterReceipt( + GetCanonicalGameplayRosterReferenceResponse response, + CanonicalGameplayRosterResponse roster) { + try { + var bytes = response.getCanonicalSelectedPlayerCreatedCharacterReceipt(); + if (bytes.isEmpty() || bytes.size() > MAX_SELECTED_PLAYER_CREATED_BYTES) { + throw new IllegalArgumentException( + "Complete bounded selected PLAYER_CREATED terminal required"); + } + var selected = CanonicalSelectedPlayerCreatedCharacterResponse.parseFrom(bytes); + if (!hasCanonicalEncoding(selected, bytes)) { + throw new IllegalArgumentException( + "Selected PLAYER_CREATED receipt bytes are not canonical"); + } + var original = response.getRequest(); + var expected = + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(response.getSelectedCharacterUuid()) + .setExpectedTarget(target(original)) + .setExpectedSource(playerCreatedSourceIdentity(original)) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.getSnapshotUuid()) + .setSnapshotDigest(roster.getSnapshotDigest())) + .setPlayerExecutionContext( + comparisonContext(original).setCharacterId(response.getSelectedCharacterUuid())) + .build(); + var validated = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(expected, selected); + if (!validated + .getTerminal() + .getOriginalRequest() + .getOriginal() + .getTargetNamespace() + .equals(original.getTargetNamespace())) { + throw new IllegalArgumentException( + "Selected creation terminal changed original workload namespace"); + } + return validated; + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("Selected PLAYER_CREATED terminal is malformed", invalid); + } + } + + private static CanonicalPlayerCreatedRosterRequest createdRosterRequest( + GetCanonicalGameplayRosterReferenceRequest original) { + return CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setExpectedTarget(target(original)) + .setExpectedSource(playerCreatedSourceIdentity(original)) + .setPlayerExecutionContext(comparisonContext(original)) + .build(); + } + + // Reconstruct comparison values only. This is never authenticated execution-context custody. + private static PlayerExecutionContext.Builder comparisonContext( + GetCanonicalGameplayRosterReferenceRequest original) { + var target = target(original); + return PlayerExecutionContext.newBuilder() + .setRequestId(original.getOperationUuid()) + .setAccountId(original.getCanonicalAccountUuid()) + .setSessionId(original.getSessionUuid()) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .setGameInstanceId(target.getGameInstanceUuid()); + } + + private static boolean isCreated(CanonicalGameplayRosterTarget target) { + return target.getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED; + } + + private static void requireCreated(CanonicalGameplayRosterTarget target) { + if (!isCreated(target) + || target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + throw new IllegalArgumentException("Distinct SHARED PLAYER_CREATED carrier required"); + } + } + + private static void requirePreseeded(CanonicalGameplayRosterTarget target) { + if (target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) { + throw new IllegalArgumentException("Distinct PRESEEDED_ONLY carrier required"); + } + } + public static net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput requireSelectionInput( net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput input) { @@ -137,9 +370,25 @@ public static GetCanonicalGameplayRosterReferenceResponse response( public static net.firedevops.firemud.entitymanagement.v1 .CanonicalGameplayRosterSelectedAssignmentResponse selectedAssignmentReceipt(GetCanonicalGameplayRosterReferenceResponse response) { + requirePreseeded(target(requireRequest(response.getRequest()))); + rejectCreatedFields(response); + if (response.getCanonicalSelectedAssignmentReceipt().isEmpty() + || response.getCanonicalSelectedAssignmentReceipt().size() + > MAX_SELECTED_ASSIGNMENT_BYTES) { + throw new IllegalArgumentException("Complete original selected assignment receipt required"); + } + return selectedAssignmentReceipt(response, receipt(response)); + } + + private static net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSelectedAssignmentResponse + selectedAssignmentReceipt( + GetCanonicalGameplayRosterReferenceResponse response, + CanonicalGameplayRosterResponse roster) { try { if (response.getCanonicalSelectedAssignmentReceipt().isEmpty() - || response.getCanonicalSelectedAssignmentReceipt().size() > 8192) { + || response.getCanonicalSelectedAssignmentReceipt().size() + > MAX_SELECTED_ASSIGNMENT_BYTES) { throw new IllegalArgumentException( "Complete original selected assignment receipt required"); } @@ -147,10 +396,9 @@ public static GetCanonicalGameplayRosterReferenceResponse response( net.firedevops.firemud.entitymanagement.v1 .CanonicalGameplayRosterSelectedAssignmentResponse.parseFrom( response.getCanonicalSelectedAssignmentReceipt()); - var roster = receipt(response); if (!selected.getUnknownFields().asMap().isEmpty() || !selected.getSnapshot().getUnknownFields().asMap().isEmpty() - || !selected.toByteString().equals(response.getCanonicalSelectedAssignmentReceipt()) + || !hasCanonicalEncoding(selected, response.getCanonicalSelectedAssignmentReceipt()) || !selected.getRequestUuid().equals(response.getRequest().getOperationUuid()) || !selected .getCanonicalAccountUuid() @@ -173,31 +421,71 @@ public static GetCanonicalGameplayRosterReferenceResponse response( public static GetCanonicalGameplayRosterReferenceResponse requireResponse( GetCanonicalGameplayRosterReferenceRequest expected, GetCanonicalGameplayRosterReferenceResponse response) { - requireRequest(expected); + return validateResponse(expected, response).response(); + } + + static CanonicalGameplayRosterResponse requireResponseSnapshot( + GetCanonicalGameplayRosterReferenceRequest expected, + GetCanonicalGameplayRosterReferenceResponse response) { + return validateResponse(expected, response).snapshotReceipt(); + } + + private static ValidatedResponse validateResponse( + GetCanonicalGameplayRosterReferenceRequest expected, + GetCanonicalGameplayRosterReferenceResponse response) { + CanonicalGameplayRosterTarget expectedTarget = requireRequestTarget(expected); Objects.requireNonNull(response, "response"); - if (!response.getUnknownFields().asMap().isEmpty() + boolean created = isCreated(expectedTarget); + if (created) { + if (!response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalSelectedAssignmentReceipt().isEmpty()) { + throw new IllegalArgumentException( + "PLAYER_CREATED original cannot carry PRESEEDED_ONLY receipts"); + } + } else { + rejectCreatedFields(response); + } + if (response.getSerializedSize() + > (created ? MAX_PLAYER_CREATED_RESPONSE_BYTES : MAX_RESPONSE_BYTES) + || response.getCanonicalPlayerCreatedRosterReceipt().size() + > MAX_PLAYER_CREATED_RECEIPT_BYTES + || response.getCanonicalSelectedPlayerCreatedCharacterReceipt().size() + > MAX_SELECTED_PLAYER_CREATED_BYTES + || !response.getUnknownFields().asMap().isEmpty() || !response.hasRequest() - || !expected.equals(requireRequest(response.getRequest())) || response.getOwnerFence() <= 0 || response.getCanonicalRosterReceipt().size() > MAX_RECEIPT_BYTES) { throw new IllegalArgumentException("Original roster selection owner binding is invalid"); } + if (!expected.equals(response.getRequest())) { + throw new IllegalArgumentException("Original roster selection owner binding is invalid"); + } + boolean hasRoster = + !response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalPlayerCreatedRosterReceipt().isEmpty(); + CanonicalGameplayRosterResponse validatedRoster = hasRoster ? snapshotReceipt(response) : null; switch (response.getState()) { case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RESERVED -> { - if (!response.getCanonicalRosterReceipt().isEmpty()) { + if (hasRoster) { throw new IllegalArgumentException("Reserved original selection cannot carry a receipt"); } } - case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED -> receipt(response); + case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED -> { + if (!hasRoster) snapshotReceipt(response); + } case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_REPLAY_CLOSED -> { if (response.getTerminalOutcome().isEmpty()) { throw new IllegalArgumentException("Closed replay requires original terminal outcome"); } } - case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED -> requireRetirement(response); + case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED -> + requireRetirementValidated(response, expectedTarget); default -> throw new IllegalArgumentException("Unknown original selection state"); } - uuid(response.getTargetFenceUuid()); + if (response.getState() + != CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) { + uuid(response.getTargetFenceUuid()); + } if (!response.getRecoveryUuid().isEmpty()) { uuid(response.getRecoveryUuid()); } @@ -222,7 +510,8 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( if (!response.getSelectedCharacterUuid().isEmpty()) { uuid(response.getSelectedCharacterUuid()); if (!response.hasSelectionInput() - || receipt(response).getActorsList().stream() + || validatedRoster == null + || validatedRoster.getActorsList().stream() .filter( actor -> actor.getCharacterUuid().equals(response.getSelectedCharacterUuid())) .count() @@ -231,18 +520,26 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( "Original chosen actor must occur once in its recorded roster"); } } - if (!response.getCanonicalSelectedAssignmentReceipt().isEmpty()) { + if (!response.getCanonicalSelectedAssignmentReceipt().isEmpty() + || !response.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty()) { if (response.getSelectedCharacterUuid().isEmpty()) { throw new IllegalArgumentException( "Original assignment receipt requires a frozen chosen actor"); } - selectedAssignmentReceipt(response); + if (created) selectedPlayerCreatedCharacterReceipt(response, validatedRoster); + else selectedAssignmentReceipt(response, validatedRoster); } - return response; + return new ValidatedResponse(response, validatedRoster); } + private record ValidatedResponse( + GetCanonicalGameplayRosterReferenceResponse response, + CanonicalGameplayRosterResponse snapshotReceipt) {} + public static CanonicalGameplayRosterResponse receipt( GetCanonicalGameplayRosterReferenceResponse response) { + requirePreseeded(target(requireRequest(response.getRequest()))); + rejectCreatedFields(response); try { ByteString bytes = response.getCanonicalRosterReceipt(); if (bytes.isEmpty() || bytes.size() > MAX_RECEIPT_BYTES) { @@ -250,7 +547,7 @@ public static CanonicalGameplayRosterResponse receipt( } var receipt = CanonicalGameplayRosterResponse.parseFrom(bytes); if (!receipt.getUnknownFields().asMap().isEmpty() - || !bytes.equals(receipt.toByteString()) + || !hasCanonicalEncoding(receipt, bytes) || !receipt .getCanonicalAccountUuid() .equals(response.getRequest().getCanonicalAccountUuid()) @@ -280,6 +577,57 @@ public static CanonicalGameplayRosterResponse receipt( } } + private static void rejectCreatedFields(GetCanonicalGameplayRosterReferenceResponse response) { + if (!response.getCanonicalPlayerCreatedRosterReceipt().isEmpty() + || !response.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty()) { + throw new IllegalArgumentException( + "PRESEEDED_ONLY original cannot carry PLAYER_CREATED receipts"); + } + } + + /** Compares canonical protobuf output byte-for-byte without materializing a second wire value. */ + private static boolean hasCanonicalEncoding(MessageLite message, ByteString bytes) { + if (message.getSerializedSize() != bytes.size()) return false; + ByteString.ByteIterator expected = bytes.iterator(); + final class ComparingOutputStream extends OutputStream { + private long offset; + private boolean matches = true; + + @Override + public void write(int value) { + if (!expected.hasNext()) { + matches = false; + } else if (expected.nextByte() != (byte) value) { + matches = false; + } + offset++; + } + + @Override + public void write(byte[] values, int start, int length) { + for (int index = 0; index < length; index++) { + if (!expected.hasNext()) { + matches = false; + } else if (expected.nextByte() != values[start + index]) { + matches = false; + } + offset++; + } + } + } + + ComparingOutputStream comparison = new ComparingOutputStream(); + try { + CodedOutputStream codedOutput = + CodedOutputStream.newInstance(comparison, CANONICAL_COMPARISON_BUFFER_BYTES); + message.writeTo(codedOutput); + codedOutput.flush(); + return comparison.matches && comparison.offset == bytes.size() && !expected.hasNext(); + } catch (IOException failure) { + throw new IllegalStateException("Unable to compare canonical protobuf", failure); + } + } + public static void requireDereference(GetCanonicalGameplayRosterReferenceResponse response) { requireResponse(response.getRequest(), response); if (!response.getRecoveryUuid().isEmpty() @@ -297,29 +645,30 @@ public static void requireDereference(GetCanonicalGameplayRosterReferenceRespons public static GetCanonicalGameplayRosterReferenceResponse sealRetirement( GetCanonicalGameplayRosterReferenceResponse response) { var unsigned = response.toBuilder().clearRetirementProofDigest().build(); - var sealed = - unsigned.toBuilder().setRetirementProofDigest(digest(unsigned.toByteArray())).build(); + var sealed = unsigned.toBuilder().setRetirementProofDigest(digest(unsigned)).build(); return requireResponse(response.getRequest(), sealed); } public static GetCanonicalGameplayRosterReferenceResponse requireRetirement( GetCanonicalGameplayRosterReferenceResponse response) { - requireRequest(response.getRequest()); + CanonicalGameplayRosterTarget target = requireRequestTarget(response.getRequest()); + return requireRetirementValidated(response, target); + } + + private static GetCanonicalGameplayRosterReferenceResponse requireRetirementValidated( + GetCanonicalGameplayRosterReferenceResponse response, CanonicalGameplayRosterTarget target) { if (!response.getUnknownFields().asMap().isEmpty() || response.getOwnerFence() <= 0 || response.getState() != CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED || !java.util.Set.of("MENU", "SELECTED", "DENIED").contains(response.getTerminalOutcome()) || !response.getSupersedingPointerDigest().matches("[0-9a-f]{64}") - || response.getSupersedingPointerVersion() - <= target(response.getRequest()).getPointerVersion() - || response.getSupersedingCatalogRevision() - < target(response.getRequest()).getCatalogRevision() - || response.getSupersedingWorldEpoch() < target(response.getRequest()).getActiveWorldEpoch() + || response.getSupersedingPointerVersion() <= target.getPointerVersion() + || response.getSupersedingCatalogRevision() < target.getCatalogRevision() + || response.getSupersedingWorldEpoch() < target.getActiveWorldEpoch() || !response .getRetirementProofDigest() - .equals( - digest(response.toBuilder().clearRetirementProofDigest().build().toByteArray()))) { + .equals(digest(response.toBuilder().clearRetirementProofDigest().build()))) { throw new IllegalArgumentException("Complete exact owner retirement proof required"); } uuid(response.getRetirementUuid()); @@ -327,12 +676,20 @@ < target(response.getRequest()).getCatalogRevision() return response; } - private static String digest(byte[] bytes) { + private static String digest(MessageLite message) { try { - return java.util.HexFormat.of() - .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (java.security.NoSuchAlgorithmException unavailable) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (DigestOutputStream digestOutput = + new DigestOutputStream(OutputStream.nullOutputStream(), digest)) { + CodedOutputStream codedOutput = CodedOutputStream.newInstance(digestOutput); + message.writeTo(codedOutput); + codedOutput.flush(); + } + return java.util.HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException unavailable) { throw new IllegalStateException(unavailable); + } catch (IOException failure) { + throw new IllegalStateException("Unable to hash canonical protobuf", failure); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java index b5f3135e87..07a1ebd273 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java @@ -1,11 +1,18 @@ package net.firedevops.firemud.common.world; +import com.google.protobuf.CodedOutputStream; +import com.google.protobuf.MessageLite; +import java.io.IOException; +import java.io.OutputStream; +import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationRequest; @@ -17,6 +24,10 @@ public final class CanonicalGameplayRosterRetirementEvidence { public static final int MAX_REQUEST_BYTES = 128 * 1024; public static final int MAX_RESPONSE_BYTES = 4096; + public static final int MAX_PLAYER_CREATED_REQUEST_BYTES = 195 * 1024 * 1024; + public static final int MAX_CONFIRMATION_BYTES = MAX_REQUEST_BYTES + MAX_RESPONSE_BYTES + 64; + public static final int MAX_PLAYER_CREATED_CONFIRMATION_BYTES = + MAX_PLAYER_CREATED_REQUEST_BYTES + MAX_RESPONSE_BYTES + 64; private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); @@ -27,7 +38,7 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck Objects.requireNonNull(request, "request"); if (request.getSchemaVersion() != 1 || !request.getUnknownFields().asMap().isEmpty() - || request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSerializedSize() > MAX_PLAYER_CREATED_REQUEST_BYTES || !request.hasOriginalSelection() || !request.hasObservedRetirement() || request.getMinimumRetentionMillis() <= 0) { @@ -36,20 +47,30 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck } GetCanonicalGameplayRosterReferenceRequest original = CanonicalGameplayRosterReferenceEvidence.requireRequest(request.getOriginalSelection()); + if (request.getSerializedSize() > acknowledgementLimit(original)) { + throw new IllegalArgumentException( + "Retirement acknowledgement exceeds its policy-specific bound"); + } GetCanonicalGameplayRosterReferenceResponse observed = request.getObservedRetirement(); if (!observed.hasRequest()) { throw new IllegalArgumentException("Complete observed retirement proof required"); } - GetCanonicalGameplayRosterReferenceRequest observedRequest = - CanonicalGameplayRosterReferenceEvidence.requireRequest(observed.getRequest()); - CanonicalGameplayRosterReferenceEvidence.requireResponse(observedRequest, observed); - CanonicalGameplayRosterReferenceEvidence.requireRetirement(observed); + if (observed.getState() + != CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) { + throw new IllegalArgumentException("Complete exact owner retirement proof required"); + } + GetCanonicalGameplayRosterReferenceRequest observedRequest = observed.getRequest(); + CanonicalGameplayRosterResponse observedRoster = + CanonicalGameplayRosterReferenceEvidence.requireResponseSnapshot(observedRequest, observed); CanonicalGameplayRosterRetirementEvidence.uuid(request.getObservationUuid()); CanonicalGameplayRosterRetirementEvidence.uuid(request.getAdmissionUuid()); if (!original.getTargetNamespace().equals(observedRequest.getTargetNamespace()) || !original.getCanonicalAccountUuid().equals(observedRequest.getCanonicalAccountUuid()) - || !original.getCanonicalTarget().equals(observedRequest.getCanonicalTarget())) { + || !original.getCanonicalTarget().equals(observedRequest.getCanonicalTarget()) + || !original + .getCanonicalPlayerCreatedSourceIdentity() + .equals(observedRequest.getCanonicalPlayerCreatedSourceIdentity())) { throw new IllegalArgumentException("Retirement proof changed exact account or target fence"); } boolean sameOperation = original.getOperationUuid().equals(observedRequest.getOperationUuid()); @@ -66,8 +87,12 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck if (hasSnapshotUuid) { CanonicalGameplayRosterReferenceEvidence.uuid(request.getSnapshotUuid()); requireDigest(request.getSnapshotDigest()); - CanonicalGameplayRosterResponse roster = - CanonicalGameplayRosterReferenceEvidence.receipt(observed); + CanonicalGameplayRosterResponse roster = observedRoster; + if (roster == null) { + CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(observed); + throw new IllegalArgumentException( + "Observed retirement does not bind the exact roster snapshot"); + } if (!roster.getSnapshotUuid().equals(request.getSnapshotUuid()) || !roster.getSnapshotDigest().equals(request.getSnapshotDigest()) || !roster.getCanonicalAccountUuid().equals(original.getCanonicalAccountUuid()) @@ -81,7 +106,8 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck // the already validated sealed account/target fence above. } else if (!sameOperation || !original.equals(observedRequest) - || !observed.getCanonicalRosterReceipt().isEmpty()) { + || !observed.getCanonicalRosterReceipt().isEmpty() + || !observed.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { throw new IllegalArgumentException( "Unbound retirement acknowledgement requires its own original proof and no roster receipt"); } @@ -90,41 +116,51 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck public static String requestDigest( CanonicalGameplayRosterRetirementAcknowledgementRequest request) { - return digest(requireAcknowledgement(request).toByteArray()); + return digest(requireAcknowledgement(request)); } public static CanonicalGameplayRosterRetirementAcknowledgementResponse response( CanonicalGameplayRosterRetirementAcknowledgementRequest request, UUID acknowledgementId, long effectiveMinimum) { - requireAcknowledgement(request); + var validatedRequest = requireAcknowledgement(request); requireUuid(acknowledgementId, "acknowledgementId"); - if (effectiveMinimum < request.getMinimumRetentionMillis()) { + if (effectiveMinimum < validatedRequest.getMinimumRetentionMillis()) { throw new IllegalArgumentException( "Effective retention minimum is below the requested minimum"); } - return requireAcknowledgementResponse( - request, + String requestDigest = digest(validatedRequest); + var response = CanonicalGameplayRosterRetirementAcknowledgementResponse.newBuilder() .setSchemaVersion(1) - .setObservationUuid(request.getObservationUuid()) + .setObservationUuid(validatedRequest.getObservationUuid()) .setAcknowledgementUuid(acknowledgementId.toString()) - .setRequestDigest(requestDigest(request)) + .setRequestDigest(requestDigest) .setMinimumRetentionMillis(effectiveMinimum) - .build()); + .build(); + return requireAcknowledgementResponseValidated(validatedRequest, response, requestDigest); } public static CanonicalGameplayRosterRetirementAcknowledgementResponse requireAcknowledgementResponse( CanonicalGameplayRosterRetirementAcknowledgementRequest request, CanonicalGameplayRosterRetirementAcknowledgementResponse response) { - requireAcknowledgement(request); + var validatedRequest = requireAcknowledgement(request); + return requireAcknowledgementResponseValidated( + validatedRequest, response, digest(validatedRequest)); + } + + private static CanonicalGameplayRosterRetirementAcknowledgementResponse + requireAcknowledgementResponseValidated( + CanonicalGameplayRosterRetirementAcknowledgementRequest request, + CanonicalGameplayRosterRetirementAcknowledgementResponse response, + String requestDigest) { Objects.requireNonNull(response, "response"); if (response.getSchemaVersion() != 1 || !response.getUnknownFields().asMap().isEmpty() || response.getSerializedSize() > MAX_RESPONSE_BYTES || !response.getObservationUuid().equals(request.getObservationUuid()) - || !response.getRequestDigest().equals(requestDigest(request)) + || !response.getRequestDigest().equals(requestDigest) || response.getMinimumRetentionMillis() < request.getMinimumRetentionMillis()) { throw new IllegalArgumentException("Retirement acknowledgement response binding is invalid"); } @@ -138,55 +174,89 @@ public static CanonicalGameplayRosterRetirementConfirmationRequest confirmation( CanonicalGameplayRosterRetirementAcknowledgementRequest request, CanonicalGameplayRosterRetirementAcknowledgementResponse response) { requireAcknowledgementResponse(request, response); - return requireConfirmation( + var confirmation = CanonicalGameplayRosterRetirementConfirmationRequest.newBuilder() .setSchemaVersion(1) .setAcknowledgementRequest(request) .setAcknowledgement(response) - .build()); + .build(); + requireConfirmationShape(confirmation); + requireConfirmationPolicyBound(confirmation); + return confirmation; } public static CanonicalGameplayRosterRetirementConfirmationRequest requireConfirmation( CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { + requireConfirmationShape(confirmation); + requireAcknowledgementResponse( + confirmation.getAcknowledgementRequest(), confirmation.getAcknowledgement()); + requireConfirmationPolicyBound(confirmation); + return confirmation; + } + + private static void requireConfirmationShape( + CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { Objects.requireNonNull(confirmation, "confirmation"); if (confirmation.getSchemaVersion() != 1 || !confirmation.getUnknownFields().asMap().isEmpty() - || confirmation.getSerializedSize() > MAX_REQUEST_BYTES + MAX_RESPONSE_BYTES + 64 + || confirmation.getSerializedSize() > MAX_PLAYER_CREATED_CONFIRMATION_BYTES || !confirmation.hasAcknowledgementRequest() || !confirmation.hasAcknowledgement()) { throw new IllegalArgumentException("Closed bounded roster-retirement confirmation required"); } - requireAcknowledgementResponse( - confirmation.getAcknowledgementRequest(), confirmation.getAcknowledgement()); - return confirmation; + } + + private static void requireConfirmationPolicyBound( + CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { + if (confirmation.getSerializedSize() + > acknowledgementLimit(confirmation.getAcknowledgementRequest().getOriginalSelection()) + + MAX_RESPONSE_BYTES + + 64) { + throw new IllegalArgumentException( + "Retirement confirmation exceeds its policy-specific bound"); + } } public static CanonicalGameplayRosterRetirementConfirmationResponse confirmationResponse( CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { - requireConfirmation(confirmation); - return requireConfirmationResponse( - confirmation, + var validatedConfirmation = requireConfirmation(confirmation); + String requestDigest = digest(validatedConfirmation); + var response = CanonicalGameplayRosterRetirementConfirmationResponse.newBuilder() .setSchemaVersion(1) - .setRequestDigest(digest(confirmation.toByteArray())) - .build()); + .setRequestDigest(requestDigest) + .build(); + return requireConfirmationResponseValidated(response, requestDigest); } public static CanonicalGameplayRosterRetirementConfirmationResponse requireConfirmationResponse( CanonicalGameplayRosterRetirementConfirmationRequest confirmation, CanonicalGameplayRosterRetirementConfirmationResponse response) { - requireConfirmation(confirmation); + var validatedConfirmation = requireConfirmation(confirmation); + return requireConfirmationResponseValidated(response, digest(validatedConfirmation)); + } + + private static CanonicalGameplayRosterRetirementConfirmationResponse + requireConfirmationResponseValidated( + CanonicalGameplayRosterRetirementConfirmationResponse response, String requestDigest) { Objects.requireNonNull(response, "response"); if (response.getSchemaVersion() != 1 || !response.getUnknownFields().asMap().isEmpty() || response.getSerializedSize() > MAX_RESPONSE_BYTES - || !response.getRequestDigest().equals(digest(confirmation.toByteArray()))) { + || !response.getRequestDigest().equals(requestDigest)) { throw new IllegalArgumentException("Retirement confirmation response binding is invalid"); } requireDigest(response.getRequestDigest()); return response; } + private static int acknowledgementLimit(GetCanonicalGameplayRosterReferenceRequest original) { + return CanonicalGameplayRosterReferenceEvidence.target(original).getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED + ? MAX_PLAYER_CREATED_REQUEST_BYTES + : MAX_REQUEST_BYTES; + } + private static UUID uuid(String value) { return CanonicalGameplayRosterReferenceEvidence.uuid(value); } @@ -204,11 +274,20 @@ private static void requireDigest(String digest) { } } - private static String digest(byte[] bytes) { + private static String digest(MessageLite message) { try { - return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (DigestOutputStream digestOutput = + new DigestOutputStream(OutputStream.nullOutputStream(), digest)) { + CodedOutputStream codedOutput = CodedOutputStream.newInstance(digestOutput); + message.writeTo(codedOutput); + codedOutput.flush(); + } + return java.util.HexFormat.of().formatHex(digest.digest()); } catch (NoSuchAlgorithmException unavailable) { throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } catch (IOException failure) { + throw new IllegalStateException("Unable to hash canonical protobuf", failure); } } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidence.java new file mode 100644 index 0000000000..df9618303b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidence.java @@ -0,0 +1,552 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Pure validation and digest functions for the PLAYER_CREATED roster wire values. */ +public final class CanonicalPlayerCreatedRosterEvidence { + public static final int MAX_REQUEST_BYTES = 16 * 1024; + public static final int MAX_SOURCE_IDENTITY_BYTES = 4096; + public static final int MAX_ROSTER_RECEIPT_BYTES = 66 * 1024; + public static final int MAX_TERMINAL_BYTES = 192 * 1024 * 1024; + public static final int MAX_SELECTED_RECEIPT_BYTES = 193 * 1024 * 1024; + + private static final int MAX_ORIGINAL_REQUEST_BYTES = 16 * 1024; + private static final int MAX_ACCOUNT_ORIGINAL_RESPONSE_BYTES = 36 * 1024 * 1024; + private static final int MAX_SOURCE_READBACK_BYTES = 32 * 1024 * 1024; + private static final int MAX_ACCOUNT_PROTECTION_BYTES = 40 * 1024 * 1024; + private static final int MAX_GAME_SESSION_PROTECTION_BYTES = 48 * 1024 * 1024; + private static final int MAX_WORLD_PROTECTION_BYTES = 48 * 1024 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SLUG = Pattern.compile("[a-z0-9][a-z0-9-]{0,63}"); + private static final String SNAPSHOT_DOMAIN = "firemud.entity.player-created-roster.v1"; + + private CanonicalPlayerCreatedRosterEvidence() {} + + public static CanonicalPlayerCreatedRosterSourceIdentity requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity source) { + Objects.requireNonNull(source, "source"); + if (source.getSerializedSize() > MAX_SOURCE_IDENTITY_BYTES + || !source.getUnknownFields().asMap().isEmpty() + || source.getSchemaVersion() != 1 + || !SHA256.matcher(source.getDescriptorDigest()).matches() + || !SHA256.matcher(source.getAuthoredBindingDigest()).matches()) { + throw new IllegalArgumentException("Closed bounded PLAYER_CREATED source identity required"); + } + uuid(source.getDescriptorUuid()); + uuid(source.getDescriptorRevisionUuid()); + uuid(source.getAuthoredBindingUuid()); + return source; + } + + public static CanonicalPlayerCreatedRosterRequest requireRequest( + CanonicalPlayerCreatedRosterRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasExpectedTarget() + || !request.hasPlayerExecutionContext() + || !request.hasExpectedSource()) { + throw new IllegalArgumentException("Closed bounded PLAYER_CREATED roster request required"); + } + uuid(request.getRequestUuid()); + uuid(request.getCanonicalAccountUuid()); + CanonicalGameplayRosterTarget target = requireTarget(request.getExpectedTarget()); + requireSourceIdentity(request.getExpectedSource()); + requireContext( + request.getPlayerExecutionContext(), + request.getRequestUuid(), + request.getCanonicalAccountUuid(), + target, + null); + return request; + } + + public static CanonicalPlayerCreatedRosterResponse requireResponse( + CanonicalPlayerCreatedRosterRequest expected, CanonicalPlayerCreatedRosterResponse response) { + requireRequest(expected); + Objects.requireNonNull(response, "response"); + if (response.getSerializedSize() > MAX_ROSTER_RECEIPT_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRoster() + || !response.hasSourceIdentity()) { + throw new IllegalArgumentException("Complete bounded PLAYER_CREATED roster receipt required"); + } + CanonicalPlayerCreatedRosterSourceIdentity source = + requireSourceIdentity(response.getSourceIdentity()); + if (!expected.getExpectedSource().equals(source)) { + throw new IllegalArgumentException("PLAYER_CREATED roster source identity changed"); + } + CanonicalGameplayRosterResponse roster = response.getRoster(); + if (roster.getSerializedSize() > MAX_ROSTER_RECEIPT_BYTES + || !roster.getUnknownFields().asMap().isEmpty() + || !roster.getCanonicalAccountUuid().equals(expected.getCanonicalAccountUuid()) + || !roster.hasTarget() + || !roster.getTarget().equals(expected.getExpectedTarget()) + || !DIGEST.matcher(roster.getSnapshotDigest()).matches() + || roster.getActorsCount() > 100) { + throw new IllegalArgumentException("PLAYER_CREATED roster binding or bounds are invalid"); + } + uuid(roster.getSnapshotUuid()); + Set actors = new HashSet<>(); + for (CanonicalGameplayRosterActor actor : roster.getActorsList()) { + if (!actor.getUnknownFields().asMap().isEmpty() + || !actors.add(uuid(actor.getCharacterUuid())) + || actor.getActorKind() + != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER + || !validDisplayName(actor.getDisplayName())) { + throw new IllegalArgumentException("Closed unique PLAYER actor roster required"); + } + } + String recomputed = + computeSnapshotDigest( + expected.getCanonicalAccountUuid(), + expected.getExpectedTarget(), + source, + roster.getActorsList()); + if (!recomputed.equals(roster.getSnapshotDigest())) { + throw new IllegalArgumentException("PLAYER_CREATED roster snapshot digest changed"); + } + return response; + } + + public static CanonicalSelectedPlayerCreatedCharacterRequest requireSelectedRequest( + CanonicalSelectedPlayerCreatedCharacterRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasExpectedTarget() + || !request.hasExpectedSnapshot() + || !request.hasPlayerExecutionContext() + || !request.hasExpectedSource()) { + throw new IllegalArgumentException("Closed bounded selected PLAYER_CREATED request required"); + } + uuid(request.getRequestUuid()); + uuid(request.getCanonicalAccountUuid()); + UUID selected = uuid(request.getSelectedCharacterUuid()); + CanonicalGameplayRosterTarget target = requireTarget(request.getExpectedTarget()); + requireSourceIdentity(request.getExpectedSource()); + if (!request.getExpectedSnapshot().getUnknownFields().asMap().isEmpty() + || !DIGEST.matcher(request.getExpectedSnapshot().getSnapshotDigest()).matches()) { + throw new IllegalArgumentException("Exact canonical roster snapshot reference required"); + } + uuid(request.getExpectedSnapshot().getSnapshotUuid()); + requireContext( + request.getPlayerExecutionContext(), + request.getRequestUuid(), + request.getCanonicalAccountUuid(), + target, + selected); + return request; + } + + /** + * Validates pure selected-created wire values and bindings; this does not authenticate owners or + * establish creation authority. + */ + public static CanonicalSelectedPlayerCreatedCharacterResponse requireSelectedResponse( + CanonicalSelectedPlayerCreatedCharacterRequest expected, + CanonicalSelectedPlayerCreatedCharacterResponse response) { + requireSelectedRequest(expected); + Objects.requireNonNull(response, "response"); + if (response.getSerializedSize() > MAX_SELECTED_RECEIPT_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasTarget() + || !response.hasSnapshot() + || !response.hasSourceIdentity() + || !response.hasTerminal() + || !response.getRequestUuid().equals(expected.getRequestUuid()) + || !response.getCanonicalAccountUuid().equals(expected.getCanonicalAccountUuid()) + || !response.getSelectedCharacterUuid().equals(expected.getSelectedCharacterUuid())) { + throw new IllegalArgumentException( + "Complete bounded selected PLAYER_CREATED receipt required"); + } + CanonicalGameplayRosterTarget target = requireTarget(response.getTarget()); + CanonicalPlayerCreatedRosterSourceIdentity source = + requireSourceIdentity(response.getSourceIdentity()); + CanonicalGameplayRosterSnapshotReference snapshot = response.getSnapshot(); + if (!target.equals(expected.getExpectedTarget()) + || !snapshot.equals(expected.getExpectedSnapshot()) + || !source.equals(expected.getExpectedSource())) { + throw new IllegalArgumentException("Selected PLAYER_CREATED receipt binding changed"); + } + + uuid(response.getCreationOperationUuid()); + if (!DIGEST.matcher(response.getMutationDigest()).matches()) { + throw new IllegalArgumentException("Canonical selected creation mutation digest required"); + } + + EntityCharacterCreateTerminal terminal = response.getTerminal(); + if (terminal.getSerializedSize() > MAX_TERMINAL_BYTES + || !terminal.getUnknownFields().asMap().isEmpty() + || !terminal.hasOriginalRequest() + || !terminal.hasAccountOriginal() + || terminal.getOriginalAccountProtection().isEmpty() + || terminal.getOriginalAccountProtection().size() > MAX_ACCOUNT_PROTECTION_BYTES + || terminal.getOriginalGameSessionProtection().isEmpty() + || terminal.getOriginalGameSessionProtection().size() > MAX_GAME_SESSION_PROTECTION_BYTES + || terminal.getOriginalWorldProtection().isEmpty() + || terminal.getOriginalWorldProtection().size() > MAX_WORLD_PROTECTION_BYTES + || terminal.getOutcome() + != EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED + || !terminal.getCharacterId().equals(expected.getSelectedCharacterUuid()) + || terminal.getTerminalFence() != 1L + || !terminal.getAbortRequestId().isEmpty()) { + throw new IllegalArgumentException("Complete committed selected creation terminal required"); + } + uuid(terminal.getTerminalId()); + canonicalInstant(terminal.getCompletedAt()); + uuid(terminal.getEntityIntakeRequestId()); + if (!SHA256.matcher(terminal.getEntitySourceReceiptDigest()).matches()) { + throw new IllegalArgumentException("Canonical Entity source receipt digest required"); + } + requireOriginalCommit(terminal.getOriginalRequest()); + ReadOriginalCharacterCreateResponse accountOriginal = terminal.getAccountOriginal(); + requireAccountOriginal( + accountOriginal, + terminal.getOriginalRequest().getOriginal(), + expected.getCanonicalAccountUuid(), + response.getCreationOperationUuid(), + response.getMutationDigest()); + + byte[] originalActionBytes = accountOriginal.getOriginalAction().toByteArray(); + CharacterCreateOperatorAction action = + CharacterCreateOperatorActionCodec.decode(originalActionBytes); + if (!Arrays.equals(originalActionBytes, CharacterCreateOperatorActionCodec.encode(action)) + || !response + .getMutationDigest() + .equals(CharacterCreateOperatorActionCodec.mutationDigest(action)) + || !action + .scope() + .targetNamespace() + .equals(terminal.getOriginalRequest().getOriginal().getTargetNamespace())) { + throw new IllegalArgumentException("Original CHARACTER_CREATE action is not canonical"); + } + requireCreatedActionBinding(action, target, source, expected.getCanonicalAccountUuid()); + return response; + } + + private static void requireOriginalCommit(CommitProtectedCharacterCreateRequest request) { + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSerializedSize() > MAX_ORIGINAL_REQUEST_BYTES + || !request.hasOriginal() + || !request.hasAccountProtection() + || !request.hasGameSessionProtection() + || !request.hasWorldProtection()) { + throw new IllegalArgumentException("Complete bounded original creation references required"); + } + var original = request.getOriginal(); + if (!original.getUnknownFields().asMap().isEmpty() + || original.getSerializedSize() > MAX_ORIGINAL_REQUEST_BYTES + || !net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace( + original.getTargetNamespace())) { + throw new IllegalArgumentException("Canonical original creation request required"); + } + uuid(original.getOperationId()); + if (!DIGEST.matcher(original.getMutationDigest()).matches()) { + throw new IllegalArgumentException("Canonical original creation digest required"); + } + requireProtectionReference(request.getAccountProtection()); + requireProtectionReference(request.getGameSessionProtection()); + requireProtectionReference(request.getWorldProtection()); + } + + private static void requireProtectionReference(CharacterCreateProtectionReference reference) { + if (!reference.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed original creation protection reference required"); + } + uuid(reference.getProtectionId()); + if (reference.getProtectionFence() <= 0L) { + throw new IllegalArgumentException("Positive original creation protection fence required"); + } + } + + private static void requireAccountOriginal( + ReadOriginalCharacterCreateResponse original, + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest request, + String expectedAccount, + String expectedOperation, + String expectedDigest) { + if (!original.getUnknownFields().asMap().isEmpty() + || original.getSerializedSize() > MAX_ACCOUNT_ORIGINAL_RESPONSE_BYTES + || original.getOriginalAction().isEmpty() + || original.getOriginalAction().size() > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + || original.getOriginalSourceReadback().isEmpty() + || original.getOriginalSourceReadback().size() > MAX_SOURCE_READBACK_BYTES + || !original.getTargetNamespace().equals(request.getTargetNamespace()) + || !original.getOperationId().equals(expectedOperation) + || !original.getMutationDigest().equals(expectedDigest) + || !"CHARACTER_CREATE".equals(original.getPurpose()) + || !original.getAuthenticatedAccountId().equals(expectedAccount)) { + throw new IllegalArgumentException("Exact bounded Account creation source required"); + } + uuid(original.getCreateCharacterRequestId()); + requireConnectScope(original.getConnectScopeId()); + if (!request.getOperationId().equals(original.getOperationId()) + || !request.getMutationDigest().equals(original.getMutationDigest())) { + throw new IllegalArgumentException("Account source differs from original request identity"); + } + } + + private static void requireConnectScope(String value) { + if (value.isBlank() + || value.length() > 2048 + || value.indexOf(0) >= 0 + || !StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException("Bounded original creation connect scope required"); + } + } + + private static void requireCreatedActionBinding( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + String accountUuid) { + var scope = action.scope(); + var actionTarget = action.target(); + var mutation = action.mutation(); + var catalog = mutation.catalog(); + var authored = mutation.authoredSource(); + if (!scope.tenantId().equals(target.getTenantUuid()) + || !scope.playableStateNamespaceId().equals(target.getPlayableStateNamespaceUuid()) + || scope.playableStateScope() + != CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || !actionTarget.accountId().equals(accountUuid) + || !actionTarget.realmId().equals(target.getRealmUuid()) + || !actionTarget.worldSlug().equals(target.getWorldSlug()) + || !actionTarget.realmSlug().equals(target.getRealmSlug()) + || !actionTarget.versionId().equals(target.getCanonicalVersionUuid()) + || !authored.canonicalTenantId().equals(target.getTenantUuid()) + || !authored.canonicalVersionId().equals(target.getCanonicalVersionUuid()) + || !authored.worldSlug().equals(target.getWorldSlug()) + || !catalog.tenantId().equals(target.getTenantUuid()) + || !catalog.realmId().equals(target.getRealmUuid()) + || !catalog.worldSlug().equals(target.getWorldSlug()) + || !catalog.realmSlug().equals(target.getRealmSlug()) + || !catalog.playableStateNamespaceId().equals(target.getPlayableStateNamespaceUuid()) + || !"SHARED".equals(catalog.stateScope()) + || !"PLAYER_CREATED".equals(catalog.characterCreationPolicy()) + || !authored.bindingId().equals(source.getAuthoredBindingUuid()) + || !authored.bindingDigest().equals(source.getAuthoredBindingDigest())) { + throw new IllegalArgumentException( + "Original creation durable target or authored binding changed"); + } + PlayerCreationDescriptor descriptor = + PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); + if (!descriptor.descriptorId().equals(source.getDescriptorUuid()) + || !descriptor.descriptorRevisionId().equals(source.getDescriptorRevisionUuid()) + || !descriptor.digest().equals(source.getDescriptorDigest()) + || !authored.descriptor().digest().equals(source.getDescriptorDigest())) { + throw new IllegalArgumentException("Original creation descriptor identity changed"); + } + } + + private static void canonicalInstant(String value) { + try { + if (!java.time.Instant.parse(value).toString().equals(value)) { + throw new IllegalArgumentException("Canonical creation terminal timestamp required"); + } + } catch (java.time.DateTimeException malformed) { + throw new IllegalArgumentException( + "Canonical creation terminal timestamp required", malformed); + } + } + + public static String computeSnapshotDigest( + String account, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + List orderedActors) { + uuid(account); + CanonicalGameplayRosterTarget canonicalTarget = requireTarget(target); + CanonicalPlayerCreatedRosterSourceIdentity canonicalSource = requireSourceIdentity(source); + Objects.requireNonNull(orderedActors, "orderedActors"); + if (orderedActors.size() > 100) { + throw new IllegalArgumentException("PLAYER_CREATED roster exceeds 100 actors"); + } + Set actors = new HashSet<>(); + for (CanonicalGameplayRosterActor actor : orderedActors) { + Objects.requireNonNull(actor, "actor"); + if (!actor.getUnknownFields().asMap().isEmpty() + || !actors.add(uuid(actor.getCharacterUuid())) + || actor.getActorKind() + != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER + || !validDisplayName(actor.getDisplayName())) { + throw new IllegalArgumentException("Closed unique PLAYER actor roster required"); + } + } + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream output = new DataOutputStream(bytes); + writeUtf8(output, SNAPSHOT_DOMAIN); + writeUtf8(output, account); + writeBytes(output, canonicalTarget.toByteArray()); + writeBytes(output, canonicalSource.toByteArray()); + output.writeInt(orderedActors.size()); + for (CanonicalGameplayRosterActor actor : orderedActors) { + writeUtf8(output, actor.getCharacterUuid()); + writeUtf8(output, actor.getDisplayName()); + } + output.flush(); + return java.util.HexFormat.of().formatHex(sha256(bytes.toByteArray())); + } catch (IOException impossible) { + throw new IllegalStateException("In-memory roster digest encoding failed", impossible); + } + } + + private static CanonicalGameplayRosterTarget requireTarget(CanonicalGameplayRosterTarget target) { + Objects.requireNonNull(target, "target"); + if (!target.getUnknownFields().asMap().isEmpty() + || target.getCatalogRevision() <= 0 + || target.getPointerVersion() <= 0 + || target.getActiveWorldEpoch() <= 0 + || target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED + || !SLUG.matcher(target.getWorldSlug()).matches() + || !SLUG.matcher(target.getRealmSlug()).matches() + || !DIGEST.matcher(target.getPublishedPolicyDigest()).matches() + || !DIGEST.matcher(target.getAdmissionPointerSnapshotDigest()).matches() + || !DIGEST.matcher(target.getPublishedOwnerProofDigest()).matches() + || target.getPublishedReleaseBundleRef().isBlank() + || target.getPublishedReleaseBundleRef().length() > 1024 + || !target + .getPublishedReleaseBundleRef() + .equals(target.getPublishedReleaseBundleRef().trim()) + || target.getPublishedReleaseBundleRef().codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Complete SHARED PLAYER_CREATED target required"); + } + uuid(target.getTenantUuid()); + uuid(target.getRealmUuid()); + uuid(target.getGameInstanceUuid()); + uuid(target.getCanonicalVersionUuid()); + uuid(target.getPlayableStateNamespaceUuid()); + return target; + } + + private static void requireContext( + PlayerExecutionContext context, + String requestUuid, + String accountUuid, + CanonicalGameplayRosterTarget target, + UUID selectedCharacter) { + if (!context.getUnknownFields().asMap().isEmpty() + || !context.getAccountId().equals(accountUuid) + || !context.getRequestId().equals(requestUuid) + || !context.getTenantId().equals(target.getTenantUuid()) + || !context.getRealmId().equals(target.getRealmUuid()) + || !context.getPlayableStateNamespaceId().equals(target.getPlayableStateNamespaceUuid()) + || !context.getGameInstanceId().equals(target.getGameInstanceUuid()) + || !context.getPlayableStateScope().equals("SHARED") + || (selectedCharacter == null && !context.getCharacterId().isEmpty()) + || (selectedCharacter != null + && !context.getCharacterId().equals(selectedCharacter.toString()))) { + throw new IllegalArgumentException( + "Player execution context does not match exact request target"); + } + uuid(context.getAccountId()); + uuid(context.getRequestId()); + uuid(context.getTenantId()); + uuid(context.getRealmId()); + uuid(context.getPlayableStateNamespaceId()); + uuid(context.getGameInstanceId()); + uuid(context.getSessionId()); + if (selectedCharacter != null) uuid(context.getCharacterId()); + } + + private static UUID uuid(String value) { + Objects.requireNonNull(value, "uuid"); + if (!UUID_PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + UUID parsed = UUID.fromString(value); + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + return parsed; + } + + private static boolean validDisplayName(String value) { + if (value.isBlank() + || !value.equals(value.trim()) + || value.codePointCount(0, value.length()) > 100 + || value.codePoints().anyMatch(Character::isISOControl)) { + return false; + } + try { + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(value)); + return true; + } catch (CharacterCodingException malformed) { + return false; + } + } + + private static void writeUtf8(DataOutputStream output, String value) throws IOException { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + writeBytes(output, bytes); + } + + private static void writeBytes(DataOutputStream output, byte[] bytes) throws IOException { + output.writeInt(bytes.length); + output.write(bytes); + } + + private static byte[] sha256(byte[] input) { + try { + return MessageDigest.getInstance("SHA-256").digest(input); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } +} diff --git a/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 89624a3ff9..f8eea3ce77 100644 --- a/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1 +1,2 @@ net.firedevops.firemud.common.config.CommonCoreAutoConfiguration +net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshallerTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshallerTest.java new file mode 100644 index 0000000000..db73d0dbc2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshallerTest.java @@ -0,0 +1,356 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class BoundedGrpcRequestMarshallerTest { + private static final Context.Key CONTEXT = Context.key("bounded-admission-test"); + + @Test + void exactUnknownLengthBoundaryParsesThenPreservesContextResponseAndLifecycle() { + var harness = new Harness(false); + harness.deliver( + new ByteArrayInputStream(new byte[8]) { + @Override + public int available() { + throw new AssertionError("available is not admission"); + } + }); + assertThat(harness.parses).hasValue(1); + harness.listener.onHalfClose(); + harness.listener.onComplete(); + assertThat(harness.events) + .containsExactly( + "start:identity", "message:identity", "half-close:identity", "complete:identity"); + assertThat(harness.call.closed).extracting(Status::getCode).containsExactly(Status.Code.OK); + assertThat(harness.call.response).isEqualTo(new byte[] {1, 2, 3}); + assertThat(harness.originalDescriptorObserved).isTrue(); + assertThat(harness.originalHeadersObserved).isTrue(); + } + + @Test + void chunkedReplayPreservesExactBytesAcrossFullChunksAndPartialTail() { + byte[] expected = new byte[2 * 64 * 1024 + 17]; + for (int index = 0; index < expected.length; index++) { + expected[index] = (byte) (index % 251); + } + var harness = new Harness(false, expected.length); + harness.deliver( + new ByteArrayInputStream(expected) { + @Override + public int available() { + throw new AssertionError("available is not admission"); + } + }); + assertThat(harness.parses).hasValue(1); + assertThat(harness.received).isEqualTo(expected); + harness.listener.onHalfClose(); + assertThat(harness.call.closed).extracting(Status::getCode).containsExactly(Status.Code.OK); + } + + @Test + void overflowAcrossChunkBoundaryStillStopsAtSentinelBeforeOriginalParser() { + int maximum = 64 * 1024 + 17; + var harness = new Harness(false, maximum); + AtomicInteger reads = new AtomicInteger(); + harness.deliver( + new InputStream() { + @Override + public int read() { + reads.incrementAndGet(); + return 255; + } + }); + harness.listener.onHalfClose(); + assertThat(reads).hasValue(maximum + 1); + assertThat(harness.parses).hasValue(0); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.RESOURCE_EXHAUSTED); + assertThat(harness.events).containsExactly("start:identity"); + } + + @Test + void oversizedMalformedUnknownLengthClosesExplicitlyWithoutParserOrOwnerDispatch() { + var harness = new Harness(false); + AtomicInteger reads = new AtomicInteger(); + harness.deliver( + new InputStream() { + @Override + public int read() { + reads.incrementAndGet(); + return 255; + } + + @Override + public int available() { + return 0; + } + }); + assertThat(reads).hasValue(9); + assertThat(harness.parses).hasValue(0); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.RESOURCE_EXHAUSTED); + harness.deliver(new ByteArrayInputStream(new byte[8])); + harness.listener.onHalfClose(); + harness.listener.onReady(); + harness.listener.onCancel(); + harness.listener.onCancel(); + harness.listener.onComplete(); + assertThat(harness.events).containsExactly("start:identity", "cancel:identity"); + assertThat(harness.call.closed).hasSize(1); + assertThat(harness.parses).hasValue(0); + } + + @Test + void readFailureClosesInternalAndTerminalCompleteStillCleansUpOnce() { + var harness = new Harness(false); + harness.deliver( + new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("broken transport"); + } + }); + harness.listener.onHalfClose(); + harness.listener.onComplete(); + harness.listener.onComplete(); + harness.listener.onCancel(); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.INTERNAL); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity", "complete:identity"); + } + + @Test + void decompressionOrTransportStatusDuringReadIsClosedExplicitly() { + var harness = new Harness(false); + harness.deliver( + new InputStream() { + @Override + public int read() { + throw Status.RESOURCE_EXHAUSTED + .withDescription("transport decompression bound") + .asRuntimeException(); + } + }); + harness.listener.onHalfClose(); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.RESOURCE_EXHAUSTED); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity"); + } + + @Test + void cancellationSuppressesReadAndHalfCloseAndForwardsCleanupOnce() { + var harness = new Harness(false); + harness.call.cancelled = true; + harness.deliver( + new InputStream() { + @Override + public int read() { + throw new AssertionError("cancelled request must not be read"); + } + }); + harness.listener.onHalfClose(); + harness.listener.onReady(); + harness.listener.onCancel(); + harness.listener.onCancel(); + harness.listener.onComplete(); + assertThat(harness.call.closed).isEmpty(); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity", "cancel:identity"); + } + + @Test + void existingHandlerRejectionBeforeMessagesRetainsItsStatusAndPreventsParsing() { + var harness = new Harness(true); + harness.deliver( + new InputStream() { + @Override + public int read() { + throw new AssertionError("denied request must not be read"); + } + }); + harness.listener.onHalfClose(); + harness.listener.onComplete(); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.PERMISSION_DENIED); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity", "complete:identity"); + } + + private static final class Harness { + private final AtomicInteger parses = new AtomicInteger(); + private final List events = new ArrayList<>(); + private final RecordingCall call = new RecordingCall(); + private final ServerCall.Listener listener; + private boolean originalDescriptorObserved; + private boolean originalHeadersObserved; + private byte[] received; + + private Harness(boolean rejectAtStart) { + this(rejectAtStart, 8); + } + + @SuppressWarnings("unchecked") + private Harness(boolean rejectAtStart, int maximum) { + MethodDescriptor original = + MethodDescriptor.newBuilder() + .setFullMethodName("test.Bounded/Read") + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(parser(parses)) + .setResponseMarshaller(parser(new AtomicInteger())) + .build(); + Metadata headers = new Metadata(); + ServerCallHandler handler = + (observedCall, observedHeaders) -> { + events.add("start:" + CONTEXT.get()); + originalDescriptorObserved = observedCall.getMethodDescriptor() == original; + originalHeadersObserved = observedHeaders == headers; + if (rejectAtStart) { + observedCall.close(Status.PERMISSION_DENIED, new Metadata()); + } + return new ServerCall.Listener<>() { + @Override + public void onMessage(byte[] message) { + received = message; + events.add("message:" + CONTEXT.get()); + } + + @Override + public void onHalfClose() { + events.add("half-close:" + CONTEXT.get()); + observedCall.sendHeaders(new Metadata()); + observedCall.sendMessage(new byte[] {1, 2, 3}); + observedCall.close(Status.OK, new Metadata()); + } + + @Override + public void onReady() { + events.add("ready:" + CONTEXT.get()); + } + + @Override + public void onCancel() { + events.add("cancel:" + CONTEXT.get()); + } + + @Override + public void onComplete() { + events.add("complete:" + CONTEXT.get()); + } + }; + }; + var service = + ServerServiceDefinition.builder("test.Bounded").addMethod(original, handler).build(); + service = + ServerInterceptors.intercept( + service, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall observedCall, + Metadata observedHeaders, + ServerCallHandler next) { + return Contexts.interceptCall( + Context.current().withValue(CONTEXT, "identity"), + observedCall, + observedHeaders, + next); + } + }); + var policy = + new GrpcRequestBytePolicy( + List.of(new GrpcRequestBytePolicy.MethodBound(original, maximum))); + var guarded = policy.guard(service, GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + var method = + (ServerMethodDefinition) + guarded.getMethod(original.getFullMethodName()); + call.method = method.getMethodDescriptor(); + listener = method.getServerCallHandler().startCall(call, headers); + } + + private void deliver(InputStream message) { + listener.onMessage(call.method.parseRequest(message)); + } + } + + private static final class RecordingCall extends ServerCall { + private MethodDescriptor method; + private final List closed = new ArrayList<>(); + private boolean cancelled; + private byte[] response; + + @Override + public void request(int count) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(InputStream message) { + try { + response = message.readAllBytes(); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } + + @Override + public void close(Status status, Metadata trailers) { + closed.add(status); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return method; + } + } + + static MethodDescriptor.Marshaller parser(AtomicInteger parses) { + return new MethodDescriptor.Marshaller<>() { + @Override + public InputStream stream(byte[] bytes) { + return new ByteArrayInputStream(bytes); + } + + @Override + public byte[] parse(InputStream stream) { + parses.incrementAndGet(); + try { + return stream.readAllBytes(); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } + }; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java new file mode 100644 index 0000000000..fcb12fc070 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.CallOptions; +import io.grpc.HandlerRegistry; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.TlsServerCredentials; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.stub.ClientCalls; +import io.grpc.stub.ServerCalls; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class BoundedGrpcServerFactoryTest { + private static final int ORDINARY = GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES; + + @Test + void rejectsDuplicateUnknownAndNonidenticalDescriptorConfiguration() { + var method = method("test.Owner/Read", new AtomicInteger()); + assertThatThrownBy( + () -> + new GrpcRequestBytePolicy( + List.of( + new GrpcRequestBytePolicy.MethodBound(method, 1024), + new GrpcRequestBytePolicy.MethodBound(method, 1024)))) + .isInstanceOf(IllegalArgumentException.class); + var policy = + new GrpcRequestBytePolicy( + List.of(new GrpcRequestBytePolicy.MethodBound(method, ORDINARY + 1024))); + var factory = factory(policy); + factory.addService(service(method.toBuilder().build())); + assertThatThrownBy(factory::createServer).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> factory(policy).createServer()) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void refusesAnUnwrappedServiceAddedByCustomizer() { + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of( + builder -> + builder.addService(service(method("test.Bypass/Read", new AtomicInteger())))), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + new GrpcRequestBytePolicy(List.of()), + ORDINARY); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unguarded gRPC method"); + } + + @Test + void refusesAnExternallyGuardedDescriptorWhoseHandlerWasReplaced() { + var policy = GrpcRequestBytePolicy.ordinary(); + var external = policy.guard(service(method("test.Bypass/Read", new AtomicInteger())), ORDINARY); + var replaced = + io.grpc.ServerInterceptors.intercept( + external, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + return new io.grpc.ServerCall.Listener<>() {}; + } + }); + assertThat(replaced.getMethod("test.Bypass/Read").getMethodDescriptor()) + .isSameAs(external.getMethod("test.Bypass/Read").getMethodDescriptor()); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(builder -> builder.addService(replaced)), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + policy, + ORDINARY); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unguarded gRPC method"); + } + + @Test + void mtlsCompressedOrdinaryAndFutureMethodsRejectBeforeParserAndFallbackCannotBypass( + @TempDir Path directory) throws Exception { + var pki = + LoopbackMtlsTestPki.create( + directory, + "bounded factory test CA", + new IdentitySpec("server", "spiffe://firemud/ns/test/sa/game-session-service", true), + new IdentitySpec( + "entity", "spiffe://firemud/ns/test/sa/entity-management-service", false)); + var serverIdentity = pki.identity("server"); + var ordinaryParses = new AtomicInteger(); + var exceptionalParses = new AtomicInteger(); + var futureParses = new AtomicInteger(); + var ordinary = method("test.Owner/Ordinary", ordinaryParses); + var exceptional = method("test.Owner/Exceptional", exceptionalParses); + var future = method("test.Owner/Future", futureParses); + var unknown = method("test.Unknown/Read", new AtomicInteger()); + var policy = + new GrpcRequestBytePolicy( + List.of(new GrpcRequestBytePolicy.MethodBound(exceptional, ORDINARY + 1024))); + var fallbackCalls = new AtomicInteger(); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of( + builder -> { + builder.fallbackHandlerRegistry( + new HandlerRegistry() { + @Override + public ServerMethodDefinition lookupMethod( + String method, String authority) { + fallbackCalls.incrementAndGet(); + return service(unknown).getMethod(method); + } + }); + }), + pki.keyManagerFactory(serverIdentity), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + policy, + explicitTransportMaximum(policy)); + factory.addService( + ServerServiceDefinition.builder("test.Owner") + .addMethod(ordinary, handler()) + .addMethod(exceptional, handler()) + .addMethod(future, handler()) + .build()); + Server server = factory.createServer().start(); + var clientIdentity = pki.identity("entity"); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(clientIdentity.privateKey(), clientIdentity.certificate()) + .build()) + .build(); + ManagedChannel noCertificate = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .sslContext(GrpcSslContexts.forClient().trustManager(pki.caCertificate()).build()) + .build(); + try { + var options = + CallOptions.DEFAULT.withDeadlineAfter(10, TimeUnit.SECONDS).withCompression("gzip"); + assertThat(ClientCalls.blockingUnaryCall(channel, ordinary, options, new byte[ORDINARY])) + .isEmpty(); + assertThat(ordinaryParses).hasValue(1); + byte[] bytes = new byte[ORDINARY + 1]; + assertThat(ClientCalls.blockingUnaryCall(channel, exceptional, options, bytes)).isEmpty(); + assertThat(exceptionalParses).hasValue(1); + // Response parsing uses a separate counter; these counters observe server request parsing. + assertRejected(channel, ordinary, options, bytes, Status.Code.RESOURCE_EXHAUSTED); + assertRejected(channel, future, options, bytes, Status.Code.RESOURCE_EXHAUSTED); + assertThat(ordinaryParses).hasValue(1); + assertThat(futureParses).hasValue(0); + assertRejected(channel, unknown, options, bytes, Status.Code.UNIMPLEMENTED); + assertThat(fallbackCalls).hasValue(0); + assertRejected( + channel, + exceptional, + options, + new byte[policy.transportMaximumBytes() + 1], + Status.Code.RESOURCE_EXHAUSTED); + assertThat(exceptionalParses).hasValue(1); + assertThatThrownBy( + () -> + ClientCalls.blockingUnaryCall( + noCertificate, + ordinary, + CallOptions.DEFAULT.withDeadlineAfter(3, TimeUnit.SECONDS), + new byte[0])) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).isOk()).isFalse()); + assertThat(ordinaryParses).hasValue(1); + } finally { + channel.shutdownNow(); + noCertificate.shutdownNow(); + server.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + assertThat(noCertificate.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void assertRejected( + ManagedChannel channel, + MethodDescriptor method, + CallOptions options, + byte[] bytes, + Status.Code code) { + assertThatThrownBy(() -> ClientCalls.blockingUnaryCall(channel, method, options, bytes)) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static int explicitTransportMaximum(GrpcRequestBytePolicy policy) { + var properties = + new org.springframework.boot.context.properties.bind.Binder( + new org.springframework.boot.context.properties.source + .MapConfigurationPropertySource( + java.util.Map.of( + "spring.grpc.server.max-inbound-message-size", + policy.transportMaximumBytes() + "B"))) + .bind( + "spring.grpc.server", + org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties.class) + .get(); + return Math.toIntExact(properties.getMaxInboundMessageSize().toBytes()); + } + + private static BoundedGrpcServerFactory factory(GrpcRequestBytePolicy policy) { + return new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + policy, + explicitTransportMaximum(policy)); + } + + private static MethodDescriptor method(String name, AtomicInteger parses) { + return MethodDescriptor.newBuilder() + .setFullMethodName(name) + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(BoundedGrpcRequestMarshallerTest.parser(parses)) + .setResponseMarshaller(BoundedGrpcRequestMarshallerTest.parser(new AtomicInteger())) + .build(); + } + + private static io.grpc.ServerCallHandler handler() { + return ServerCalls.asyncUnaryCall( + (request, observer) -> { + observer.onNext(new byte[0]); + observer.onCompleted(); + }); + } + + private static ServerServiceDefinition service(MethodDescriptor method) { + return ServerServiceDefinition.builder( + MethodDescriptor.extractFullServiceName(method.getFullMethodName())) + .addMethod(method, handler()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java new file mode 100644 index 0000000000..4fbf6e76b9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java @@ -0,0 +1,436 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.BindableService; +import io.grpc.CallOptions; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; +import io.grpc.ServerInterceptor; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.ClientCalls; +import io.grpc.stub.ServerCalls; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.annotation.Order; +import org.springframework.grpc.server.DefaultGrpcServerFactory; +import org.springframework.grpc.server.GlobalServerInterceptor; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.DefaultGrpcServiceConfigurer; +import org.springframework.grpc.server.service.DefaultGrpcServiceDiscoverer; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.grpc.server.service.GrpcServiceConfigurer; +import org.springframework.grpc.server.service.GrpcServiceDiscoverer; + +class CommonGrpcRequestBoundsAutoConfigurationTest { + private static final MethodDescriptor READ = + MethodDescriptor.newBuilder() + .setFullMethodName("test.Discovered/Read") + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonGrpcRequestBoundsAutoConfiguration.class, + GrpcServerFactoryAutoConfiguration.class, + GrpcServerAutoConfiguration.class)) + .withPropertyValues("spring.grpc.server.port=0", "spring.grpc.server.ssl.enabled=false") + .withUserConfiguration(DiscoveredServiceConfiguration.class); + + @Test + void productionAutoConfigurationDiscoversRegistersAndCallsRealServiceWithOrderedInterceptors() { + runner.run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerFactory.class) + .hasSingleBean(GrpcServerLifecycle.class); + assertThat(context.getBean(GrpcServiceDiscoverer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceDiscoverer.class); + assertThat(context.getBean(GrpcServiceConfigurer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceConfigurer.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle.getFactory()) + .isSameAs(context.getBean(BoundedGrpcServerFactory.class)); + assertThat(lifecycle.isRunning()).isTrue(); + var state = context.getBean(DiscoveryState.class); + assertThat(state.filtered).hasValue(1); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", lifecycle.getPort()) + .usePlaintext() + .build(); + try { + assertThat( + ClientCalls.blockingUnaryCall( + channel, + READ, + CallOptions.DEFAULT + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withCompression("gzip"), + Empty.getDefaultInstance())) + .isEqualTo(Empty.getDefaultInstance()); + assertThat(state.events).containsExactly("first", "second", "handler"); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + }); + } + + @Test + void realSpringBootAutoDiscoveryKeepsFrameworkSupportAndCanonicalGuardTogether() + throws Exception { + // Exercise classpath auto-configuration discovery rather than enumerating gRPC configurations. + // Core runtime composition is unrelated to this focused server registration proof. + try (var context = + new SpringApplicationBuilder(AutoDiscoveredBootApplication.class) + .web(WebApplicationType.NONE) + .registerShutdownHook(false) + .run( + "--spring.profiles.active=test", + "--spring.application.name=bounded-grpc-boot-test", + "--spring.grpc.server.port=0", + "--spring.grpc.server.ssl.enabled=false", + "--spring.main.banner-mode=off", + "--spring.autoconfigure.exclude=net.firedevops.firemud.common.config.CommonCoreAutoConfiguration," + + "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration")) { + assertThat(context.getBeansOfType(GrpcServerFactory.class)).hasSize(1); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(context.getBean(GrpcServiceDiscoverer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceDiscoverer.class); + assertThat(context.getBean(GrpcServiceConfigurer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceConfigurer.class); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle.isRunning()).isTrue(); + assertThat(lifecycle.getFactory()).isSameAs(context.getBean(BoundedGrpcServerFactory.class)); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", lifecycle.getPort()).usePlaintext().build(); + try { + assertThat( + ClientCalls.blockingUnaryCall( + channel, + READ, + CallOptions.DEFAULT + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withCompression("gzip"), + Empty.getDefaultInstance())) + .isEqualTo(Empty.getDefaultInstance()); + assertThat(context.getBean(DiscoveryState.class).events) + .containsExactly("first", "second", "handler"); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void explicitNoServerLifecycleBacksOffWithoutWeakeningFactoryDescriptorChecks() { + runner + .withUserConfiguration(NoGrpcServerTestConfiguration.class) + .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) + .run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerLifecycle.class) + .hasSingleBean(GrpcServerFactory.class) + .doesNotHaveBean("boundedGrpcServerLifecycle"); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); + verify(lifecycle, never()).start(); + var factory = context.getBean(GrpcServerFactory.class); + assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact registered descriptor"); + }); + } + + @Test + void explicitNoServerFixtureAlsoBootsWhenFrameworkGrpcSupportIsExcluded() { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonGrpcRequestBoundsAutoConfiguration.class)) + .withUserConfiguration( + DiscoveredServiceConfiguration.class, NoGrpcServerTestConfiguration.class) + .withPropertyValues("spring.grpc.server.port=0", "spring.grpc.server.ssl.enabled=false") + .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) + .run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerLifecycle.class) + .hasSingleBean(GrpcServerFactory.class) + .hasSingleBean(GrpcServiceConfigurer.class) + .doesNotHaveBean("boundedGrpcServerLifecycle"); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); + verify(lifecycle, never()).start(); + verifyNoInteractions(context.getBean(GrpcServiceConfigurer.class)); + var factory = context.getBean(GrpcServerFactory.class); + assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact registered descriptor"); + }); + } + + @Test + void createdPolicyRequiresExplicitTransportOptInAndKeepsOrdinaryMethodsBounded() { + var createdRunner = + runner + .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) + .withBean(CreatedRosterService.class, CreatedRosterService::new); + createdRunner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat( + context.getBean(GrpcServerProperties.class).getMaxInboundMessageSize().toBytes()) + .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + assertPurposeAndOrdinaryAdmission( + context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.RESOURCE_EXHAUSTED); + assertThat(context.getBean(DiscoveryState.class).events).doesNotContain("handler"); + }); + createdRunner + .withPropertyValues( + "spring.grpc.server.max-inbound-message-size=" + + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES + + "B") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat( + context + .getBean(GrpcServerProperties.class) + .getMaxInboundMessageSize() + .toBytes()) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + // UNIMPLEMENTED comes from the generated base only after the actual eligible request + // parses. + assertPurposeAndOrdinaryAdmission( + context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.UNIMPLEMENTED); + assertThat(context.getBean(DiscoveryState.class).events).doesNotContain("handler"); + }); + createdRunner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=0B") + .run(context -> assertThat(context).hasFailed()); + createdRunner + .withPropertyValues( + "spring.grpc.server.max-inbound-message-size=" + + ((long) + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES + + 1) + + "B") + .run(context -> assertThat(context).hasFailed()); + } + + private static void assertPurposeAndOrdinaryAdmission(int port, Status.Code purposeStatus) + throws Exception { + var unknown = + UnknownFieldSet.newBuilder() + .addField( + 9999, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom(new byte[GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES])) + .build()) + .build(); + var request = + CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() + .setUnknownFields(unknown) + .build(); + assertThat(request.getSerializedSize()) + .isGreaterThan(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", port).usePlaintext().build(); + try { + var options = + CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS).withCompression("gzip"); + assertThatThrownBy( + () -> + ClientCalls.blockingUnaryCall( + channel, + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod(), + options, + request)) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(purposeStatus)); + assertThatThrownBy( + () -> + ClientCalls.blockingUnaryCall( + channel, READ, options, Empty.newBuilder().setUnknownFields(unknown).build())) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void alternateFactoryAndDuplicatePoliciesFailClosed() { + runner + .withBean("unguarded", GrpcServerFactory.class, () -> mock(GrpcServerFactory.class)) + .run(context -> assertThat(context).hasFailed()); + runner + .withBean("policyOne", GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::ordinary) + .withBean("policyTwo", GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::ordinary) + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void missingExceptionsUseOrdinaryCeilingAndUnknownOrUnboundedTransportCannotWidenIt() { + runner.run( + context -> + assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) + .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES)); + runner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=5MB") + .run(context -> assertThat(context).hasFailed()); + runner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=-1B") + .run(context -> assertThat(context).hasFailed()); + runner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=1MB") + .run(context -> assertThat(context).hasNotFailed()); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + @Import(DiscoveredServiceConfiguration.class) + static class AutoDiscoveredBootApplication {} + + static class DiscoveryState { + final List events = new CopyOnWriteArrayList<>(); + final AtomicInteger filtered = new AtomicInteger(); + } + + @Configuration(proxyBeanMethods = false) + static class DiscoveredServiceConfiguration { + @Bean + DiscoveryState discoveryState() { + return new DiscoveryState(); + } + + @Bean + DiscoveredService discoveredService(DiscoveryState state) { + return new DiscoveredService(state); + } + + @Bean + GrpcServerFactoryCustomizer serviceFilter(DiscoveryState state) { + return factory -> + ((DefaultGrpcServerFactory) factory) + .setServiceFilter( + (service, ignored) -> { + state.filtered.incrementAndGet(); + return true; + }); + } + + @Bean + @GlobalServerInterceptor + @Order(10) + ServerInterceptor firstInterceptor(DiscoveryState state) { + return interceptor(state, "first"); + } + + @Bean + @GlobalServerInterceptor + @Order(20) + ServerInterceptor secondInterceptor(DiscoveryState state) { + return interceptor(state, "second"); + } + } + + @GrpcService + static class CreatedRosterService + extends CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase {} + + @GrpcService + static class DiscoveredService implements BindableService { + private final DiscoveryState state; + + DiscoveredService(DiscoveryState state) { + this.state = state; + } + + @Override + public ServerServiceDefinition bindService() { + return ServerServiceDefinition.builder("test.Discovered") + .addMethod( + READ, + ServerCalls.asyncUnaryCall( + (request, observer) -> { + state.events.add("handler"); + observer.onNext(Empty.getDefaultInstance()); + observer.onCompleted(); + })) + .build(); + } + } + + private static ServerInterceptor interceptor(DiscoveryState state, String name) { + return new ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + state.events.add(name); + return next.startCall(call, headers); + } + }; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java new file mode 100644 index 0000000000..58eebb2e5b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import org.junit.jupiter.api.Test; + +/** Pure carrier integrity; these comparison values are not authenticated recovery evidence. */ +class CanonicalGameplayRosterRecoveryEvidenceTest { + @Test + void createdRecoveryReturnsOnlyItsDistinctRosterAndKeepsExactOwnerFenceAndMarker() + throws Exception { + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var request = request(fixture.original()); + var response = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), fixture.roster()); + assertThat(response.getCanonicalRosterReceipt()).isEmpty(); + assertThat(response.getCanonicalPlayerCreatedRosterReceipt()) + .isEqualTo(fixture.roster().toByteString()); + assertThat( + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, CanonicalGameplayRosterRecoveryResponse.parseFrom(response.toByteArray()))) + .isEqualTo(response); + var owner = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), + response.getOwnerFence(), + UUID.fromString(response.getTargetFenceUuid()), + fixture.roster()) + .toBuilder() + .setRecoveryUuid(request.getRecoveryUuid()) + .build(); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireOwnerRecovery(request, owner)) + .isEqualTo(owner); + assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.requireDereference(owner)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.response( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + var noCapture = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), null); + assertThat(noCapture.getCanonicalPlayerCreatedRosterReceipt()).isEmpty(); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireResponse(request, noCapture)) + .isEqualTo(noCapture); + for (var changed : + List.of( + response.toBuilder() + .setCanonicalRosterReceipt(fixture.roster().getRoster().toByteString()) + .build(), + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + fixture.roster().toBuilder() + .setSourceIdentity( + fixture.roster().getSourceIdentity().toBuilder() + .setAuthoredBindingUuid(UUID.randomUUID().toString())) + .build() + .toByteString()) + .build(), + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + fixture.roster().toBuilder() + .setRoster( + fixture.roster().getRoster().toBuilder() + .setCanonicalAccountUuid(UUID.randomUUID().toString())) + .build() + .toByteString()) + .build(), + response.toBuilder() + .setRequest(request.toBuilder().setRecoveryUuid(UUID.randomUUID().toString())) + .build())) { + assertThatThrownBy( + () -> CanonicalGameplayRosterRecoveryEvidence.requireResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void recoveryBudgetsStayEightAnd128KiBWithClosedPolicySpecificReceiptFields() { + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var request = request(fixture.original()); + var response = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), null); + assertThat(CanonicalGameplayRosterRecoveryEvidence.MAX_REQUEST_BYTES).isEqualTo(8192); + assertThat(CanonicalGameplayRosterRecoveryEvidence.MAX_RESPONSE_BYTES).isEqualTo(128 * 1024); + int maximumRosterEnvelope = 66 * 1024 + 4096 + 256; + assertThat(maximumRosterEnvelope) + .isLessThanOrEqualTo(CanonicalGameplayRosterRecoveryEvidence.MAX_RESPONSE_BYTES); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( + 66 * 1024 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( + 128 * 1024 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + var oldTarget = + CanonicalGameplayRosterReferenceEvidence.target(fixture.original()).toBuilder() + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + var old = + CanonicalGameplayRosterReferenceEvidence.request( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "gameplay", oldTarget); + var oldRequest = request(old); + var oldReceipt = + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(old.getCanonicalAccountUuid()) + .setTarget(oldTarget) + .setSnapshotUuid(UUID.randomUUID().toString()) + .setSnapshotDigest("d".repeat(64)) + .build(); + var oldResponse = + CanonicalGameplayRosterRecoveryEvidence.response( + oldRequest, UUID.randomUUID(), 1L, UUID.randomUUID(), oldReceipt); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireResponse(oldRequest, oldResponse)) + .isEqualTo(oldResponse); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + oldRequest, + oldResponse.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + oldRequest, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameplayRosterRecoveryRequest request( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original) { + return CanonicalGameplayRosterRecoveryRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(original) + .setRecoveryUuid(UUID.randomUUID().toString()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java index e3ec61c2f5..391e0759ba 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java @@ -3,13 +3,23 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.UnknownFieldSet; +import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; import org.junit.jupiter.api.Test; class CanonicalGameplayRosterReferenceEvidenceTest { @@ -232,6 +242,426 @@ void closedRecoveryEchoAndOptionalOriginalReceiptNeverPermitSubstitution() { } } + @Test + void createdMenuAndSelectedReplayRetainTheDistinctCompleteOriginalCreationReceipt() + throws Exception { + var fixture = createdFixture(); + var original = fixture.original(); + var menu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 1L, UUID.randomUUID(), fixture.roster()); + assertThat(CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(menu)) + .isEqualTo(fixture.roster()); + assertThat(CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(menu)) + .isEqualTo(fixture.roster().getRoster()); + var selected = selectedOriginal(fixture, menu); + assertThat(CanonicalGameplayRosterReferenceEvidence.requireResponse(original, selected)) + .isEqualTo(selected); + var replay = GetCanonicalGameplayRosterReferenceResponse.parseFrom(selected.toByteArray()); + assertThat(CanonicalGameplayRosterReferenceEvidence.requireResponse(original, replay)) + .isEqualTo(selected); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt(replay)) + .isEqualTo(fixture.selected()); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt(replay) + .getTerminal()) + .isEqualTo(fixture.selected().getTerminal()); + assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.receipt(menu)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt(selected)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.response( + original, 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.request( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "gameplay", + fixture.roster().getRoster().getTarget())) + .isInstanceOf(IllegalArgumentException.class); + var foreignOriginal = original.toBuilder().setTargetNamespace("other").build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + foreignOriginal, selected.toBuilder().setRequest(foreignOriginal).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload namespace"); + for (var changed : + List.of( + selected.toBuilder().setSelectedCharacterUuid(UUID.randomUUID().toString()).build(), + selected.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toBuilder() + .setRequestUuid(UUID.randomUUID().toString()) + .build() + .toByteString()) + .build(), + selected.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toBuilder() + .setCanonicalAccountUuid(UUID.randomUUID().toString()) + .build() + .toByteString()) + .build(), + selected.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toBuilder() + .setSourceIdentity( + fixture.selected().getSourceIdentity().toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString())) + .build() + .toByteString()) + .build())) { + assertThatThrownBy( + () -> CanonicalGameplayRosterReferenceEvidence.requireResponse(original, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void fiveMebibyteSelectedReceiptRequiresExactCanonicalBytesAndRejectsTamperingAndOversize() + throws Exception { + var fixture = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection("gameplay"); + var original = fixture.original(); + var canonicalSelectedBytes = original.getCanonicalSelectedPlayerCreatedCharacterReceipt(); + + assertThat(canonicalSelectedBytes.size()).isGreaterThan(5 * 1024 * 1024); + int midpoint = canonicalSelectedBytes.size() / 2; + var ropeBackedCanonicalBytes = + canonicalSelectedBytes + .substring(0, midpoint) + .concat(canonicalSelectedBytes.substring(midpoint, canonicalSelectedBytes.size())); + var ropeBackedOriginal = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt(ropeBackedCanonicalBytes) + .build(); + assertThat( + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), ropeBackedOriginal)) + .isEqualTo(ropeBackedOriginal); + + var duplicateRequestField = + new byte[CodedOutputStream.computeStringSize(1, fixture.selected().getRequestUuid())]; + var codedOutput = CodedOutputStream.newInstance(duplicateRequestField); + codedOutput.writeString(1, fixture.selected().getRequestUuid()); + codedOutput.checkNoSpaceLeft(); + var noncanonical = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + canonicalSelectedBytes.concat(ByteString.copyFrom(duplicateRequestField))) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), noncanonical)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Selected PLAYER_CREATED receipt bytes are not canonical"); + + var tamperedSelected = + fixture.selected().toBuilder() + .setTarget( + fixture.selected().getTarget().toBuilder() + .setPointerVersion(fixture.selected().getTarget().getPointerVersion() + 1L) + .build()) + .build(); + var tampered = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt(tamperedSelected.toByteString()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), tampered)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("binding changed"); + + var oversized = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES + 1)) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Original roster selection owner binding is invalid"); + } + + @Test + void createdSourceBytesAndPolicyBranchesAreClosedAndMutuallyExclusive() { + var fixture = createdFixture(); + var created = fixture.original(); + var source = CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity(created); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + for (var changed : + List.of( + created.toBuilder().clearCanonicalPlayerCreatedSourceIdentity().build(), + created.toBuilder() + .setCanonicalPlayerCreatedSourceIdentity( + source.toBuilder().setUnknownFields(unknown).build().toByteString()) + .build(), + created.toBuilder() + .setCanonicalPlayerCreatedSourceIdentity( + source.toByteString().concat(ByteString.copyFrom(new byte[] {8, 1}))) + .build(), + created.toBuilder() + .setCanonicalTarget( + CanonicalGameplayRosterReferenceEvidence.target(created).toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .build() + .toByteString()) + .build(), + created.toBuilder() + .setCanonicalTarget( + CanonicalGameplayRosterReferenceEvidence.target(created).toBuilder() + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_AUTO_PROVISIONED) + .build() + .toByteString()) + .build(), + request().toBuilder() + .setCanonicalPlayerCreatedSourceIdentity(source.toByteString()) + .build())) { + assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.requireRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + var createdMenu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + created, 1L, UUID.randomUUID(), fixture.roster()); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + created, + createdMenu.toBuilder() + .setCanonicalRosterReceipt(fixture.roster().getRoster().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var preseeded = request(); + var reserved = + CanonicalGameplayRosterReferenceEvidence.response(preseeded, 1L, UUID.randomUUID(), null); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + preseeded, 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void largestCreatedSelectorsAndUnicodeReleaseFitUnchangedOriginalAndRecoveryRequestBudgets() { + var fixture = createdFixture(); + var target = + CanonicalGameplayRosterReferenceEvidence.target(fixture.original()).toBuilder() + .setWorldSlug("a".repeat(64)) + .setRealmSlug("b".repeat(64)) + .setCatalogRevision(Long.MAX_VALUE) + .setPointerVersion(Long.MAX_VALUE) + .setActiveWorldEpoch(Long.MAX_VALUE) + .setPublishedReleaseBundleRef("\u0800".repeat(1024)) + .build(); + var largest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(63), + target, + CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity( + fixture.original())); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_REQUEST_BYTES).isEqualTo(4096); + assertThat( + target.getPublishedReleaseBundleRef().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .hasSize(3072); + assertThat(largest.getSerializedSize()) + .isEqualTo(4081) + .isLessThanOrEqualTo(CanonicalGameplayRosterReferenceEvidence.MAX_REQUEST_BYTES); + var recovery = + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest + .newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(largest) + .setRecoveryUuid(UUID.randomUUID().toString()) + .build(); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireRequest(recovery).getSerializedSize()) + .isEqualTo(4124) + .isLessThanOrEqualTo(CanonicalGameplayRosterRecoveryEvidence.MAX_REQUEST_BYTES); + } + + @Test + void createdPurposeBudgetsRetainTheFullTerminalAndRejectOversizeWithoutHugeBackingArrays() { + var fixture = createdFixture(); + var menu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), 1L, UUID.randomUUID(), fixture.roster()); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_RECEIPT_BYTES).isEqualTo(64 * 1024); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_ASSIGNMENT_BYTES) + .isEqualTo(8192); + assertThat(CanonicalPlayerCreatedRosterEvidence.MAX_TERMINAL_BYTES) + .isEqualTo(192 * 1024 * 1024); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES) + .isEqualTo(193 * 1024 * 1024); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES) + .isEqualTo(194 * 1024 * 1024); + var preseeded = request(); + var reserved = + CanonicalGameplayRosterReferenceEvidence.response(preseeded, 1L, UUID.randomUUID(), null); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalRosterReceipt(logicalBytes(64 * 1024 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt( + reserved.toBuilder() + .setCanonicalSelectedAssignmentReceipt(logicalBytes(8192 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + int completeSelectedEnvelope = + CodedOutputStream.computeTagSize(18) + + CodedOutputStream.computeUInt32SizeNoTag( + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES) + + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES; + // A full 193 MiB selected envelope, 66 KiB menu, maximal original and bounded input/metadata + // fit the original-response purpose without constructing a gratuitous 192 MiB terminal. + assertThat(completeSelectedEnvelope + 66 * 1024 + 4096 + 2048) + .isLessThanOrEqualTo( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES); + for (var changed : + List.of( + menu.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RECEIPT_BYTES + + 1)) + .build(), + menu.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES + + 1)) + .build(), + menu.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES + + 1)) + .build())) { + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.original(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + // Rope ByteStrings share their tiny backing payload; over-budget tests reject before parsing. + static ByteString logicalBytes(int size) { + ByteString bytes = ByteString.copyFrom(new byte[1024]); + while (bytes.size() < size) bytes = bytes.concat(bytes); + return bytes.substring(0, size); + } + + record CreatedFixture( + GetCanonicalGameplayRosterReferenceRequest original, + CanonicalPlayerCreatedRosterResponse roster, + CanonicalSelectedPlayerCreatedCharacterResponse selected) {} + + static CreatedFixture createdFixture() { + var selected = CanonicalPlayerCreatedRosterEvidenceTest.selectedFixture(); + var request = selected.request(); + var actors = + List.of( + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(request.getSelectedCharacterUuid()) + .setDisplayName("Persisted created actor") + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()); + var digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), + request.getExpectedTarget(), + request.getExpectedSource(), + actors); + var snapshot = + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(request.getExpectedSnapshot().getSnapshotUuid()) + .setSnapshotDigest(digest) + .build(); + var roster = + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(request.getExpectedSource()) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(snapshot.getSnapshotUuid()) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .build(); + var original = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), + selected + .response() + .getTerminal() + .getOriginalRequest() + .getOriginal() + .getTargetNamespace(), + request.getExpectedTarget(), + request.getExpectedSource()); + return new CreatedFixture( + original, roster, selected.response().toBuilder().setSnapshot(snapshot).build()); + } + + static GetCanonicalGameplayRosterReferenceResponse selectedOriginal( + CreatedFixture fixture, GetCanonicalGameplayRosterReferenceResponse menu) { + return menu.toBuilder() + .setSelectionInput( + net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("1")) + .setSelectedCharacterUuid(fixture.selected().getSelectedCharacterUuid()) + .setCanonicalSelectedPlayerCreatedCharacterReceipt(fixture.selected().toByteString()) + .setTerminalOutcome("SELECTED") + .build(); + } + private static GetCanonicalGameplayRosterReferenceRequest request() { var target = CanonicalGameplayRosterTarget.newBuilder() diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java index b7f12db50a..05435d4845 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java @@ -4,10 +4,15 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.UnknownFieldSet; +import java.io.OutputStream; +import java.security.DigestOutputStream; import java.security.MessageDigest; import java.util.HexFormat; import java.util.UUID; +import net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; @@ -60,6 +65,19 @@ void acceptsDifferentAnchorOperationOnlyForTheExactSharedSnapshotAndFence() { acknowledgement(original, anchorProof, "", ""))); } + @Test + void acknowledgementRequiresRetiredStateEvenWhenTheOwnerResponseBindingsMatch() { + var original = original(OPERATION, target()); + var reserved = + CanonicalGameplayRosterReferenceEvidence.response(original, 17L, TARGET_FENCE, null); + + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + acknowledgement(original, reserved, "", ""))); + } + @Test void rejectsChangedAccountTargetPolicyAndSnapshotPair() { var original = original(OPERATION, target()); @@ -170,6 +188,10 @@ void acknowledgementAndConfirmationBindExactRequestHashesAndHorizons() throws Ex var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation(request, response); var confirmationResponse = CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation); + assertEquals( + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(confirmation.toByteArray())), + confirmationResponse.getRequestDigest()); assertEquals( confirmationResponse, CanonicalGameplayRosterRetirementEvidence.requireConfirmationResponse( @@ -189,6 +211,235 @@ void acknowledgementAndConfirmationBindExactRequestHashesAndHorizons() throws Ex .build())); } + @Test + void createdFiveMebibyteAcknowledgementStreamsExactDigestsAndRejectsNestedTampering() + throws Exception { + var fixture = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection("gameplay"); + var request = fixture.acknowledgementRequest(); + var acknowledgement = fixture.acknowledgement(); + var confirmation = fixture.confirmation(); + + assertTrue(request.getSerializedSize() > 5 * 1024 * 1024); + var unsignedRetirement = + request.getObservedRetirement().toBuilder().clearRetirementProofDigest().build(); + assertEquals( + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(unsignedRetirement.toByteArray())), + request.getObservedRetirement().getRetirementProofDigest()); + assertEquals( + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(request.toByteArray())), + CanonicalGameplayRosterRetirementEvidence.requestDigest(request)); + assertEquals( + acknowledgement, + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgementResponse( + request, acknowledgement)); + var confirmationResponse = + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation); + assertEquals( + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(confirmation.toByteArray())), + confirmationResponse.getRequestDigest()); + assertEquals( + confirmationResponse, + CanonicalGameplayRosterRetirementEvidence.requireConfirmationResponse( + confirmation, confirmationResponse)); + + var duplicateRequestField = + new byte[CodedOutputStream.computeStringSize(1, fixture.selected().getRequestUuid())]; + var codedOutput = CodedOutputStream.newInstance(duplicateRequestField); + codedOutput.writeString(1, fixture.selected().getRequestUuid()); + codedOutput.checkNoSpaceLeft(); + var observedRetirement = request.getObservedRetirement(); + var noncanonicalRetirement = + observedRetirement.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + observedRetirement + .getCanonicalSelectedPlayerCreatedCharacterReceipt() + .concat(ByteString.copyFrom(duplicateRequestField))) + .build(); + // Recompute the wire seal so ACK validation reaches the canonical receipt check. This is a + // controlled value fixture and does not establish the owner authority of the proof. + var unsignedNoncanonicalRetirement = + noncanonicalRetirement.toBuilder().clearRetirementProofDigest().build(); + var sealedNoncanonicalRetirement = + unsignedNoncanonicalRetirement.toBuilder() + .setRetirementProofDigest(streamedDigest(unsignedNoncanonicalRetirement)) + .build(); + var noncanonicalFailure = + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + request.toBuilder() + .setObservedRetirement(sealedNoncanonicalRetirement) + .build())); + assertTrue( + noncanonicalFailure + .getMessage() + .contains("Selected PLAYER_CREATED receipt bytes are not canonical")); + + var changedRetirement = + request.toBuilder() + .setObservedRetirement( + request.getObservedRetirement().toBuilder() + .setSupersedingPointerVersion( + request.getObservedRetirement().getSupersedingPointerVersion() + 1L)) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(changedRetirement)); + + var changedConfirmation = + confirmation.toBuilder() + .setAcknowledgement( + acknowledgement.toBuilder().setRequestDigest("0".repeat(64)).build()) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> CanonicalGameplayRosterRetirementEvidence.requireConfirmation(changedConfirmation)); + } + + @Test + void createdRetirementCarriesTheCompleteSelectedTerminalAndBindsCrossOriginalSourceIdentity() { + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var original = fixture.original(); + var menu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 17L, TARGET_FENCE, fixture.roster()); + var selected = CanonicalGameplayRosterReferenceEvidenceTest.selectedOriginal(fixture, menu); + var target = CanonicalGameplayRosterReferenceEvidence.target(original); + var proof = createdRetirement(selected); + var roster = fixture.roster().getRoster(); + var request = + acknowledgement(original, proof, roster.getSnapshotUuid(), roster.getSnapshotDigest()); + assertEquals( + request, CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(request)); + assertEquals( + fixture.selected().toByteString(), + request.getObservedRetirement().getCanonicalSelectedPlayerCreatedCharacterReceipt()); + var ack = CanonicalGameplayRosterRetirementEvidence.response(request, uuid(12), 20_000L); + var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation(request, ack); + assertEquals( + confirmation, CanonicalGameplayRosterRetirementEvidence.requireConfirmation(confirmation)); + var otherOriginal = + original.toBuilder() + .setOperationUuid(uuid(80).toString()) + .setSessionUuid(uuid(81).toString()) + .build(); + var anchored = + acknowledgement(otherOriginal, proof, roster.getSnapshotUuid(), roster.getSnapshotDigest()); + assertEquals( + anchored, CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(anchored)); + var changedSource = + CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity(otherOriginal) + .toBuilder() + .setAuthoredBindingUuid(uuid(82).toString()) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + anchored.toBuilder() + .setOriginalSelection( + otherOriginal.toBuilder() + .setCanonicalPlayerCreatedSourceIdentity(changedSource.toByteString())) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + anchored.toBuilder().clearSnapshotUuid().clearSnapshotDigest().build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + request.toBuilder().setSnapshotDigest("0".repeat(64)).build())); + var unboundProof = + createdRetirement( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 17L, TARGET_FENCE, null) + .toBuilder() + .setTerminalOutcome("DENIED") + .build()); + var unbound = acknowledgement(original, unboundProof, "", ""); + assertEquals( + unbound, CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(unbound)); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + acknowledgement(otherOriginal, unboundProof, "", ""))); + assertEquals( + target, + CanonicalGameplayRosterReferenceEvidence.target( + anchored.getObservedRetirement().getRequest())); + } + + @Test + void acknowledgementPurposeBoundsKeepOldCapsAndFitCompleteCreatedOriginalWithoutHugeArrays() { + assertEquals(128 * 1024, CanonicalGameplayRosterRetirementEvidence.MAX_REQUEST_BYTES); + assertEquals(4096, CanonicalGameplayRosterRetirementEvidence.MAX_RESPONSE_BYTES); + assertEquals( + 195 * 1024 * 1024, + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES); + assertEquals( + CanonicalGameplayRosterRetirementEvidence.MAX_REQUEST_BYTES + 4096 + 64, + CanonicalGameplayRosterRetirementEvidence.MAX_CONFIRMATION_BYTES); + assertEquals( + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES + 4096 + 64, + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + int original = CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES; + int encodedOriginal = + com.google.protobuf.CodedOutputStream.computeTagSize(3) + + com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(original) + + original; + assertTrue( + encodedOriginal + 4096 + 512 + <= CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES); + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var request = + acknowledgement( + fixture.original(), + createdRetirement( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), 17L, TARGET_FENCE, fixture.roster())), + fixture.roster().getRoster().getSnapshotUuid(), + fixture.roster().getRoster().getSnapshotDigest()); + var oversized = + request.toBuilder() + .setObservedRetirement( + request.getObservedRetirement().toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_REQUEST_BYTES + + 1))) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(oversized)); + } + + private static GetCanonicalGameplayRosterReferenceResponse createdRetirement( + GetCanonicalGameplayRosterReferenceResponse original) { + var target = CanonicalGameplayRosterReferenceEvidence.target(original.getRequest()); + return CanonicalGameplayRosterReferenceEvidence.sealRetirement( + original.toBuilder() + .setState( + CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) + .setTerminalOutcome( + original.getTerminalOutcome().isEmpty() ? "MENU" : original.getTerminalOutcome()) + .setRetirementUuid(uuid(18).toString()) + .setSupersedingPointerDigest("9".repeat(64)) + .setSupersedingPointerVersion(target.getPointerVersion() + 1L) + .setSupersedingCatalogRevision(target.getCatalogRevision()) + .setSupersedingWorldEpoch(target.getActiveWorldEpoch()) + .build()); + } + private static CanonicalGameplayRosterRetirementAcknowledgementRequest acknowledgement( GetCanonicalGameplayRosterReferenceRequest original, GetCanonicalGameplayRosterReferenceResponse observed, @@ -268,4 +519,16 @@ private static CanonicalGameplayRosterTarget target(int variant) { private static UUID uuid(long value) { return new UUID(0L, value); } + + private static String streamedDigest(GetCanonicalGameplayRosterReferenceResponse response) + throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (DigestOutputStream digestOutput = + new DigestOutputStream(OutputStream.nullOutputStream(), digest)) { + CodedOutputStream codedOutput = CodedOutputStream.newInstance(digestOutput); + response.writeTo(codedOutput); + codedOutput.flush(); + } + return HexFormat.of().formatHex(digest.digest()); + } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidenceTest.java new file mode 100644 index 0000000000..828d9fa645 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidenceTest.java @@ -0,0 +1,856 @@ +package net.firedevops.firemud.common.world; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.io.InputStream; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.AuthoredSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Catalog; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Core; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Descriptor; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.ExpectedVersion; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Mutation; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Pointer; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Policy; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Rule; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Scope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Target; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; + +/** + * Pure controlled PLAYER_CREATED value tests; these do not establish authenticated creation proof. + */ +class CanonicalPlayerCreatedRosterEvidenceTest { + private static final String VECTOR_RESOURCE = "/operator/character-create-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ACCOUNT = uuid(1); + private static final String CHARACTER_1 = uuid(2); + private static final String CHARACTER_2 = uuid(3); + private static final String SNAPSHOT = uuid(4); + + record SelectedFixture( + CanonicalSelectedPlayerCreatedCharacterRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse response) {} + + private record Fixture( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + CanonicalSelectedPlayerCreatedCharacterRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse response) {} + + static SelectedFixture selectedFixture() { + try { + Fixture fixture = fixture(false); + return new SelectedFixture(fixture.request(), fixture.response()); + } catch (IOException failure) { + throw new IllegalStateException("Controlled CHARACTER_CREATE vector is unavailable", failure); + } + } + + @Test + void acceptsEmptyRosterWithoutInventingAnActor() { + CanonicalPlayerCreatedRosterRequest request = request(target(), source(), context(null)); + CanonicalPlayerCreatedRosterResponse response = response(request, List.of()); + + assertEquals(response, CanonicalPlayerCreatedRosterEvidence.requireResponse(request, response)); + } + + @Test + void digestBindsOneAndManyOrderedActors() { + var one = List.of(actor(CHARACTER_1, "Mira")); + var many = List.of(actor(CHARACTER_1, "Mira"), actor(CHARACTER_2, "Tāne")); + + String oneDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), one); + String manyDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), many); + String reversedDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), List.of(many.get(1), many.get(0))); + + assertEquals(64, oneDigest.length()); + assertEquals(64, manyDigest.length()); + org.junit.jupiter.api.Assertions.assertNotEquals(oneDigest, manyDigest); + org.junit.jupiter.api.Assertions.assertNotEquals(manyDigest, reversedDigest); + } + + @Test + void responseRejectsChangedSourceTargetAndSnapshotDigest() { + CanonicalPlayerCreatedRosterRequest request = request(target(), source(), context(null)); + CanonicalPlayerCreatedRosterResponse valid = + response(request, List.of(actor(CHARACTER_1, "Mira"))); + + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, valid.toBuilder().setSourceIdentity(source(9)).build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, + valid.toBuilder() + .setRoster(valid.getRoster().toBuilder().setTarget(target(9))) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, + valid.toBuilder() + .setRoster(valid.getRoster().toBuilder().setSnapshotDigest("0".repeat(64))) + .build())); + } + + @Test + void requestRejectsUnknownNilAndMalformedContextValues() { + var request = request(target(), source(), context(null)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder().setRequestUuid(uuid(0)).build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder().setUnknownFields(unknown).build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder() + .setPlayerExecutionContext( + request.getPlayerExecutionContext().toBuilder().setPlayableStateScope("1")) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder() + .setExpectedTarget( + request.getExpectedTarget().toBuilder() + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY)) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder() + .setPlayerExecutionContext( + request.getPlayerExecutionContext().toBuilder().setUnknownFields(unknown)) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + source().toBuilder().setDescriptorUuid(uuid(0)).build())); + } + + @Test + void rejectsDuplicateActorsAndMalformedSelectedContext() { + var duplicateActors = List.of(actor(CHARACTER_1, "Mira"), actor(CHARACTER_1, "Mira")); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), duplicateActors)); + + var selected = selectedRequest(context(CHARACTER_1)); + assertEquals(selected, CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest(selected)); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest( + selected.toBuilder() + .setPlayerExecutionContext( + selected.getPlayerExecutionContext().toBuilder() + .setCharacterId(CHARACTER_2)) + .build())); + } + + @Test + void acceptsExactSelectedCreationReceiptAndReturnsTheOriginalImmutableResponse() { + Fixture controlled = uncheckedFixture(false); + assertNotEquals( + rawDigest(controlled.action().mutation().authoredSource().policy().contentDigest()), + controlled.target().getPublishedPolicyDigest()); + PlayerCreationDescriptor actualDescriptor = + PlayerCreationDescriptor.parse( + controlled.action().mutation().authoredSource().descriptor().canonicalJson()); + assertEquals(actualDescriptor.digest(), controlled.source().getDescriptorDigest()); + assertEquals( + actualDescriptor.digest(), controlled.response().getSourceIdentity().getDescriptorDigest()); + SelectedFixture fixture = new SelectedFixture(controlled.request(), controlled.response()); + + assertSame( + fixture.response(), + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( + fixture.request(), fixture.response())); + } + + @Test + void acceptsOriginalCreationAcrossRuntimeReplacement() throws IOException { + Fixture fixture = fixture(true); + + assertEquals( + fixture.response(), + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( + fixture.request(), fixture.response())); + } + + @Test + void rejectsOuterSubstitutionsAndChangedCreationOperationDigestOrActor() { + Fixture fixture = uncheckedFixture(false); + var response = fixture.response(); + + assertRejected(fixture.request(), response.toBuilder().setRequestUuid(uuid(101)).build()); + assertRejected( + fixture.request(), response.toBuilder().setCanonicalAccountUuid(uuid(102)).build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTarget(response.getTarget().toBuilder().setPointerVersion(99)) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setSnapshot(response.getSnapshot().toBuilder().setSnapshotDigest("f".repeat(64))) + .build()); + assertRejected( + fixture.request(), response.toBuilder().setCreationOperationUuid(uuid(103)).build()); + assertRejected( + fixture.request(), response.toBuilder().setMutationDigest("f".repeat(64)).build()); + + var changedActorRequest = + selectedCreatedRequest(fixture.action(), fixture.target(), fixture.source(), uuid(104)); + assertRejected( + changedActorRequest, response.toBuilder().setSelectedCharacterUuid(uuid(104)).build()); + } + + @Test + void rejectsDescriptorBindingPolicyAndVersionSubstitution() throws IOException { + Fixture fixture = fixture(false); + var changedDescriptor = fixture.source().toBuilder().setDescriptorUuid(uuid(111)).build(); + assertRejectedWithSource(fixture, changedDescriptor); + var changedBindingId = fixture.source().toBuilder().setAuthoredBindingUuid(uuid(112)).build(); + assertRejectedWithSource(fixture, changedBindingId); + var changedBindingDigest = + fixture.source().toBuilder().setAuthoredBindingDigest("sha256:" + "f".repeat(64)).build(); + assertRejectedWithSource(fixture, changedBindingDigest); + + CanonicalGameplayRosterTarget changedPolicy = + fixture.target().toBuilder().setPublishedPolicyDigest("f".repeat(64)).build(); + assertRejected( + fixture.request(), fixture.response().toBuilder().setTarget(changedPolicy).build()); + CanonicalGameplayRosterTarget changedVersion = + fixture.target().toBuilder().setCanonicalVersionUuid(uuid(113)).build(); + assertRejectedWithTarget(fixture, changedVersion); + } + + @Test + void rejectsMalformedUnknownMissingAndAbortedTerminalValues() { + Fixture fixture = uncheckedFixture(false); + var response = fixture.response(); + var terminal = response.getTerminal(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertRejected(fixture.request(), response.toBuilder().setUnknownFields(unknown).build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().setUnknownFields(unknown)).build()); + assertRejected(fixture.request(), response.toBuilder().clearTerminal().build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().clearOriginalRequest()).build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOutcome( + EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED)) + .build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().setTerminalId("")).build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().setTerminalFence(0)).build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setCompletedAt("not-an-instant")) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setAbortRequestId(uuid(115))) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setOriginalWorldProtection(ByteString.EMPTY)) + .build()); + + var malformedAccountOriginal = + terminal.getAccountOriginal().toBuilder() + .setOriginalSourceReadback(ByteString.EMPTY) + .build(); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setAccountOriginal(malformedAccountOriginal)) + .build()); + var unknownReference = + terminal.getOriginalRequest().getWorldProtection().toBuilder() + .setUnknownFields(unknown) + .build(); + var unknownOriginalRequest = + terminal.getOriginalRequest().toBuilder().setWorldProtection(unknownReference).build(); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setOriginalRequest(unknownOriginalRequest)) + .build()); + } + + @Test + void enforcesOriginalSourceAndProtectionPurposeBoundsWithoutLargeByteArrays() { + Fixture fixture = uncheckedFixture(false); + var response = fixture.response(); + var terminal = response.getTerminal(); + var tooLargeSourceReadback = + terminal.getAccountOriginal().toBuilder() + .setOriginalSourceReadback(bytesWithSize(32 * 1024 * 1024 + 1)) + .build(); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setAccountOriginal(tooLargeSourceReadback)) + .build()); + + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOriginalAccountProtection(bytesWithSize(40 * 1024 * 1024 + 1))) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOriginalGameSessionProtection(bytesWithSize(48 * 1024 * 1024 + 1))) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOriginalWorldProtection(bytesWithSize(48 * 1024 * 1024 + 1))) + .build()); + } + + private static Fixture fixture(boolean runtimeReplacement) throws IOException { + CharacterCreateOperatorAction action = controlledAction(); + CanonicalGameplayRosterTarget target = target(action, runtimeReplacement); + CanonicalPlayerCreatedRosterSourceIdentity source = source(action); + CanonicalSelectedPlayerCreatedCharacterRequest request = + selectedCreatedRequest(action, target, source, CHARACTER_1); + CanonicalSelectedPlayerCreatedCharacterResponse response = + selectedCreatedResponse(action, target, source, request); + return new Fixture(action, target, source, request, response); + } + + private static Fixture uncheckedFixture(boolean runtimeReplacement) { + try { + return fixture(runtimeReplacement); + } catch (IOException failure) { + throw new IllegalStateException("Controlled CHARACTER_CREATE vector is unavailable", failure); + } + } + + private static CharacterCreateOperatorAction controlledAction() throws IOException { + JsonNode root; + try (InputStream input = + CanonicalPlayerCreatedRosterEvidenceTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (input == null) throw new IOException("Missing CHARACTER_CREATE test vector"); + root = JSON.readTree(input); + } + for (JsonNode vector : root.path("vectors")) { + if ("base-public-player-created".equals(text(vector, "name"))) return action(vector); + } + throw new IOException("Missing controlled PLAYER_CREATED action vector"); + } + + private static CharacterCreateOperatorAction action(JsonNode vector) { + JsonNode scopeNode = vector.path("scope"); + JsonNode targetNode = vector.path("target"); + JsonNode expectedNode = vector.path("expectedVersion"); + JsonNode mutationNode = vector.path("mutation"); + JsonNode catalogNode = mutationNode.path("catalog"); + JsonNode pointerNode = mutationNode.path("pointer"); + JsonNode authoredNode = mutationNode.path("authoredSource"); + JsonNode policyNode = authoredNode.path("policy"); + JsonNode coreNode = authoredNode.path("core"); + JsonNode descriptorNode = authoredNode.path("descriptor"); + + Scope scope = + new Scope( + text(scopeNode, "targetNamespace"), + text(scopeNode, "tenantId"), + text(scopeNode, "playableStateNamespaceId"), + CharacterCreateOperatorAction.PlayableStateScope.valueOf( + text(scopeNode, "playableStateScope"))); + Target target = + new Target( + text(targetNode, "accountId"), + text(targetNode, "realmId"), + text(targetNode, "worldSlug"), + text(targetNode, "realmSlug"), + text(targetNode, "gameInstanceId"), + text(targetNode, "versionId")); + ExpectedVersion expected = + new ExpectedVersion( + text(expectedNode, "catalogRevision"), + text(expectedNode, "pointerVersion"), + text(expectedNode, "activeLifecycleEpoch"), + Instant.parse(text(expectedNode, "evaluatedAt")), + Instant.parse(text(expectedNode, "connectScopeExpiresAt"))); + Catalog catalog = + new Catalog( + text(catalogNode, "tenantId"), + text(catalogNode, "tenantSlug"), + text(catalogNode, "worldSlug"), + text(catalogNode, "worldDisplayName"), + text(catalogNode, "realmId"), + text(catalogNode, "realmSlug"), + text(catalogNode, "realmDisplayName"), + catalogNode.path("visible").booleanValue(), + catalogNode.path("publicProduction").booleanValue(), + text(catalogNode, "stateScope"), + text(catalogNode, "playableStateNamespaceId"), + text(catalogNode, "characterCreationPolicy"), + text(catalogNode, "catalogRevision")); + Pointer pointer = + new Pointer( + text(pointerNode, "tenantId"), + text(pointerNode, "realmId"), + text(pointerNode, "worldSlug"), + text(pointerNode, "realmSlug"), + text(pointerNode, "admissionState"), + text(pointerNode, "admissibleGameInstanceId"), + text(pointerNode, "pointerVersion"), + text(pointerNode, "catalogRevision"), + Instant.parse(text(pointerNode, "updatedAt"))); + Policy policy = + new Policy( + text(policyNode, "commitId"), + text(policyNode, "revisionId"), + text(policyNode, "logicalRevisionId"), + text(policyNode, "canonicalPolicyJson"), + text(policyNode, "contentDigest")); + Core core = new Core(text(coreNode, "canonicalJson")); + Descriptor descriptor = + new Descriptor(text(descriptorNode, "canonicalJson"), text(descriptorNode, "digest")); + AuthoredSource authored = + new AuthoredSource( + text(authoredNode, "schema"), + text(authoredNode, "bindingId"), + text(authoredNode, "bindingDigest"), + text(authoredNode, "canonicalTenantId"), + text(authoredNode, "canonicalVersionId"), + text(authoredNode, "worldSourceOperationId"), + text(authoredNode, "worldSourceEvidenceDigest"), + text(authoredNode, "worldSlug"), + text(authoredNode, "publicationWorkflowId"), + text(authoredNode, "selectedCommitId"), + text(authoredNode, "selectedCommitDigest"), + policy, + core, + descriptor, + rule(authoredNode.path("disposition")), + rule(authoredNode.path("safeFeedback"))); + Mutation mutation = + new Mutation( + text(mutationNode, "purpose"), + text(mutationNode, "entryPolicy"), + catalog, + pointer, + authored, + text(mutationNode, "canonicalCreationInput")); + return new CharacterCreateOperatorAction( + scope, target, expected, mutation, CharacterCreateOperatorAction.AuditReason.ABSENT); + } + + private static Rule rule(JsonNode node) { + return new Rule( + text(node, "key"), + text(node, "definitionJson"), + text(node, "definitionDigest"), + text(node, "sourceCommitId"), + text(node, "sourceCommitDigest"), + text(node, "revisionId"), + text(node, "revisionOrder")); + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Missing text field " + field); + } + return value.textValue(); + } + + private static CanonicalGameplayRosterTarget target( + CharacterCreateOperatorAction action, boolean runtimeReplacement) { + var target = action.target(); + var expected = action.expectedVersion(); + long catalogRevision = Long.parseLong(expected.catalogRevision()); + long pointerVersion = Long.parseLong(expected.pointerVersion()); + long worldEpoch = Long.parseLong(expected.activeLifecycleEpoch()); + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(action.scope().tenantId()) + .setRealmUuid(target.realmId()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(runtimeReplacement ? uuid(119) : target.gameInstanceId()) + .setCatalogRevision(runtimeReplacement ? catalogRevision + 11 : catalogRevision) + .setPublishedPolicyDigest("e".repeat(64)) + .setPublishedReleaseBundleRef("release/controlled-player-created") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCanonicalVersionUuid(target.versionId()) + .setPointerVersion(runtimeReplacement ? pointerVersion + 13 : pointerVersion) + .setActiveWorldEpoch(runtimeReplacement ? worldEpoch + 17 : worldEpoch) + .build(); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source( + CharacterCreateOperatorAction action) { + var authored = action.mutation().authoredSource(); + PlayerCreationDescriptor descriptor = + PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); + return CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(authored.bindingId()) + .setAuthoredBindingDigest(authored.bindingDigest()) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterRequest selectedCreatedRequest( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + String character) { + String requestUuid = uuid(117); + return CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(requestUuid) + .setCanonicalAccountUuid(action.target().accountId()) + .setSelectedCharacterUuid(character) + .setExpectedTarget(target) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(SNAPSHOT) + .setSnapshotDigest("a".repeat(64))) + .setPlayerExecutionContext( + context(target, action.target().accountId(), requestUuid, character)) + .setExpectedSource(source) + .build(); + } + + private static PlayerExecutionContext context( + CanonicalGameplayRosterTarget target, String account, String request, String character) { + return PlayerExecutionContext.newBuilder() + .setAccountId(account) + .setTenantId(target.getTenantUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setSessionId(uuid(118)) + .setRealmId(target.getRealmUuid()) + .setRequestId(request) + .setPlayableStateScope("SHARED") + .setCharacterId(character) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterResponse selectedCreatedResponse( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + CanonicalSelectedPlayerCreatedCharacterRequest request) { + byte[] originalAction = CharacterCreateOperatorActionCodec.encode(action); + String mutationDigest = CharacterCreateOperatorActionCodec.mutationDigest(originalAction); + ReadOriginalCharacterCreateRequest originalRequest = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setMutationDigest(mutationDigest) + .build(); + CommitProtectedCharacterCreateRequest terminalRequest = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(originalRequest) + .setAccountProtection(protectionReference(121)) + .setGameSessionProtection(protectionReference(122)) + .setWorldProtection(protectionReference(123)) + .build(); + ReadOriginalCharacterCreateResponse accountOriginal = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setCreateCharacterRequestId(uuid(124)) + .setConnectScopeId("controlled-connect-scope") + .setAuthenticatedAccountId(action.target().accountId()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(originalAction)) + // This opaque fixture is preserved as bytes and is not treated as remote authority. + .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-source-readback")) + .setMutationDigest(mutationDigest) + .build(); + EntityCharacterCreateTerminal terminal = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest(terminalRequest) + .setAccountOriginal(accountOriginal) + .setOriginalAccountProtection(ByteString.copyFromUtf8("account-protection")) + .setOriginalGameSessionProtection(ByteString.copyFromUtf8("game-session-protection")) + .setOriginalWorldProtection(ByteString.copyFromUtf8("world-protection")) + .setEntityIntakeRequestId(uuid(125)) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(request.getSelectedCharacterUuid()) + .setTerminalId(uuid(126)) + .setTerminalFence(1) + .setCompletedAt("2026-10-23T00:00:00Z") + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .build(); + return CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(target) + .setSnapshot(request.getExpectedSnapshot()) + .setSourceIdentity(source) + .setCreationOperationUuid(uuid(120)) + .setMutationDigest(mutationDigest) + .setTerminal(terminal) + .build(); + } + + private static CharacterCreateProtectionReference protectionReference(int value) { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(uuid(value)) + .setProtectionFence(1) + .build(); + } + + private static String rawDigest(String prefixedDigest) { + return prefixedDigest.substring("sha256:".length()); + } + + private static void assertRejected( + CanonicalSelectedPlayerCreatedCharacterRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse response) { + assertThrows( + IllegalArgumentException.class, + () -> CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, response)); + } + + private static void assertRejectedWithSource( + Fixture fixture, CanonicalPlayerCreatedRosterSourceIdentity source) { + var request = selectedCreatedRequest(fixture.action(), fixture.target(), source, CHARACTER_1); + var response = fixture.response().toBuilder().setSourceIdentity(source).build(); + assertRejected(request, response); + } + + private static void assertRejectedWithTarget( + Fixture fixture, CanonicalGameplayRosterTarget target) { + var request = selectedCreatedRequest(fixture.action(), target, fixture.source(), CHARACTER_1); + var response = fixture.response().toBuilder().setTarget(target).build(); + assertRejected(request, response); + } + + private static ByteString bytesWithSize(int size) { + ByteString megabyte = ByteString.copyFrom(new byte[1024 * 1024]); + ByteString result = ByteString.EMPTY; + int remaining = size; + while (remaining >= megabyte.size()) { + result = result.concat(megabyte); + remaining -= megabyte.size(); + } + if (remaining > 0) result = result.concat(megabyte.substring(0, remaining)); + return result; + } + + private static CanonicalPlayerCreatedRosterResponse response( + CanonicalPlayerCreatedRosterRequest request, List actors) { + String digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), + request.getExpectedTarget(), + request.getExpectedSource(), + actors); + return CanonicalPlayerCreatedRosterResponse.newBuilder() + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .setSourceIdentity(request.getExpectedSource()) + .build(); + } + + private static CanonicalPlayerCreatedRosterRequest request( + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + PlayerExecutionContext context) { + return CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(uuid(5)) + .setCanonicalAccountUuid(ACCOUNT) + .setExpectedTarget(target) + .setPlayerExecutionContext(context) + .setExpectedSource(source) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterRequest selectedRequest( + PlayerExecutionContext context) { + return CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(uuid(5)) + .setCanonicalAccountUuid(ACCOUNT) + .setSelectedCharacterUuid(CHARACTER_1) + .setExpectedTarget(target()) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(SNAPSHOT) + .setSnapshotDigest("a".repeat(64))) + .setPlayerExecutionContext(context) + .setExpectedSource(source()) + .build(); + } + + private static PlayerExecutionContext context(String character) { + var builder = + PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT) + .setTenantId(uuid(10)) + .setPlayableStateNamespaceId(uuid(11)) + .setGameInstanceId(uuid(12)) + .setSessionId(uuid(13)) + .setRealmId(uuid(14)) + .setRequestId(uuid(5)) + .setPlayableStateScope("SHARED"); + if (character != null) builder.setCharacterId(character); + return builder.build(); + } + + private static CanonicalGameplayRosterTarget target() { + return target(0); + } + + private static CanonicalGameplayRosterTarget target(int variant) { + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(uuid(10)) + .setRealmUuid(uuid(14)) + .setWorldSlug("world") + .setRealmSlug("realm") + .setGameInstanceUuid(uuid(12)) + .setCatalogRevision(7) + .setPublishedPolicyDigest("a".repeat(64)) + .setPublishedReleaseBundleRef("release/one") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setPlayableStateNamespaceUuid(uuid(11)) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCanonicalVersionUuid(uuid(15)) + .setPointerVersion(variant == 0 ? 2 : 3) + .setActiveWorldEpoch(4) + .build(); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source() { + return source(0); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source(int variant) { + return CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(uuid(20 + variant)) + .setDescriptorRevisionUuid(uuid(30)) + .setDescriptorDigest("sha256:" + "d".repeat(64)) + .setAuthoredBindingUuid(uuid(40)) + .setAuthoredBindingDigest("sha256:" + "e".repeat(64)) + .build(); + } + + private static CanonicalGameplayRosterActor actor(String character, String displayName) { + return CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(character) + .setDisplayName(displayName) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build(); + } + + private static String uuid(int value) { + return new UUID(0L, value).toString(); + } +} diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java new file mode 100644 index 0000000000..2779b4df53 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java @@ -0,0 +1,508 @@ +package net.firedevops.firemud.common.testing; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationRequest; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** + * Controlled complete CHARACTER_CREATE values for transport proofs only. Foreign protection and + * source-readback bytes are stipulated fixtures; this class grants no authenticated owner custody. + */ +public final class ControlledPlayerCreatedRosterTerminalFixtures { + private ControlledPlayerCreatedRosterTerminalFixtures() {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "All retained generated protobuf messages are immutable.") + public record Bundle( + GetCanonicalGameplayRosterReferenceRequest originalRequest, + GetCanonicalGameplayRosterReferenceResponse original, + CanonicalSelectedPlayerCreatedCharacterResponse selected, + CanonicalGameplayRosterRetirementAcknowledgementRequest acknowledgementRequest, + CanonicalGameplayRosterRetirementAcknowledgementResponse acknowledgement, + CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "All retained generated protobuf messages are immutable.") + public Bundle {} + } + + /** One real canonical action/terminal with a controlled 5 MiB opaque Account protection. */ + public static Bundle withFiveMebibyteAccountProtection(String namespace) { + return build(namespace, false, false); + } + + /** + * Controlled known-field vector: saturates every opaque byte field and the authored projection. + */ + public static Bundle withMaximumOpaqueProtections(String namespace, boolean highEntropy) { + return build(namespace, true, highEntropy); + } + + private static Bundle build(String namespace, boolean maximum, boolean highEntropy) { + var action = maximum ? largestFeedbackAction(action(namespace)) : action(namespace); + var target = target(action); + var source = source(action); + var account = action.target().accountId(); + var operation = uuid(117); + var character = uuid(2); + var context = + PlayerExecutionContext.newBuilder() + .setRequestId(operation) + .setAccountId(account) + .setSessionId(uuid(118)) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .setGameInstanceId(target.getGameInstanceUuid()) + .build(); + var rosterRequest = + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(operation) + .setCanonicalAccountUuid(account) + .setExpectedTarget(target) + .setExpectedSource(source) + .setPlayerExecutionContext(context) + .build(); + var actors = + List.of( + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(character) + .setDisplayName("Persisted created actor") + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()); + var digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest(account, target, source, actors); + var roster = + CanonicalPlayerCreatedRosterEvidence.requireResponse( + rosterRequest, + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(source) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(account) + .setTarget(target) + .setSnapshotUuid(uuid(4)) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .build()); + var selectedRequest = + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(operation) + .setCanonicalAccountUuid(account) + .setSelectedCharacterUuid(character) + .setExpectedTarget(target) + .setExpectedSource(source) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(uuid(4)) + .setSnapshotDigest(digest)) + .setPlayerExecutionContext(context.toBuilder().setCharacterId(character)) + .build(); + var selected = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( + selectedRequest, + selectedCreatedResponse(action, target, source, selectedRequest, maximum, highEntropy)); + var originalRequest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(operation), + UUID.fromString(account), + UUID.fromString(uuid(118)), + namespace, + target, + source); + var original = + CanonicalGameplayRosterReferenceEvidence.requireResponse( + originalRequest, + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + originalRequest, 1L, UUID.fromString(uuid(130)), roster) + .toBuilder() + .setSelectionInput( + CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("1")) + .setSelectedCharacterUuid(character) + .setCanonicalSelectedPlayerCreatedCharacterReceipt(selected.toByteString()) + .setTerminalOutcome("SELECTED") + .build()); + var retired = + CanonicalGameplayRosterReferenceEvidence.sealRetirement( + original.toBuilder() + .setState( + CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) + .setRetirementUuid(uuid(131)) + .setSupersedingPointerDigest("e".repeat(64)) + .setSupersedingPointerVersion(target.getPointerVersion() + 1) + .setSupersedingCatalogRevision(target.getCatalogRevision()) + .setSupersedingWorldEpoch(target.getActiveWorldEpoch()) + .build()); + var request = + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(originalRequest) + .setObservedRetirement(retired) + .setObservationUuid(uuid(132)) + .setAdmissionUuid(uuid(133)) + .setSnapshotUuid(uuid(4)) + .setSnapshotDigest(digest) + .setMinimumRetentionMillis(1000) + .build()); + var acknowledgement = + CanonicalGameplayRosterRetirementEvidence.response( + request, UUID.fromString(uuid(134)), 1000); + return new Bundle( + originalRequest, + original, + selected, + request, + acknowledgement, + CanonicalGameplayRosterRetirementEvidence.confirmation(request, acknowledgement)); + } + + private static CanonicalGameplayRosterTarget target(CharacterCreateOperatorAction action) { + var target = action.target(); + var expected = action.expectedVersion(); + long catalogRevision = Long.parseLong(expected.catalogRevision()); + long pointerVersion = Long.parseLong(expected.pointerVersion()); + long worldEpoch = Long.parseLong(expected.activeLifecycleEpoch()); + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(action.scope().tenantId()) + .setRealmUuid(target.realmId()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(target.gameInstanceId()) + .setCatalogRevision(catalogRevision) + .setPublishedPolicyDigest("e".repeat(64)) + .setPublishedReleaseBundleRef("release/controlled-player-created") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCanonicalVersionUuid(target.versionId()) + .setPointerVersion(pointerVersion) + .setActiveWorldEpoch(worldEpoch) + .build(); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source( + CharacterCreateOperatorAction action) { + var authored = action.mutation().authoredSource(); + PlayerCreationDescriptor descriptor = + PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); + return CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(authored.bindingId()) + .setAuthoredBindingDigest(authored.bindingDigest()) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterResponse selectedCreatedResponse( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + CanonicalSelectedPlayerCreatedCharacterRequest request, + boolean maximum, + boolean highEntropy) { + byte[] originalAction = CharacterCreateOperatorActionCodec.encode(action); + String mutationDigest = CharacterCreateOperatorActionCodec.mutationDigest(originalAction); + ReadOriginalCharacterCreateRequest originalRequest = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setMutationDigest(mutationDigest) + .build(); + CommitProtectedCharacterCreateRequest terminalRequest = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(originalRequest) + .setAccountProtection(protectionReference(121)) + .setGameSessionProtection(protectionReference(122)) + .setWorldProtection(protectionReference(123)) + .build(); + ReadOriginalCharacterCreateResponse accountOriginal = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setCreateCharacterRequestId(uuid(124)) + .setConnectScopeId("controlled-connect-scope") + .setAuthenticatedAccountId(action.target().accountId()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(originalAction)) + // This opaque fixture is preserved as bytes and is not treated as remote authority. + .setOriginalSourceReadback( + maximum + ? opaque(32 * 1024 * 1024, 301, highEntropy) + : ByteString.copyFromUtf8("controlled-source-readback")) + .setMutationDigest(mutationDigest) + .build(); + EntityCharacterCreateTerminal terminal = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest(terminalRequest) + .setAccountOriginal(accountOriginal) + .setOriginalAccountProtection( + maximum + ? opaque(40 * 1024 * 1024, 302, highEntropy) + : ByteString.copyFrom(new byte[5 * 1024 * 1024])) + .setOriginalGameSessionProtection( + maximum + ? opaque(48 * 1024 * 1024, 303, highEntropy) + : ByteString.copyFromUtf8("game-session-protection")) + .setOriginalWorldProtection( + maximum + ? opaque(48 * 1024 * 1024, 304, highEntropy) + : ByteString.copyFromUtf8("world-protection")) + .setEntityIntakeRequestId(uuid(125)) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(request.getSelectedCharacterUuid()) + .setTerminalId(uuid(126)) + .setTerminalFence(1) + .setCompletedAt("2026-10-23T00:00:00Z") + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .build(); + return CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(target) + .setSnapshot(request.getExpectedSnapshot()) + .setSourceIdentity(source) + .setCreationOperationUuid(uuid(120)) + .setMutationDigest(mutationDigest) + .setTerminal(terminal) + .build(); + } + + private static ByteString opaque(int size, long seed, boolean highEntropy) { + var random = new java.util.Random(seed); + byte[] chunk = new byte[64 * 1024]; + var output = ByteString.newOutput(chunk.length); + for (int remaining = size; remaining > 0; ) { + int count = Math.min(remaining, chunk.length); + if (highEntropy) random.nextBytes(chunk); + output.write(chunk, 0, count); + remaining -= count; + } + return output.toByteString(); + } + + private static CharacterCreateOperatorAction largestFeedbackAction( + CharacterCreateOperatorAction base) { + CharacterCreateOperatorActionCodec.encode(base); + CharacterCreateOperatorAction best = base; + int low = 1; + int high = CharacterCreateOperatorActionCodec.MAX_EXACT_UTF8_SOURCE_BYTES; + while (low <= high) { + int count = low + (high - low) / 2; + var candidate = withFeedbackText(base, "x".repeat(count)); + try { + CharacterCreateOperatorActionCodec.encode(candidate); + best = candidate; + low = count + 1; + } catch (IllegalArgumentException beyondKnownFieldLimit) { + high = count - 1; + } + } + return best; + } + + private static CharacterCreateOperatorAction withFeedbackText( + CharacterCreateOperatorAction base, String text) { + var mutation = base.mutation(); + var source = mutation.authoredSource(); + var prior = source.safeFeedback(); + String definition = prior.definitionJson().replace("Welcome, traveler.", text); + final String digest; + try { + digest = + "sha256:" + + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(definition.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + var feedback = + new CharacterCreateOperatorAction.Rule( + prior.key(), + definition, + digest, + prior.sourceCommitId(), + prior.sourceCommitDigest(), + prior.revisionId(), + prior.revisionOrder()); + var authored = + new CharacterCreateOperatorAction.AuthoredSource( + source.schema(), + source.bindingId(), + source.bindingDigest(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.worldSourceOperationId(), + source.worldSourceEvidenceDigest(), + source.worldSlug(), + source.publicationWorkflowId(), + source.selectedCommitId(), + source.selectedCommitDigest(), + source.policy(), + source.core(), + source.descriptor(), + source.disposition(), + feedback); + return new CharacterCreateOperatorAction( + base.scope(), + base.target(), + base.expectedVersion(), + new CharacterCreateOperatorAction.Mutation( + mutation.purpose(), + mutation.entryPolicy(), + mutation.catalog(), + mutation.pointer(), + authored, + mutation.canonicalCreationInput()), + base.auditReason()); + } + + private static CharacterCreateProtectionReference protectionReference(int value) { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(uuid(value)) + .setProtectionFence(1) + .build(); + } + + // Same complete base-public-player-created action values as the Common codec vector. + private static CharacterCreateOperatorAction action(String namespace) { + return new CharacterCreateOperatorAction( + new CharacterCreateOperatorAction.Scope( + namespace, + "a1000000-0000-4000-8000-000000000001", + "a3000000-0000-4000-8000-000000000001", + CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + new CharacterCreateOperatorAction.Target( + "a4000000-0000-4000-8000-000000000001", + "a2000000-0000-4000-8000-000000000001", + "ember-vale", + "salt-harbor", + "a5000000-0000-4000-8000-000000000001", + "a6000000-0000-4000-8000-000000000001"), + new CharacterCreateOperatorAction.ExpectedVersion( + "17", + "23", + "31", + Instant.parse("2026-10-11T12:34:56.123456789Z"), + Instant.parse("2026-10-11T12:39:56.987654321Z")), + new CharacterCreateOperatorAction.Mutation( + "CHARACTER_CREATE", + "PLAYER_CREATED", + new CharacterCreateOperatorAction.Catalog( + "a1000000-0000-4000-8000-000000000001", + "tideward", + "ember-vale", + "Ember Reach", + "a2000000-0000-4000-8000-000000000001", + "salt-harbor", + "Salt Harbor", + true, + true, + "SHARED", + "a3000000-0000-4000-8000-000000000001", + "PLAYER_CREATED", + "17"), + new CharacterCreateOperatorAction.Pointer( + "a1000000-0000-4000-8000-000000000001", + "a2000000-0000-4000-8000-000000000001", + "ember-vale", + "salt-harbor", + "OPEN", + "a5000000-0000-4000-8000-000000000001", + "23", + "17", + Instant.parse("2026-10-11T12:30:01.012345678Z")), + new CharacterCreateOperatorAction.AuthoredSource( + "game-design-authored-initial-actor-core-projection/v1", + "a7000000-0000-4000-8000-000000000001", + "sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a", + "a1000000-0000-4000-8000-000000000001", + "a6000000-0000-4000-8000-000000000001", + "a8000000-0000-4000-8000-000000000001", + "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "ember-vale", + "published-ember-workflow-2026-10-11", + "a9000000-0000-4000-8000-000000000001", + "sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a", + new CharacterCreateOperatorAction.Policy( + "aa000000-0000-4000-8000-000000000001", + "ab000000-0000-4000-8000-000000000001", + "policy-logical-ember-r4", + "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1"), + new CharacterCreateOperatorAction.Core( + "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"), + new CharacterCreateOperatorAction.Descriptor( + "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415"), + new CharacterCreateOperatorAction.Rule( + "newcomer", + "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "ae000000-0000-4000-8000-000000000001", + "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "af000000-0000-4000-8000-000000000001", + "41"), + new CharacterCreateOperatorAction.Rule( + "welcome", + "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "ae000000-0000-4000-8000-000000000001", + "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "b0000000-0000-4000-8000-000000000001", + "42")), + "{}"), + CharacterCreateOperatorAction.AuditReason.ABSENT); + } + + private static String uuid(int value) { + return new UUID(0L, value).toString(); + } +} diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java index ed87ad4d05..5fcebb233d 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java @@ -4,6 +4,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.CertificateEncodingException; @@ -14,6 +15,8 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; /** Test-only PKI for loopback mTLS proofs. */ @@ -102,6 +105,34 @@ public Identity identity(String alias) { return identity; } + /** Creates fresh server key managers using the existing issued identity and CA chain. */ + public KeyManagerFactory keyManagerFactory(Identity identity) + throws GeneralSecurityException, IOException { + char[] password = STORE_PASSWORD.toCharArray(); + KeyStore store = KeyStore.getInstance("PKCS12"); + store.load(null, password); + store.setKeyEntry( + "identity", + identity.privateKey(), + password, + new X509Certificate[] {identity.certificate(), caCertificate}); + KeyManagerFactory factory = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + factory.init(store, password); + return factory; + } + + /** Creates fresh trust managers containing only this fixture's CA. */ + public TrustManagerFactory trustManagerFactory() throws GeneralSecurityException, IOException { + KeyStore store = KeyStore.getInstance("PKCS12"); + store.load(null, null); + store.setCertificateEntry("test-ca", caCertificate); + TrustManagerFactory factory = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(store); + return factory; + } + public CommonGrpcClientProperties clientProperties(Path directory, Identity identity) throws IOException, CertificateEncodingException { Path clientDirectory = Files.createTempDirectory(directory, "loopback-mtls-client-"); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java index d21104276b..1d67f596b4 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java @@ -6,6 +6,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.GrpcServiceConfigurer; import org.springframework.grpc.server.service.GrpcServiceDiscoverer; /** Shared test configuration for contexts that should not start or discover real gRPC servers. */ @@ -18,6 +19,12 @@ GrpcServerLifecycle grpcServerLifecycle() { return mock(GrpcServerLifecycle.class); } + @Bean + @Primary + GrpcServiceConfigurer grpcServiceConfigurer() { + return mock(GrpcServiceConfigurer.class); + } + @Bean @Primary GrpcServiceDiscoverer grpcServiceDiscoverer() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfiguration.java new file mode 100644 index 0000000000..cd3cd0d7ea --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfiguration.java @@ -0,0 +1,25 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.boot.grpc.server.autoconfigure.ConditionalOnGrpcServerEnabled; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration(proxyBeanMethods = false) +public class GameSessionGrpcRequestByteConfiguration { + @Bean + public GrpcRequestBytePolicy gameSessionGrpcRequestBytePolicy() { + return GrpcRequestBytePolicy.createdRosterRetirement(); + } + + @Bean + @ConditionalOnGrpcServerEnabled + SmartInitializingSingleton requireGameSessionBoundedGrpcServerFactory( + BoundedGrpcServerFactory factory) { + // A required typed bean dependency prevents plain Spring factory fallback if shared + // request-bound auto-configuration is accidentally omitted or excluded. + return () -> java.util.Objects.requireNonNull(factory); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java index 454b9c41d4..747bf7223f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -45,6 +45,7 @@ import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalUnavailableException; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -93,6 +94,7 @@ class InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest { @BeforeAll static void controlledSigningKey() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); var generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(3072); keys = generator.generateKeyPair(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java new file mode 100644 index 0000000000..627f0ccb5c --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java @@ -0,0 +1,345 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; +import com.google.protobuf.Empty; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.TlsServerCredentials; +import io.grpc.protobuf.ProtoUtils; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.gamesession.config.GameSessionGrpcRequestByteConfiguration; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.GrpcService; + +class GameSessionGrpcRequestByteConfigurationTest { + @Test + void onlyGeneratedAcknowledgementAndConfirmationDescriptorsReceiveLargeAdmission() { + var policy = new GameSessionGrpcRequestByteConfiguration().gameSessionGrpcRequestBytePolicy(); + assertThat(policy.transportMaximumBytes()) + .isEqualTo(CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + var transportProperties = + new org.springframework.boot.context.properties.bind.Binder( + new org.springframework.boot.context.properties.source + .MapConfigurationPropertySource( + java.util.Map.of( + "spring.grpc.server.max-inbound-message-size", + policy.transportMaximumBytes() + "B"))) + .bind( + "spring.grpc.server", + org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties.class) + .get(); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + policy, + Math.toIntExact(transportProperties.getMaxInboundMessageSize().toBytes())); + Map parsedMessages = new HashMap<>(); + factory.addService( + recordOriginalMessages( + new CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase() {}.bindService(), + parsedMessages)); + var ordinary = + MethodDescriptor.newBuilder() + .setFullMethodName("test.Unrelated/Read") + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + factory.addService( + recordOriginalMessages( + ServerServiceDefinition.builder("test.Unrelated") + .addMethod( + ordinary, + io.grpc.stub.ServerCalls.asyncUnaryCall( + (request, response) -> { + response.onNext(Empty.getDefaultInstance()); + response.onCompleted(); + })) + .build(), + parsedMessages)); + Server server = factory.createServer(); + try { + // Well-formed protobuf unknown fields exercise parsing without domain authorization. + byte[] exact = rawRequest(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + byte[] oversized = rawRequest(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES + 1); + for (var service : server.getServices()) { + for (var method : service.getMethods()) { + String name = method.getMethodDescriptor().getFullMethodName(); + boolean retirementException = + name.equals( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod() + .getFullMethodName()) + || name.equals( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getConfirmCanonicalGameplayRosterRetirementAcknowledgementMethod() + .getFullMethodName()); + // The generated base reports UNIMPLEMENTED only after parsing and unary dispatch. + Status.Code admittedOutcome = + name.equals(ordinary.getFullMethodName()) + ? Status.Code.OK + : Status.Code.UNIMPLEMENTED; + assertThat(dispatch(method, exact).getCode()).isEqualTo(admittedOutcome); + assertThat(parsedMessages.get(name)).isEqualTo(1); + assertThat(dispatch(method, oversized).getCode()) + .isEqualTo(retirementException ? admittedOutcome : Status.Code.RESOURCE_EXHAUSTED); + assertThat(parsedMessages.get(name)).isEqualTo(retirementException ? 2 : 1); + if (retirementException) { + int maximum = + name.equals( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod() + .getFullMethodName()) + ? CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES + : CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES; + var abovePurposeMaximum = new OversizedRawStream(maximum + 1); + assertThat(dispatch(method, abovePurposeMaximum).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED); + assertThat(abovePurposeMaximum.consumed).isEqualTo(maximum + 1); + assertThat(parsedMessages.get(name)).isEqualTo(2); + } + } + } + } finally { + server.shutdownNow(); + } + } + + @Test + void activeGameSessionPolicyFailsStartupWithoutSharedGuardOrWithPlainFactory() { + var runner = productionRunner(false); + runner.run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf( + org.springframework.beans.factory.NoSuchBeanDefinitionException.class); + }); + runner + .withBean( + GrpcServerFactory.class, + () -> + new ShadedNettyGrpcServerFactory( + "127.0.0.1:0", List.of(), null, null, TlsServerCredentials.ClientAuth.NONE)) + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf( + org.springframework.beans.factory.NoSuchBeanDefinitionException.class); + }); + } + + @Test + void realProductionDiscoverySatisfiesRequiredGameSessionGuardAndClosedPolicy() { + productionRunner(true) + .run( + context -> { + assertThat(context).hasNotFailed().hasSingleBean(GrpcServerFactory.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); + assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + }); + } + + private static byte[] rawRequest(int size) { + int payloadSize = + size + - CodedOutputStream.computeTagSize(9999) + - CodedOutputStream.computeUInt32SizeNoTag(size); + byte[] raw = + Empty.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 9999, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFrom(new byte[payloadSize])) + .build()) + .build()) + .build() + .toByteArray(); + assertThat(raw).hasSize(size); + return raw; + } + + private static ServerServiceDefinition recordOriginalMessages( + ServerServiceDefinition service, Map messages) { + return ServerInterceptors.intercept( + service, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>( + next.startCall(call, headers)) { + @Override + public void onMessage(Q message) { + messages.merge(call.getMethodDescriptor().getFullMethodName(), 1, Integer::sum); + super.onMessage(message); + } + }; + } + }); + } + + private static Status dispatch(ServerMethodDefinition definition, byte[] raw) { + return dispatch(definition, new ByteArrayInputStream(raw)); + } + + @SuppressWarnings("unchecked") + private static Status dispatch(ServerMethodDefinition definition, InputStream raw) { + // The bounded production factory's public adapter uses InputStream in both directions. + var method = (ServerMethodDefinition) definition; + var call = new RecordingCall(method.getMethodDescriptor()); + var listener = method.getServerCallHandler().startCall(call, new Metadata()); + listener.onMessage(method.getMethodDescriptor().parseRequest(raw)); + listener.onHalfClose(); + listener.onComplete(); + assertThat(call.closed).hasSize(1); + return call.closed.getFirst(); + } + + /** + * Finite unknown-length source; the guard's real readNBytes still allocates its admission buffer. + */ + private static final class OversizedRawStream extends InputStream { + private int remaining; + private int consumed; + + private OversizedRawStream(int size) { + remaining = size; + } + + @Override + public int read() { + if (remaining == 0) { + return -1; + } + remaining--; + consumed++; + return 255; + } + + @Override + public int read(byte[] buffer, int offset, int length) { + if (length == 0) { + return 0; + } + if (remaining == 0) { + return -1; + } + int count = Math.min(length, remaining); + Arrays.fill(buffer, offset, offset + count, (byte) 255); + remaining -= count; + consumed += count; + return count; + } + + @Override + public int available() { + return 0; + } + } + + private static final class RecordingCall extends ServerCall { + private final MethodDescriptor method; + private final List closed = new ArrayList<>(); + + private RecordingCall(MethodDescriptor method) { + this.method = method; + } + + @Override + public void request(int count) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(InputStream response) {} + + @Override + public void close(Status status, Metadata trailers) { + closed.add(status); + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return method; + } + } + + private static ApplicationContextRunner productionRunner(boolean includeGuard) { + var runner = + new ApplicationContextRunner() + .withUserConfiguration(GameSessionGrpcRequestByteConfiguration.class) + .withBean(TestRosterService.class, TestRosterService::new) + .withPropertyValues( + "spring.grpc.server.port=0", "spring.grpc.server.ssl.enabled=false"); + return includeGuard + ? runner.withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonGrpcRequestBoundsAutoConfiguration.class, + GrpcServerFactoryAutoConfiguration.class, + GrpcServerAutoConfiguration.class)) + : runner.withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + GrpcServerFactoryAutoConfiguration.class, + GrpcServerAutoConfiguration.class)); + } + + @GrpcService + static class TestRosterService + extends CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase {} +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 41e9d23b1a..b99e790051 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -42,7 +42,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; -import org.springframework.grpc.server.service.GrpcServiceDiscoverer; import org.springframework.test.util.TestSocketUtils; /** Shared bootstrap helpers for nested cross-service Spring application contexts in tests. */ @@ -144,9 +143,7 @@ public static GameSessionHolder startGameSession( props.put("spring.flyway.locations", "filesystem:" + gameSessionMigrationDir()); props.put( "spring.autoconfigure.exclude", - "org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration," - + "org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration," - + "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration"); + "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration"); props.put("firemud.services.gameLogicService", "localhost:" + gameLogicPort); props.put("firemud.services.accountService", "localhost:" + accountPort); props.put("firemud.grpc.plaintext", "true"); @@ -213,12 +210,6 @@ ConflictTracker conflictTracker() { return key -> {}; } - @Bean - @Primary - GrpcServiceDiscoverer grpcServiceDiscoverer() { - return org.mockito.Mockito.mock(GrpcServiceDiscoverer.class); - } - @Bean @Primary ModerationPolicyClient moderationPolicyClient() { diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java index ed0eca9cac..1515193573 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java @@ -142,21 +142,21 @@ private static GatewayHolder startGateway(String upstreamUrl) { TEST_UPSTREAM_URL.set(upstreamUrl); return new GatewayHolder( ReactiveTestApplicationSupport.startReactiveApp( - Map.of( - "spring.profiles.active", - "test", - "spring.flyway.enabled", - "false", - "firemud.database.enabled", - "false", - GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT, - "", - GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER, - ""), + Map.ofEntries( + Map.entry("spring.profiles.active", "test"), + Map.entry("spring.flyway.enabled", "false"), + Map.entry("firemud.database.enabled", "false"), + propertyEntry(GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT), + propertyEntry(GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER)), SpringCloudGatewayApplication.class, GatewayBridgeTestOverrideConfiguration.class)); } + private static Map.Entry propertyEntry(String assignment) { + int separator = assignment.indexOf('='); + return Map.entry(assignment.substring(0, separator), assignment.substring(separator + 1)); + } + private record GatewayHolder(ReactiveTestApplicationSupport.ReactiveAppHolder app) { String websocketUrl() { return app.websocketUrl(); @@ -185,13 +185,13 @@ static UpstreamHolder start(int port) { Map.entry("spring.main.allow-bean-definition-overriding", "true"), Map.entry("spring.flyway.enabled", "false"), Map.entry("firemud.database.enabled", "false"), - Map.entry(GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT, ""), - Map.entry(GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, ""), - Map.entry(GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, ""), - Map.entry(GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, ""), - Map.entry(GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, ""), + propertyEntry(GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT), + propertyEntry(GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED), + propertyEntry(GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH), + propertyEntry(GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH), + propertyEntry(GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH), Map.entry("firemud.grpc.plaintext", "true"), - Map.entry(GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER, "")), + propertyEntry(GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER)), UpstreamStubApplication.class); return new UpstreamHolder(app.context(), app.port()); } @@ -265,6 +265,7 @@ ReactorResourceFactory reactorResourceFactory() { } @Configuration + @Import(NoGrpcServerTestConfiguration.class) static class GatewayBridgeTestOverrideConfiguration { @Bean @Primary diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java index fb499af3a2..9436e1439c 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.springcloudgateway.config.GatewayTcpProxyListenerProperties; import net.firedevops.firemud.springcloudgateway.config.TcpProxyTlsListener; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.TlsTestSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -56,7 +57,9 @@ class TcpProxyTlsListenerAdmissionIntegrationTest { @Test void productionConfigurationMapsHealthAndReadinessWhenInternalTlsIsDisabled() { - SpringApplication application = new SpringApplication(SpringCloudGatewayApplication.class); + SpringApplication application = + new SpringApplication( + SpringCloudGatewayApplication.class, NoGrpcServerTestConfiguration.class); application.setWebApplicationType(WebApplicationType.REACTIVE); try (ConfigurableApplicationContext context =