diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index c693fd89e8..bf12d23d73 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,6 +6,10 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status +The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. + +The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. + The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. The live `CharacterController`, `InventoryController`, `EquipmentController`, and `FriendController` REST handlers are also legacy direct adapters. They remain runtime-reachable behind baseline bearer authentication and their implemented tenant-access checks. @@ -39,10 +43,11 @@ curl http://localhost:8080/ping ## gRPC - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. -- `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 allocation and replay contract remains target state; current implementation proves denial only. +- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – separate target wire contract for the `PRESEEDED_ONLY` pre-admission roster branch. Both carry `shared.v1.PlayerExecutionContext`; its scope string is exactly `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The first binds the authenticated account/session/request and prospective tenant/realm/namespace/scope/instance target, while the second additionally binds `context.character_id` to the selected UUID and exact roster snapshot. The selection response echoes discovery bindings only; it mints no assignment receipt or admission proof, which remain with the owning downstream write/readback. The exact same-namespace Game Session workload mTLS identity is allowlisted. These reads are not actor admission or a session-binding shortcut, and their proto has no handler or activation yet. +- `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – 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` (target-state policy/descriptor/template/namespace fields) – returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates the account-to-character association before returning any roster or visibility result; an account identifier is ownership evidence, not controller identity. The target response includes exactly one published v1 entry policy (`PLAYER_CREATED`, `PRESEEDED_ONLY`, or `AUTO_PROVISIONED`) plus only its policy-applicable versioned identity: a descriptor identity/version for `PLAYER_CREATED`, a template identity/version for `AUTO_PROVISIONED`, and neither descriptor nor template fields for `PRESEEDED_ONLY`; it echoes the resolved namespace/scope. It also returns one immutable roster snapshot identity and digest for the exact target, policy/version, and ordered roster; an exact unchanged snapshot reuses both values, while a roster or policy/version change advances the identity or digest. Callers bind that snapshot for selection and retry and reject a changed snapshot rather than silently selecting a different actor. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results are explicit: policy determines the zero-result next action, one may be selected automatically, and many require explicit selection. A roster is discovery evidence, not admission authority. The current proto surface has none of the target policy, descriptor/template, namespace, or roster-snapshot fields and does not prove this boundary. +- `ListCharactersByAccount` (broader target-state policy/descriptor/template/namespace behavior) – the eventual policy-aware roster contract returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates account-to-character ownership; account identity is ownership evidence, not controller identity. The target response includes the exact published v1 entry policy and only its applicable versioned identity: descriptor/version for `PLAYER_CREATED`, template/version for `AUTO_PROVISIONED`, neither for `PRESEEDED_ONLY`; it echoes namespace/scope and returns an immutable roster snapshot identity/digest for the exact target, policy/version, and ordered roster. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results follow policy-specific next actions; a roster is discovery evidence, not admission authority. The separate `CanonicalGameplayRosterService` wire above currently specifies only the `PRESEEDED_ONLY` branch. `PLAYER_CREATED` and `AUTO_PROVISIONED` remain later-owned target branches, and the legacy numeric `ListCharactersByAccount` method is not trusted for canonical gameplay. Current handlers do not prove these target contracts. - `AutoProvisionCharacter` (target-state) – after explicit entry, idempotently provisions at most one actor from the published realm template using the trusted `{tenantId, accountId, playableStateNamespaceId}` as the at-most-one uniqueness tuple. The request carries explicit `entryPolicy=AUTO_PROVISIONED`, the unchanged discovered-entry object and `discoveredEntryDigest`, the applicable exact template identity/version, a caller-stable `autoProvisionRequestId` that is stable and unique only within that exact `{tenantId, accountId, playableStateNamespaceId}` target scope, canonical `mutationDigest`, and an explicit absent-creation-input marker following ADR 0140's fixed-position presence encoding. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks it against the canonical snapshot and applicable template identity/version. Entity recomputes the mutation digest over the immutable trusted target, `entryPolicy`, exact template identity/version, and absent-input marker, and durably guards the operation by `{tenantId, accountId, playableStateNamespaceId, autoProvisionRequestId}` separately from the at-most-one-actor constraint; these operation-guard and actor-uniqueness constraints remain distinct. An actor-uniqueness race between distinct request IDs has one winner; each loser transactionally rereads and validates the exact target, policy, template provenance, and digest, durably stores its own guard result, and returns/replays the same actor only on exact match. A loser with mismatched provenance or digest stores a terminal `IDEMPOTENCY_CONFLICT` outcome and never replaces or allocates another actor. `playableStateScope` is only server-validated routing/authorization-fence evidence and is not an alternate key; `gameInstanceId` is the replaceable active-runtime fence. The same target-scoped guard with the same digest exact-replays the persisted actor, including under concurrent delivery; the same scoped guard with a changed digest-bound intent returns `IDEMPOTENCY_CONFLICT` before allocation. A different tenant, account, or namespace selects a different target-scoped guard and must not conflict solely because the text request ID is reused; no global request registry is implied. The current surface and proof are not implemented. - `QueryActorState` – returns gameplay-attested actor resources and active conditions for a scoped character. - `ApplyActorCondition` – **target-state request:** applies a gameplay-attested active condition or transient action state for a scoped character. The canonical target request carries a dedicated operation-unique `effectId`, separate source provenance, optional expiry, and the exact release-pinned typed effect declaration/reference and digest resolved by the server-side gameplay path; caller-defined effect JSON is not mutation authority. The target mutation persists the frozen definition/release and its server-resolved typed applied-effect snapshot and digest, never a caller-supplied payload. The current request still accepts transitional `effectPayloadJson`, so this typed-plan/no-caller-payload boundary is not live enforcement yet. diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index fffe06fa22..ca02a38ca7 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -16,6 +16,10 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved. Current `GameAssetServiceImpl` refuses before accessing the multipart body or repository because Account commit-bound owner proof is unavailable; this fail-closed response does not establish upload readiness or resource-safety proof. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. The private export mechanics write content-addressed artifact and manifest objects, but public/Temporal full-version ingress remains fail-closed, and durable private-candidate isolation and approved public `/assets/**` delivery remain unimplemented. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). +### Authored-World Launch Boundary + +The canonical authored-world launch slice includes source-qualified ResolveLaunchDescriptor and exact independent GetLaunchDescriptor. Target `GetCompleteLaunchBinding` returns the exact descriptor and release-attestation evidence separately; current production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads. Game Session's evidence-only preparation and focused proof sources are present; capability and proof gaps are recorded in the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#launch-activation-cutover-and-termination). Numeric launch selectors are non-authorizing. + ## Responsibilities - Provide REST/gRPC tools and a web UI for editing game assets. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index b2969c2bb1..7e66da5da1 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -6,6 +6,16 @@ The protobuf service definitions under [../../../../protos/game-design/v1](../.. For REST endpoints, the authoritative request/response schema source is [openapi.yaml](../../../../services/game-design-service/src/main/resources/openapi.yaml). Design-doc examples should be updated to match when those schemas evolve. +## Authored-World Launch Binding + +Launch resolution is authorized by an exact canonical authored-world source, not by a legacy numeric tenant selector, a template/default tuple alone, or retained Game Session instance metadata. ResolveLaunchDescriptor binds a canonical non-nil tenant UUID, worldSlug, authored-source operation UUID and expected source-evidence digest to the control-plane request and template selection. Optional inputs retain explicit presence in the closed request digest. Game Design verifies source evidence and template ownership, then persists one immutable descriptor outcome for the exact namespace, tenant, and controlPlaneRequestId; exact retries return that original result or deterministic denial, while changed request or source scope cannot replace it. The response carries the complete authored-world request/result evidence needed for independent verification. + +GetLaunchDescriptor is a separate exact read using a fresh non-nil read-request UUID, canonical tenant UUID, world slug, control-plane request ID, and expected request/result digests. A caller compares this committed readback with the original resolve response; a successful resolve response alone is not committed-evidence proof. GetCompleteLaunchBinding reads the same exact descriptor together with its matching immutable full-version release attestation, including participant digests and manifest/artifact evidence. Descriptor evidence and release attestation remain separate digested objects and must not be substituted for one another. These reads are read-only and do not authorize Game Session instance creation, World activation, admission, or PLAY. + +The target caller matrix is: launch resolution accepts only the exact same-namespace Game Session workload identity; descriptor readback accepts same-namespace Game Session or World Management; complete-binding readback accepts same-namespace Game Session, World Management, or Entity Management. Target behavior rejects absent/malformed peer identity, noncanonical or nil UUIDs, and unknown request fields before owner reads. Legacy numeric Game Session launch selectors fail closed and are not translated into this contract. The base and production gRPC public-method lists include `ResolveLaunchDescriptor`, `GetLaunchDescriptor`, and `GetCompleteLaunchBinding` to bypass bearer validation; each method retains its method-specific same-namespace mTLS peer check. + +Current limitation: `GetCompleteLaunchBinding` authenticates those exact same-namespace candidate peers and then returns `PERMISSION_DENIED` before request validation or owner reads. No production owner-read permission or activation authority is enabled; see the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#launch-activation-cutover-and-termination). + ## Fresh-Tenant Prerequisite Implementation Status The owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented; authenticated creator authorization, Account enrollment, runtime admission, and playable proof remain unavailable. No creation RPC or activation is introduced. Current validation evidence and remaining gaps are recorded in the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#fresh-tenant-identity-prerequisite). @@ -132,7 +142,9 @@ The published realm-policy owner read is present behind the default-off `firemud - `GetDesignControlPlaneDigest` – digest surface for publish gating over normalized metadata. - `GetTemplateReferencePhase` – **Target state only; absent from the current proto and implementation:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle` – authoritative read surface for immutable release attestation used by activation, cutover preflight, and repair workflows. It also carries the canonical publish workflow identity and workflow-runtime status for operators. `NOT_FOUND` means the target version is not publish-complete; `SCHEMA_VERSION_UNSUPPORTED` means callers must fail closed until they understand the attestation schema. -- `ResolveLaunchDescriptor` – resolves template metadata and control-plane inputs into one immutable launch descriptor for a game-instance creation attempt. The request must include `controlPlaneRequestId`, and repeated calls for the same launch attempt must return the same descriptor values without re-resolving to newer attestation or patch state. The resolved descriptor now carries the real version-state CAS epoch rather than a derived release-bundle surrogate, and deterministic launch-preflight failures such as `RELEASE_BUNDLE_NOT_FOUND` and `LAUNCH_REMAP_REQUIRED` are returned as normal app errors rather than generic invalid-input collapse. When a cross-version replacement launch is valid, the descriptor now freezes the approved persisted `remapSetId` for the source/target version pair. +- `ResolveLaunchDescriptor` – resolves an exact canonical authored-world source, tenant/world selector, template, and closed optional override tuple into one immutable source-qualified descriptor. The descriptor contains request/result digests and source operation/evidence identity; exact retries replay the stored outcome, and changed reuse fails closed. +- `GetLaunchDescriptor` – independently reads the exact committed descriptor by read-request UUID, canonical tenant, world slug, control-plane request ID, and expected request/result digests. +- `GetCompleteLaunchBinding` – **Target behavior:** returns that exact descriptor together with its matching full-version release attestation and artifact/manifest evidence; it does not infer or authorize runtime admission. **Current behavior:** authenticates the exact same-namespace candidate peer, then returns `PERMISSION_DENIED` before request validation or owner reads. - `CreateTemplateRemapSet` / `ApproveTemplateRemapSet` / `GetTemplateRemapSet` – authoritative control-plane APIs for persisted version-to-version remap identities and their audit history. Game Design owns the `remapSetId` namespace consumed by replacement launch resolution and later cutover preflight. - `CanDeleteVersionAssets` – deletion-eligibility oracle for version-scoped asset prefixes. - `BeginPurgeVersionAssets` – **Target state:** CAS-guarded purge start that atomically re-checks deletion eligibility and transitions `version_asset_artifact` into purge-in-progress state. The current implementation has no database CAS or shared idempotency ledger. @@ -210,8 +222,9 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `GetDesignControlPlaneDigest(GetDesignControlPlaneDigestRequest) returns (GetDesignControlPlaneDigestResponse)` – returns normalized metadata digest used by publish gates. - `GetTemplateReferencePhase(GetTemplateReferencePhaseRequest) returns (GetTemplateReferencePhaseResponse)` – **Target state only; the current proto has no such RPC:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. -- `ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse)` – resolves template metadata and control-plane inputs into one immutable launch descriptor for a game-instance creation attempt. - Missing attestation must surface as `RELEASE_BUNDLE_NOT_FOUND`, unsupported attestation schema as `SCHEMA_VERSION_UNSUPPORTED`, and cross-version replacement launches without exactly one approved persisted remap set for the source/target pair as `LAUNCH_REMAP_REQUIRED`. +- `ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse)` – resolves a source-qualified canonical authored-world request and returns a descriptor carrying the complete request/result evidence. +- `GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse)` – performs an independent committed read using exact tenant, world, request, and expected-digest selectors. +- `GetCompleteLaunchBinding(GetLaunchDescriptorRequest) returns (GetCompleteLaunchBindingResponse)` – **Target behavior:** returns the exact descriptor plus a matching immutable release attestation; callers must compare both complete evidence objects. **Current behavior:** authenticates the exact same-namespace candidate peer, then returns `PERMISSION_DENIED` before request validation or owner reads. - `CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse)` – persists a draft remap set for a concrete `(tenantId, sourceVersionId, targetVersionId)` pair. - `ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) returns (ApproveTemplateRemapSetResponse)` – marks a persisted remap set approved for launch/cutover consumers and records approval reason. - `GetTemplateRemapSet(GetTemplateRemapSetRequest) returns (GetTemplateRemapSetResponse)` – returns the canonical remap-set payload and approval state for an existing `remapSetId`. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index cd71b9f414..d02b292f3e 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -223,12 +223,14 @@ Required deterministic failure vocabulary for the first implementation slice: These are application-level launch-preflight outcomes, not transport failures. Retries for the same `controlPlaneRequestId` must return the same deterministic business result until callers intentionally start a new launch attempt with a new `controlPlaneRequestId`. -Illustrative control-plane schema: +The current authored-world launch-binding wire contract is defined in the [Game Design API contract](./api-contracts.md#authored-world-launch-binding) and [Game Design proto](../../../../protos/game-design/v1/game_design_service.proto). `ResolveLaunchDescriptorRequest` is source-qualified by `canonical_tenant_id`, `world_slug`, `authored_world_source_operation_id`, and `expected_authored_world_source_evidence_digest`; its response carries the complete authored-world binding evidence. Plugin-selection and named rollback-target fields are not part of this current wire contract. -- Request: `ResolveLaunchDescriptorRequest { tenantId, gameTemplateId, controlPlaneRequestId, requestedRuntimeFlags?, requestedScriptPatchVersion?, requestedPluginSelection?: { mode: EMPTY | EXPLICIT | REUSE_ROLLBACK_TARGET, enabledPluginVersions[]? { pluginId, pluginVersionId } }, sourceVersionId?, targetVersionId?, rollbackTargetLaunchDescriptorId? }` -- Response: `ResolveLaunchDescriptorResponse { launchDescriptorId, tenantId, gameTemplateId, versionId, scriptPatchVersion (nullable; explicit null when no patch is pinned), pluginSelectionMode, enabledPluginVersions[] { pluginId, pluginVersionId }, runtimeFlags, generationConfigRevision, versionStateEpoch, remapSetId?, publishedReleaseBundleRef }` +Target-only plugin-selection and rollback illustration (not the current wire contract): -The exact transport schema may evolve, but every implementation must preserve the same contract shape: +- Request extension: `requestedPluginSelection?: { mode: EMPTY | EXPLICIT | REUSE_ROLLBACK_TARGET, enabledPluginVersions[]? { pluginId, pluginVersionId } }`, `rollbackTargetLaunchDescriptorId?`. +- Response extension: `pluginSelectionMode`, `enabledPluginVersions[] { pluginId, pluginVersionId }`. + +These target-only fields do not replace or relax the current authored-world source binding. If implemented, their transport must preserve the following plugin-selection semantics: - request fields identify the template, the launch attempt identity, and any caller-supplied runtime overrides that are allowed to participate in deterministic resolution; - response fields are the immutable resolved values consumed by launch-time workflows; @@ -243,9 +245,9 @@ The exact transport schema may evolve, but every implementation must preserve th Before computing the request idempotency digest, normalization rejects `EMPTY` with a non-empty list, `EXPLICIT` with an empty list, and `REUSE_ROLLBACK_TARGET` without a named rollback target or with any entries; accepted presence forms must first derive the modes and effective selections defined above consistently. -Normative examples: +Target-only conceptual extension illustrations (not the current wire contract or executable RPC examples): -The examples below intentionally use numeric `versionId` values because the current Game Design launch and published-bundle protobuf contracts expose `int64 version_id`. UUID-shaped version identifiers elsewhere in the target architecture must not be substituted into these current-contract examples until those transport fields are migrated together. +The current authored-world binding wire contract is defined by the [Game Design API contract](./api-contracts.md#authored-world-launch-binding) and [Game Design proto](../../../../protos/game-design/v1/game_design_service.proto). The current launch and published-bundle protobuf contracts expose numeric `int64 version_id`, so these illustrations retain numeric `versionId` values. The plugin-selection and rollback fields shown below are conceptual target extensions and are not current transport fields or executable requests. - Fresh launch from a template with no script patch pinned: diff --git a/design/architecture/microservices/game-session-service/README.md b/design/architecture/microservices/game-session-service/README.md index 871c6afd12..82c8b2433f 100644 --- a/design/architecture/microservices/game-session-service/README.md +++ b/design/architecture/microservices/game-session-service/README.md @@ -32,6 +32,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat Current seams are narrower: patch/request convergence reads, instance-scoped pause/resume, region-epoch fencing, and existing version-fence paths do not yet prove complete `scriptPinEpoch` propagation, final-effect enforcement, or Game-Session-owned append-only history. Track those implementation and proof gaps in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +The canonical authored-world launch preparation service is an evidence-only, source-backed preparation seam. It validates the committed realm catalog and source intake, resolves the canonical descriptor, independently reads it back, and persists exact prepared evidence. It is not wired into instance creation or runtime composition and does not write game_instances, call World activation, admit gameplay, or authorize PLAY; focused proof sources are present and validation is deferred. + ## Terminology - **Tenant** – a hosted game world or project, identified by `tenantId`. All database rows and Redis keys include this prefix so data is isolated between games. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 5a9995b803..7552344320 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -36,6 +36,8 @@ For script transitions, the live boundary includes the exact `scriptPinEpoch` an Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. +The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality; context `playable_state_scope` is the exact text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. Its response echoes discovery bindings and returns the original assignment operation UUID and immutable intent digest from Entity's unique matching committed receipt. Game Session binds and reuses that original reference for later owner revalidation; it does not mint an assignment identity or treat the reference as admission proof or current Account eligibility. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This Game Session source slice introduces no Entity handler or activation; [Entity API contracts](../entity-management-service/api-contracts.md#grpc) record the owning implementation status. The wire policy does not authorize other roster branches or actor admission. + For target gameplay forwarding, `PlayerExecutionContext` carries the server-resolved `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId}` binding and, for region-scoped work, its `{regionId, regionEpoch}` fence as one context. Game Session forwards the namespace and scope unchanged and validates exact context/request equality on every downstream response or mutation result; it never accepts a caller-selected namespace or substitutes a current one after admission. The current context/forwarding wire is narrower in places and does not yet carry or prove this complete namespace-plus-fence tuple, so that path remains an implementation/proof gap and must fail closed on missing authority. It also communicates game lifecycle changes to other microservices over gRPC so they can react to game instances starting, stopping, or changing runtime configuration. @@ -64,6 +66,24 @@ An exact retry or post-restart recovery reuses the same attempt and hold identit The local run-owned Compose fixture path now reaches this owner transaction through a scheduled Game Session coordinator, explicitly disabled by default. It accepts only a read-only capability file bound to the claimed run and Compose project, one stable operation ID, the fixed demo/production fixture, and the exact development Game Session and World Management recipient leaf/CA pins; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the persisted Game Design launch descriptor, durably reserves the matching launch identity, and drives World prepare/activate with exact epoch readback so a restart resumes the same launch. The coordinator persists the initial-bind intent before requesting the World hold, then uses the owner-local pointer/audit/outcome transaction and World’s authenticated owner-proof reconciliation; bounded retries reuse the same operation identity, and ambiguous evidence keeps the World termination fence closed. This path is a local Compose fixture bootstrap, not the accepted Account `JOIN` transaction or a production activation path; realm identity and admission-pointer authority remain defined by the [Multi-Tenancy contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract), and explicit join remains owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). See the [run-owned player-flow smoke boundary](../../system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) and [canonical launch-evidence contract](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). Cross-service database race/restart proof remains outstanding; implementation and proof state are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) and [validation workflow](../../../developer-workflows/validation-and-runtime-proof.md). The existing cutover transaction and [replacement hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract) remain distinct; the canonical initial-bind contract is owned by [World](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +### Canonical gameplay roster owner reads + +#### Canonical gameplay roster owner read + +The internal `CanonicalGameplayRosterOwnerReadService.GetCanonicalGameplayRosterOwnerRead` method is an Entity-only point-in-time source read. It requires the exact same-namespace Entity Management mTLS workload and no authenticated caller context; the request retains its exact caller-observed pointer-version and World-epoch preconditions. The route-reader composition is disabled unless `firemud.canonical-gameplay-roster-owner-read.enabled=true`; the bearer-check allowlist does not enable its source beans. The read returns source evidence only and does not create actors, bind sessions, or activate `PLAY` or `LOOK`. + +For the Entity-only canonical roster-owner read, Game Session returns `admissionPointerSnapshotDigest` from [`CanonicalInitialAdmissionRepository.readCurrentOpenSnapshotForRealm`](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java) only after validating one current V3 `OPEN` pointer, matching its exact durable `COMMITTED` attempt and append-only audit readback, and confirming the entire pointer row is unchanged across the before/after read. Its raw lowercase 64-hex SHA-256 preimage has domain `gs-canonical-current-open-pointer-snapshot/v1` and, in fixed order, binds: representation version; target namespace; canonical tenant UUID; world slug/display name; realm UUID/slug/display name; playable-state namespace UUID and scope; positive catalog revision and pointer version; admission state; visible and public-production flags; the required-null character-selection flag; character-creation policy; canonical game-instance and version UUIDs; initial-admission request ID/digest; origin kind and nullable expected prior-pointer version; positive active World epoch; hold UUID/fence/binding digest; last-updated actor/reason; the required-null prepared-version-upgrade ID; committed outcome; owner proof digest; positive audit event ID; and terminal timestamp. `pointer.updated_at` and audit occurrence time are validated against that terminal timestamp before hashing. Pointer surrogate ID, retained numeric tenant/game-instance/runtime-version IDs, and row creation time are not canonical identity inputs; canonical UUIDs remain the identity. + +Encoding is closed and unambiguous: strings use strict UTF-8 with a signed 32-bit byte length (`-1` only for null), without Unicode normalization; UUIDs are lowercase canonical strings; representation version is fixed-width big-endian int32; every long counter uses the unique base-10 `Long.toString()` representation in the same length-prefixed UTF-8 form; booleans use one byte; nullable booleans use `0=null`, `1=false`, `2=true`; nullable prior-pointer versions use a presence boolean followed by the canonical decimal counter string when present; and the terminal instant uses canonical UTC `Instant.toString()` after database-microsecond validation. The [Common evidence carrier](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java) and [roster-read response proto](../../../../protos/game-session/v1/canonical_gameplay_roster_owner_read.proto) transport this exact digest; they do not recompute it or treat it as a second authority. It is a point-in-time current-pointer commitment, not a permission spanning a later mutation, a fresh lifecycle check, membership proof, actor ownership, or `PLAY` admission. The opaque committed owner-proof digest is included as evidence; it is not a mapping from a retained numeric row key to canonical identity. + +#### Entity preseeded-actor assignment source read + +`CanonicalGameplayRosterOwnerReadService.GetPreseededActorAssignmentOwnerRead` is an internal, Entity-only source read for non-admitting PRESEEDED actor assignment. It requires Entity Management's exact same-namespace workload identity over mTLS and no authenticated caller context. Its request selects the canonical Account and tenant plus the exact immutable realm, namespace/scope, current instance/version, catalog, policy-digest, and release selectors. It does not accept `pointerVersion` or `activeWorldEpoch`: Game Session derives both from its current OPEN pointer and terminal COMMITTED World-hold proof, then checks the complete current catalog, launch binding, and sealed Game Design policy set and rereads them before returning the request-bound evidence. The response carries the complete source proof and policy-set evidence plus the current pointer projection digest. + +Entity consumer code remains outside this Game Session source slice. The read itself is not permission to mutate actor data; Account remains the identity and membership authority, and this source method is not `JOIN` or `PLAY` admission. + +Game Session exposes a default-off `CanonicalGameplayRosterSelectionService` composition whose intended Entity reads use the typed roster wire contract defined in [Entity API contracts](../entity-management-service/api-contracts.md#grpc). No Entity handler or activation is introduced by this Game Session source slice; the Entity contract records its owning implementation and proof status. The composition accepts a `PlayerExecutionContext` already constructed from authenticated Game Session state, binds its tenant, realm, namespace, scope, and instance to the current published route, and accepts only a one-based ordinal from the validated Entity snapshot. It rereads the exact published route after each Entity read and returns only a selection menu, denial, or Entity's original assignment reference. This source-only composition does not establish membership or admission, persist a selection, bind a session, change gameplay state, or activate `PLAY` or `LOOK`; Entity remains the assignment-evidence owner, including later revalidation. + ## Session Front-End and Lease-Owner Routing Game Session deliberately separates socket ownership from region execution ownership: diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 81b87a0f2d..53663768a1 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. + - Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. @@ -57,6 +59,8 @@ The sections below define the target-state runtime contract. Current implementat Game Session does not persist or allocate the primary actor. It resolves the realm target, asks Entity Management for the valid roster/policy result, and keeps `CHARS` as discovery before `PLAY`. A normal binding requires one persisted `characterId`; controller uniqueness is `{tenantId, playableStateNamespaceId, characterId}`, with `accountId` owner evidence and `playableStateScope`, `gameInstanceId`, and region/epoch as routing/fence evidence. See [Entity Runtime and Data](../entity-management-service/runtime-and-data.md) for allocation, policy, descriptor/template, and fork-copy rules. +The current Game Session route and published-policy readers, plus the Entity-only roster and preseeded-assignment source reads, remain behind default-off composition. They return bounded source evidence; they do not persist actor assignments, attach a gameplay session, or activate `PLAY`/`LOOK`. See [API Contracts](./api-contracts.md#canonical-gameplay-roster-owner-reads) for the local read boundary. + The local runtime stores only active attachment, protocol state, presence, and controller-fence data. A playtest copy is selected by its new fork-local `characterId`; `sourceCharacterId` is not used as authority. Current per-instance lookup, unresolved-character fallback, and complete cross-service proof remain gaps. ## Owner-Local Gameplay Restrictions diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index 58ec423939..ed39acbaca 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -250,9 +250,9 @@ These workflows: - Modify **persistent storage (PostgreSQL)** across multiple services - Require compensation and persisted step status, but not durable workflow execution -For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses Entity's `ListCharactersByAccount` against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. +For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses its later-owned policy-aware Entity roster contract against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. The separate `CanonicalGameplayRosterService.ListPreseededRoster` wire specifies only the pre-admission `PRESEEDED_ONLY` lookup; `PLAYER_CREATED` remains a later-owned target branch, and neither it nor `AUTO_PROVISIONED` may fall back to the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `ListCharactersByAccount` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; a retry must validate that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. +`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `CanonicalGameplayRosterService.ListPreseededRoster` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; `ReadSelectedPreseededAssignment` requires that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. The response echoes request/account/selected-character/target/snapshot bindings and returns Entity's original assignment operation UUID and immutable intent digest from the unique matching committed receipt. The saga binds and retries with that unchanged reference so the later placement owner can revalidate the original assignment; the reference is neither minted by this read nor evidence of admission or current Account eligibility. The separate wire accepts only `PRESEEDED_ONLY`; other policy values fail with `FAILED_PRECONDITION`. `PLAYER_CREATED` remains a later-owned policy-aware roster branch, and `AUTO_PROVISIONED` remains its owner-defined idempotent existing-actor operation; neither branch may use the legacy numeric `ListCharactersByAccount` RPC as canonical gameplay authority. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. If a workflow needs restart-safe continuation, durable waits/timers, or operator-visible in-flight state that survives one service lifetime, it should use the shared Temporal substrate described in [Temporal Control-Plane Workflows](./system-architecture-temporal-workflows.md) instead of extending `SagaRunner` toward durable workflow behavior. @@ -359,7 +359,7 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): boundCreateCharacterRequestId, boundMutationDigest, boundCanonicalCreationInput) # replay before fresh-roster rejection return stored-or-replayed result - rosterSnapshot = Entity.ListCharactersByAccount(discoveredEntry, discoveredEntryDigest) + rosterSnapshot = Entity.ListCharactersByAccount(discoveredEntry, discoveredEntryDigest) # later-owned target contract; legacy numeric RPC is not canonical authority if retrying roster-selection step: require rosterSnapshot.identity == boundRosterSnapshot.identity require rosterSnapshot.digest == boundRosterSnapshot.digest @@ -396,12 +396,25 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): Entity.AutoProvisionCharacter(discoveredEntry, discoveredEntryDigest, autoProvisionRequestId, mutationDigest, canonicalCreationInput) PRESEEDED_ONLY: require creation input is absent - rosterSnapshot = Entity.ListCharactersByAccount(discoveredEntry, discoveredEntryDigest) - if retrying selection step: - require rosterSnapshot.identity == boundRosterSnapshot.identity - require rosterSnapshot.digest == boundRosterSnapshot.digest + if retrying after assignment reference was bound: + selectionReadback = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, boundRosterSnapshot.reference, selectedCharacterId) + require selectionReadback.request_uuid == boundRequest.request_uuid + require selectionReadback.canonical_account_uuid == boundRequest.canonical_account_uuid + require selectionReadback.selected_character_uuid == selectedCharacterId + require selectionReadback.target == boundRequest.expected_target + require selectionReadback.snapshot == boundRosterSnapshot.reference + require selectionReadback.assignment_uuid == boundAssignmentUuid + require selectionReadback.intent_digest == boundIntentDigest + # original persisted reference only; placement owner must revalidate it + rosterSnapshot = boundRosterSnapshot else: - bind rosterSnapshot.identity and rosterSnapshot.digest to sagaStep + rosterSnapshot = Entity.CanonicalGameplayRosterService.ListPreseededRoster(discoveredEntry, discoveredEntryDigest) + if retrying selection step: + require rosterSnapshot.identity == boundRosterSnapshot.identity + require rosterSnapshot.digest == boundRosterSnapshot.digest + rosterSnapshot = boundRosterSnapshot # preserve the original selection evidence + else: + bind rosterSnapshot.identity and rosterSnapshot.digest to sagaStep roster = rosterSnapshot.roster if roster is zero: return pre-seeded-only denial @@ -413,7 +426,15 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): resolvedSelectedCharacter = require actor matching selectedCharacterId in unchanged roster/snapshot bind resolvedSelectedCharacter.characterId to sagaStep select resolvedSelectedCharacter # lookup/selection only; no actor mutation - retries reuse the same discoveredEntry, discoveredEntryDigest, branch, applicable roster snapshot identity/digest, and resolved selectedCharacterId; an entered PLAYER_CREATED create step replays Entity before any fresh roster rejection, and each actor mutation reuses its operation request identity, mutationDigest, and canonicalCreationInput, while a changed input or roster snapshot fails closed + if assignment reference is not yet bound: + selectionReadback = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, rosterSnapshot.reference, selectedCharacterId) + require selectionReadback.request_uuid == boundRequest.request_uuid + require selectionReadback.canonical_account_uuid == boundRequest.canonical_account_uuid + require selectionReadback.selected_character_uuid == selectedCharacterId + require selectionReadback.target == boundRequest.expected_target + require selectionReadback.snapshot == rosterSnapshot.reference + bind selectionReadback.assignment_uuid and selectionReadback.intent_digest to sagaStep + retries reuse the same discoveredEntry, discoveredEntryDigest, branch, applicable roster snapshot identity/digest, and resolved selectedCharacterId; a PRESEEDED_ONLY retry before assignment-reference binding rereads and validates the original roster snapshot, then resumes the original selected-assignment read without requiring an absent assignment UUID or intent digest, while an assignment-bound retry retains the exact original tuple assertions. An entered PLAYER_CREATED create step replays Entity before any fresh roster rejection, and each actor mutation reuses its operation request identity, mutationDigest, and canonicalCreationInput, while a changed input or roster snapshot fails closed ``` This is a target-state branch illustration, not current implementation or proof. Compensation applies only to the selected mutating branch; the `PRESEEDED_ONLY` lookup has no actor mutation to compensate. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index e051361f2f..0f619ebb15 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -16,6 +16,8 @@ The subsequent CLI6/Hosted4 correction batch passed local proof on 2026-10-13: 4 This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. +Canonical authored-world launch source covers request-bound Resolve and exact descriptor Get readback. The target complete descriptor-plus-release-attestation binding is defined, but production `GetCompleteLaunchBinding` currently authenticates exact same-namespace candidate Game Session, World Management, and Entity Management peers and then denies before request validation or owner reads. Focused proof for this deny-before-owner-read boundary is pending validation; positive owner-read authorization remains pending. The matching Game Session preparation persists evidence but is not runtime-wired or admitting. Focused producer/consumer proof and prior numeric-launch evidence do not establish complete-binding authorization or activation. + Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. @@ -87,7 +89,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java); [CanonicalLaunchGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. `ResolveLaunchDescriptor`, `GetLaunchDescriptor`, and `GetCompleteLaunchBinding` are registered in the base and production gRPC public-method lists to bypass bearer validation, and each retains its method-specific same-namespace mTLS peer check. Production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index aa95dc8423..2ba7c21cb0 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -14,8 +14,12 @@ Focused unit tests cover immutable replay, descriptor comparison, certificate-pi This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. +The Entity-only roster and preseeded-assignment owner reads are a separate default-off, read-only source boundary; they do not change tick execution, attach sessions, or activate `PLAY`/`LOOK`. The focused [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) proof executed in source Validation `38362401283` on published `65bf7294a906df9fc7fdd3150ddc94572c60dc09`: Game Session completed 2,209 unit and 264 integration cases, and Game Design completed 492 unit and 114 integration cases, with zero skips. Current-head CI is pending, so these results establish bounded source proof only. This selection source has no player-command caller and does not activate `PLAY`/`LOOK`; see [Player Access and Session](./player-access-and-session.md) for AA-2.1 status and [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) for the source boundary. + Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple, and a separate source-only Account-facing current-attempt read. The latter returns the exact original pending attempt only while its owner lease and Account reference are live. Its composed Common/Game Session checks, generated SQL model, migration-version and documentation checks passed locally; PostgreSQL execution remains pending because the local database-dependent cases skipped. The RPC is not registered or deployed. The initial-admission owner-proof read returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither existing endpoint is deployed; those results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. +Ordinary legacy `StartSession` preflight remains blocked by the default-denied production owner-read RPCs; the run-owned fixture projection handoff does not establish full convergence, admission, or playability. + Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). Canonical region-bootstrap receiving preparation resolves the exact World operational UUID from a workload-pinned `ACTIVE` lifecycle read bound to the complete target request; it has no runtime registration or mutation path. Focused resolver proof does not establish real owner composition or protected currentness through a later commit. Qualified timeline persistence, the actual Redis lease/durable executor-fence handshake, same-lease staging revalidation, takeover/restart preservation, and physical composition remain open under the [Game Session runtime/data contract](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). The legacy instance-scoped runtime row and its decimal region surrogate are unchanged; neither supplies canonical initialization or playable proof. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 70d5d22698..1973b6f4de 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). + +The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. + ### Entity character-creation denial The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). @@ -143,7 +147,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index f908fd1ee5..e5a48cb4ab 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -10,6 +10,8 @@ The working realm-catalog projection, admission-pointer reads, bootstrap/connect ## Packet 4 Status and Proof Gaps +The Game Session canonical authored-world launch preparation service validates exact committed realm-catalog and source evidence, then persists authenticated descriptor resolution plus independent owner readback. This source remains evidence-only and unregistered for runtime admission: no routing pointer, game instance, World activation, PLAY, or runtime state is changed. Focused source/proof is present; validation is deferred, so no routing or playable-state capability rating is upgraded. + - `AA-3.3` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) remain the owners for namespace/replacement and lifecycle coordination. Current routing/playable-state implementation and focused proof remain partial; namespace transition, cutover, drain, cleanup, and termination proof are not established. - `AR-3.4` / `AA-3.2`: [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md), [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md), [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md), [Versioning & Runtime Configuration](../../architecture/system-architecture-versioning-runtime.md#fork-snapshot-boundary-for-playtest-realms), [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract), and [Session Behavior](../../architecture/system-architecture-session-behavior.md#playtest-grant-and-lifecycle-session-consequences) remain the canonical owners. This tracker claims no playtest/lifecycle implementation or proof; cross-owner integration remains unverified. diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 3bc971bcde..eda2eb2236 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -4,6 +4,7 @@ package entity_management.v1; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; +import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.entitymanagement.v1"; option java_multiple_files = true; @@ -36,6 +37,130 @@ 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 +// rather than in-response errors: malformed requests are INVALID_ARGUMENT, stale snapshots or +// selections not present in the bound snapshot are FAILED_PRECONDITION, unauthorized callers are +// UNAUTHENTICATED or PERMISSION_DENIED as applicable, and unavailable dependencies are +// UNAVAILABLE. No partial success is returned. +service CanonicalGameplayRosterService { + // Returns the persisted preseeded roster for the exact expected target. The server requires an + // authenticated, server-derived PlayerExecutionContext and exact same-namespace Game Session + // mTLS caller allowlisting. Context account_id equals canonical_account_uuid; request_id equals + // request_uuid; tenant_id, realm_id, playable_state_namespace_id, playable_state_scope, and + // game_instance_id equal the corresponding expected_target values; session_id identifies the + // authenticated session. Context playable_state_scope is the exact text "SHARED" or + // "ISOLATED" corresponding to the target enum value; numeric enum text is invalid. No + // character_id is selected yet. The target policy must be PRESEEDED_ONLY. These equality + // checks do not require an additional Account lookup. A successful response includes its + // immutable snapshot UUID and digest, including when the roster is empty. + rpc ListPreseededRoster(CanonicalGameplayRosterRequest) + returns (CanonicalGameplayRosterResponse); + // Reads the selected assignment only if the supplied snapshot UUID and digest still identify + // the roster from which selected_character_uuid was chosen. The response echoes that exact + // snapshot reference. A changed snapshot or selection absent from it fails with + // FAILED_PRECONDITION. It has the same authenticated context and exact target equality + // requirements as ListPreseededRoster, and context.character_id must equal + // selected_character_uuid. The target policy must be PRESEEDED_ONLY. + rpc ReadSelectedPreseededAssignment(CanonicalGameplayRosterSelectedAssignmentRequest) + returns (CanonicalGameplayRosterSelectedAssignmentResponse); +} + +message CanonicalGameplayRosterRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + CanonicalGameplayRosterTarget expected_target = 3; + shared.v1.PlayerExecutionContext player_execution_context = 4; +} + +message CanonicalGameplayRosterTarget { + string tenant_uuid = 1; + string realm_uuid = 2; + string world_slug = 3; + string realm_slug = 4; + string game_instance_uuid = 5; + int64 catalog_revision = 6; + reserved 7, 8; + string published_policy_digest = 9; + string published_release_bundle_ref = 10; + string admission_pointer_snapshot_digest = 11; + string published_owner_proof_digest = 12; + string playable_state_namespace_uuid = 13; + PlayableStateScope playable_state_scope = 14; + CanonicalGameplayRosterEntryPolicy entry_policy = 15; + string canonical_version_uuid = 16; + // Exact positive counters observed from the current owning Game Session target. + int64 pointer_version = 17; + int64 active_world_epoch = 18; +} + +enum CanonicalGameplayRosterEntryPolicy { + CANONICAL_ROSTER_ENTRY_POLICY_UNSPECIFIED = 0; + CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED = 1; + CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY = 2; + CANONICAL_ROSTER_ENTRY_POLICY_AUTO_PROVISIONED = 3; +} + +message CanonicalGameplayRosterResponse { + string canonical_account_uuid = 1; + CanonicalGameplayRosterTarget target = 2; + string snapshot_uuid = 3; + string snapshot_digest = 4; + repeated CanonicalGameplayRosterActor actors = 5; + reserved 6; + reserved "error"; +} + +// Immutable identity and content digest of one exact roster snapshot. +message CanonicalGameplayRosterSnapshotReference { + string snapshot_uuid = 1; + string snapshot_digest = 2; +} + +message CanonicalGameplayRosterActor { + string character_uuid = 1; + string display_name = 2; + CanonicalGameplayRosterActorKind actor_kind = 3; +} + +message CanonicalGameplayRosterSelectedAssignmentRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget expected_target = 4; + // Exact snapshot_uuid and snapshot_digest returned by ListPreseededRoster. Retries must reuse + // these values and may not silently select against a changed roster. + CanonicalGameplayRosterSnapshotReference expected_snapshot = 5; + shared.v1.PlayerExecutionContext player_execution_context = 6; +} + +message CanonicalGameplayRosterSelectedAssignmentResponse { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget target = 4; + // Original non-nil operation identity and immutable intent digest from the unique committed + // ASSIGNED PRESEEDED PLAYER receipt matching this exact account, actor, target, and owner proof. + // This read returns persisted owner evidence; it never mints an assignment identity or digest. + string assignment_uuid = 5; + string intent_digest = 6; + reserved 7; + reserved "error"; + // Exact snapshot reference supplied by the caller and validated by this operation. The + // response echoes that binding alongside the original persisted assignment reference. The + // reference does not prove admission or current Account eligibility; placement must revalidate + // it with its owning Entity write/readback contract. + CanonicalGameplayRosterSnapshotReference snapshot = 8; +} + +enum CanonicalGameplayRosterActorKind { + CANONICAL_ROSTER_ACTOR_KIND_UNSPECIFIED = 0; + CANONICAL_ROSTER_ACTOR_KIND_PLAYER = 1; +} + message CreateCharacterRequest { string tenant_id = 1; string account_id = 2; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java new file mode 100644 index 0000000000..f1222d4ef0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.common.entity; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRosterProtoDescriptorTest { + @Test + void canonicalRosterRequestsCarryTheTypedPlayerExecutionContext() { + assertPlayerExecutionContextField(CanonicalGameplayRosterRequest.getDescriptor(), 4); + assertPlayerExecutionContextField( + CanonicalGameplayRosterSelectedAssignmentRequest.getDescriptor(), 6); + } + + @Test + void selectedAssignmentRoundTripsTheExactTypedSnapshotReference() { + FieldDescriptor expectedSnapshot = + CanonicalGameplayRosterSelectedAssignmentRequest.getDescriptor().findFieldByNumber(5); + FieldDescriptor snapshot = + CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor().findFieldByNumber(8); + + assertThat(expectedSnapshot.getName()).isEqualTo("expected_snapshot"); + assertThat(expectedSnapshot.getMessageType()) + .isEqualTo(CanonicalGameplayRosterSnapshotReference.getDescriptor()); + assertThat(snapshot.getName()).isEqualTo("snapshot"); + assertThat(snapshot.getMessageType()) + .isEqualTo(CanonicalGameplayRosterSnapshotReference.getDescriptor()); + + Descriptor snapshotDescriptor = CanonicalGameplayRosterSnapshotReference.getDescriptor(); + assertThat(snapshotDescriptor.findFieldByNumber(1).getName()).isEqualTo("snapshot_uuid"); + assertThat(snapshotDescriptor.findFieldByNumber(2).getName()).isEqualTo("snapshot_digest"); + } + + @Test + void canonicalRosterResponsesHaveNoInResponseErrorAndReserveItsSlot() { + assertErrorSlotReserved(CanonicalGameplayRosterResponse.getDescriptor(), 6); + assertErrorSlotReserved(CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor(), 7); + assertThat(CanonicalGameplayRosterResponse.getDescriptor().findFieldByNumber(6)).isNull(); + assertThat( + CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor() + .findFieldByNumber(8) + .getName()) + .isEqualTo("snapshot"); + } + + @Test + void selectedAssignmentResponseCarriesTheOriginalAssignmentReference() { + Descriptor response = CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor(); + + assertThat(response.findFieldByNumber(5).getName()).isEqualTo("assignment_uuid"); + assertThat(response.findFieldByNumber(5).getType()).isEqualTo(FieldDescriptor.Type.STRING); + assertThat(response.findFieldByNumber(6).getName()).isEqualTo("intent_digest"); + assertThat(response.findFieldByNumber(6).getType()).isEqualTo(FieldDescriptor.Type.STRING); + assertThat(response.findFieldByNumber(7)).isNull(); + assertThat(response.toProto().getReservedRangeList()) + .anySatisfy(range -> assertThat(range.getStart()).isEqualTo(7)); + assertThat(response.toProto().getReservedNameList()).contains("error"); + } + + private static void assertErrorSlotReserved(Descriptor descriptor, int fieldNumber) { + assertThat(descriptor.toProto().getReservedRangeList()) + .anySatisfy(range -> assertThat(range.getStart()).isEqualTo(fieldNumber)); + assertThat(descriptor.toProto().getReservedNameList()).contains("error"); + } + + private static void assertPlayerExecutionContextField(Descriptor descriptor, int fieldNumber) { + FieldDescriptor context = descriptor.findFieldByNumber(fieldNumber); + assertThat(context.getName()).isEqualTo("player_execution_context"); + assertThat(context.getMessageType()).isEqualTo(PlayerExecutionContext.getDescriptor()); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index 60201917df..4aeaebbfff 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -723,6 +723,44 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorWithOptionalValue "approved-remap-41-42"); } + @Test + void completeReadRejectsUnknownFieldsOnArtifactAndErrorMessages() throws Exception { + var world = authoredWorldFixture(); + var descriptor = world.launchBinding().descriptor(); + var release = releaseWithArtifact(world.launchBinding().releaseAttestation()); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + var request = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); + var good = completeResponse(request, binding); + + var releaseWithUnknownArtifact = + good.getReleaseAttestation().toBuilder() + .setArtifactDigests( + 0, + good.getReleaseAttestation().getArtifactDigests(0).toBuilder() + .setUnknownFields(UNKNOWN_FIELD)) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setReleaseAttestation(releaseWithUnknownArtifact).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setError( + ErrorDetail.newBuilder() + .setUnknownFields(UNKNOWN_FIELD) + .setCode("DENIED")) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + private static AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest getRequest( AuthoredWorldLaunchDescriptorEvidence descriptor) { return new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 170ec88282..5f2bc1c4f4 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -53,6 +53,9 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies + - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor + - gamedesign.v1.GameDesignService/GetLaunchDescriptor + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 3ee2e497fc..aba342b57e 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -64,6 +64,9 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies + - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor + - gamedesign.v1.GameDesignService/GetLaunchDescriptor + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java index 4ab73cfb74..546d3fc31e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -94,6 +94,9 @@ private static void assertConfiguredGrpcMethods(String fileName) throws IOExcept .getFullMethodName(), PublishedRealmEntryPolicyServiceGrpc .getListPublishedRealmEntryPoliciesMethod() - .getFullMethodName())); + .getFullMethodName(), + "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor", + "gamedesign.v1.GameDesignService/GetLaunchDescriptor", + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding")); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java new file mode 100644 index 0000000000..c422c55ff0 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java @@ -0,0 +1,547 @@ +package unit.net.firedevops.firemud.gamedesign.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Message; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PingService; +import net.firedevops.firemud.gamedesign.service.RevisionService; +import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflowMetadataResolver; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; +import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +class CanonicalLaunchGrpcAuthWiringTest { + private static final String RESOLVE_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor"; + private static final String GET_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/GetLaunchDescriptor"; + private static final String GET_COMPLETE_LAUNCH_BINDING_METHOD = + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding"; + private static final String UNLISTED_METHOD = + "gamedesign.v1.GameDesignService/GetPublishedReleaseBundle"; + private static final List ALLOWLISTED_METHODS = + List.of( + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy", + "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies", + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + GET_LAUNCH_DESCRIPTOR_METHOD, + GET_COMPLETE_LAUNCH_BINDING_METHOD); + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WORLD_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String OTHER_NAMESPACE_GAME_SESSION_URI = + "spiffe://firemud/ns/other/sa/game-session-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String REQUEST_ID = "22222222-2222-4222-8222-222222222222"; + private static final String TENANT_ID = "33333333-3333-4333-8333-333333333333"; + private static final String SOURCE_OPERATION_ID = "44444444-4444-4444-8444-444444444444"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void sameNamespaceGameSessionPeerReachesResolveAndDescriptorReadButBindingReadIsDenied() { + AuthTokenInterceptor interceptor = interceptor(); + Harness harness = harness(); + when(harness.launchDescriptorService().resolveLaunchDescriptor(any())) + .thenThrow(new IllegalStateException("intentional owner read probe")); + when(harness + .launchDescriptorService() + .getLaunchDescriptor( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString())) + .thenThrow(new IllegalArgumentException("intentional exact read probe")); + DispatchResult resolve = + dispatchHandler( + interceptor, + harness, + GAME_SESSION_URI, + new Metadata(), + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor); + DispatchResult descriptorRead = + dispatchHandler( + interceptor, + harness, + GAME_SESSION_URI, + new Metadata(), + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor); + DispatchResult completeRead = + dispatchHandler( + interceptor, + harness, + GAME_SESSION_URI, + new Metadata(), + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding); + + assertThat(resolve.dispatched()).isTrue(); + assertThat(resolve.closedStatus()).isNull(); + assertThat(resolve.response()).isNotNull(); + assertThat(resolve.response().getError().getCode()).isNotEqualTo("PERMISSION_DENIED"); + assertThat(descriptorRead.dispatched()).isTrue(); + assertThat(descriptorRead.closedStatus()).isNull(); + assertThat(descriptorRead.response()).isNotNull(); + assertThat(descriptorRead.response().getError().getCode()).isNotEqualTo("PERMISSION_DENIED"); + assertThat(completeRead.dispatched()).isTrue(); + assertThat(completeRead.closedStatus()).isNull(); + assertThat(completeRead.response()).isNotNull(); + assertThat(completeRead.response().getError().getCode()).isEqualTo("PERMISSION_DENIED"); + verify(harness.launchDescriptorService()).resolveLaunchDescriptor(any()); + verify(harness.launchDescriptorService()) + .getLaunchDescriptor( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString()); + verifyNoInteractions(harness.completeLaunchBindingService()); + } + + @Test + void workloadPeerMustMatchNamespaceAndServiceEvenWhenMethodSkipsBearerValidation() { + AuthTokenInterceptor interceptor = interceptor(); + for (String peerUri : List.of("", OTHER_NAMESPACE_GAME_SESSION_URI, ACCOUNT_URI)) { + GrpcPeerIdentity peer = peerUri.isEmpty() ? null : identity(peerUri); + assertAllLaunchHandlersDeny(interceptor, peer, new Metadata()); + } + } + + @Test + void worldDescriptorReadIsAllowedButCompleteBindingCandidatePeersAreDenied() { + AuthTokenInterceptor interceptor = interceptor(); + Harness harness = harness(); + when(harness + .launchDescriptorService() + .getLaunchDescriptor( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString())) + .thenThrow(new IllegalArgumentException("intentional exact read probe")); + DispatchResult worldDescriptorRead = + dispatchHandler( + interceptor, + harness, + WORLD_MANAGEMENT_URI, + new Metadata(), + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor); + DispatchResult worldCompleteRead = + dispatchHandler( + interceptor, + harness, + WORLD_MANAGEMENT_URI, + new Metadata(), + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding); + DispatchResult entityCompleteRead = + dispatchHandler( + interceptor, + harness, + ENTITY_MANAGEMENT_URI, + new Metadata(), + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding); + + assertAllowedHandlerReached(worldDescriptorRead); + assertThat(worldCompleteRead.dispatched()).isTrue(); + assertThat(worldCompleteRead.closedStatus()).isNull(); + assertThat(worldCompleteRead.response()).isNotNull(); + assertThat(worldCompleteRead.response().getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(entityCompleteRead.dispatched()).isTrue(); + assertThat(entityCompleteRead.closedStatus()).isNull(); + assertThat(entityCompleteRead.response()).isNotNull(); + assertThat(entityCompleteRead.response().getError().getCode()).isEqualTo("PERMISSION_DENIED"); + verify(harness.launchDescriptorService()) + .getLaunchDescriptor( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString()); + verifyNoInteractions(harness.completeLaunchBindingService()); + + assertDenied( + interceptor, + identity(WORLD_MANAGEMENT_URI), + new Metadata(), + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + identity(ENTITY_MANAGEMENT_URI), + new Metadata(), + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + identity(ENTITY_MANAGEMENT_URI), + new Metadata(), + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor, + response -> response.getError().getCode()); + } + + @Test + void playerJwtCannotSubstituteForMissingGameSessionPeerIdentity() { + JwtUtil jwtUtil = new JwtUtil("valid-test-player-jwt-secret-123456", 60_000L); + Metadata playerJwt = new Metadata(); + playerJwt.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + jwtUtil.generateToken("player-42", Map.of("role", "player"))); + + assertAllLaunchHandlersDeny(interceptor(jwtUtil), null, playerJwt); + } + + @Test + void unlistedGameDesignMethodStillRequiresBearerToken() { + AuthTokenInterceptor interceptor = interceptor(); + DispatchResult result = + dispatch( + interceptor, + null, + new Metadata(), + UNLISTED_METHOD, + GetPublishedReleaseBundleRequest.getDefaultInstance(), + GetPublishedReleaseBundleResponse.getDefaultInstance(), + GetPublishedReleaseBundleRequest.getDefaultInstance(), + (request, observer) -> {}); + + assertThat(result.dispatched()).isFalse(); + assertThat(result.closedStatus()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(result.response()).isNull(); + } + + private static void assertAllLaunchHandlersDeny( + AuthTokenInterceptor interceptor, GrpcPeerIdentity peer, Metadata headers) { + assertDenied( + interceptor, + peer, + headers, + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + peer, + headers, + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + peer, + headers, + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding, + response -> response.getError().getCode()); + } + + private static void assertDenied( + AuthTokenInterceptor interceptor, + GrpcPeerIdentity peer, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + HandlerCall handlerCall, + java.util.function.Function errorCode) { + Harness harness = harness(); + DispatchResult result = + dispatchHandler( + interceptor, + harness, + peer, + headers, + methodName, + defaultRequest, + defaultResponse, + request, + handlerCall); + + assertThat(result.dispatched()).isTrue(); + assertThat(result.closedStatus()).isNull(); + assertThat(result.response()).isNotNull(); + assertThat(errorCode.apply(result.response())).isEqualTo("PERMISSION_DENIED"); + verifyNoInteractions(harness.launchDescriptorService(), harness.completeLaunchBindingService()); + } + + private static void assertAllowedHandlerReached(DispatchResult result) { + assertThat(result.dispatched()).isTrue(); + assertThat(result.closedStatus()).isNull(); + assertThat(result.response()).isNotNull(); + } + + private static + DispatchResult dispatchHandler( + AuthTokenInterceptor interceptor, + Harness harness, + String peerUri, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + HandlerCall handlerCall) { + return dispatchHandler( + interceptor, + harness, + peerUri == null ? null : identity(peerUri), + headers, + methodName, + defaultRequest, + defaultResponse, + request, + handlerCall); + } + + private static + DispatchResult dispatchHandler( + AuthTokenInterceptor interceptor, + Harness harness, + GrpcPeerIdentity peer, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + HandlerCall handlerCall) { + return dispatch( + interceptor, + peer, + headers, + methodName, + defaultRequest, + defaultResponse, + request, + (message, observer) -> handlerCall.invoke(harness.service(), message, observer)); + } + + private static + DispatchResult dispatch( + AuthTokenInterceptor interceptor, + GrpcPeerIdentity peer, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + java.util.function.BiConsumer> handler) { + ServerCall call = mock(); + when(call.getMethodDescriptor()) + .thenReturn(method(methodName, defaultRequest, defaultResponse)); + AtomicReference closedStatus = new AtomicReference<>(); + AtomicBoolean dispatched = new AtomicBoolean(); + AtomicReference response = new AtomicReference<>(); + doAnswer( + invocation -> { + Status status = invocation.getArgument(0); + closedStatus.set(status.getCode()); + return null; + }) + .when(call) + .close(any(), any()); + + ServerCallHandler next = + (serverCall, ignoredHeaders) -> { + dispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(RequestT message) { + handler.accept( + message, + new StreamObserver<>() { + @Override + public void onNext(ResponseT value) { + response.set(value); + } + + @Override + public void onError(Throwable throwable) { + closedStatus.set(Status.fromThrowable(throwable).getCode()); + } + + @Override + public void onCompleted() {} + }); + } + }; + }; + + Runnable invoke = + () -> { + ServerCall.Listener listener = interceptor.interceptCall(call, headers, next); + if (listener != null) { + listener.onMessage(request); + } + }; + if (peer == null) { + invoke.run(); + } else { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invoke); + } + return new DispatchResult<>(dispatched.get(), closedStatus.get(), response.get()); + } + + private static + MethodDescriptor method( + String methodName, RequestT defaultRequest, ResponseT defaultResponse) { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(methodName) + .setRequestMarshaller(ProtoUtils.marshaller(defaultRequest)) + .setResponseMarshaller(ProtoUtils.marshaller(defaultResponse)) + .build(); + } + + private static AuthTokenInterceptor interceptor() { + return new AuthTokenInterceptor(mock(JwtUtil.class), Set.copyOf(ALLOWLISTED_METHODS)); + } + + private static AuthTokenInterceptor interceptor(JwtUtil jwtUtil) { + return new AuthTokenInterceptor(jwtUtil, Set.copyOf(ALLOWLISTED_METHODS)); + } + + private static Harness harness() { + LaunchDescriptorService launchDescriptorService = mock(LaunchDescriptorService.class); + CompleteLaunchBindingService completeLaunchBindingService = + mock(CompleteLaunchBindingService.class); + GameDesignGrpcService service = + new GameDesignGrpcService( + mock(PingService.class), + mock(RevisionService.class), + mock(VersionService.class), + launchDescriptorService, + completeLaunchBindingService, + mock(TemplateRemapSetService.class), + mock(VersionAssetArtifactService.class), + mock(SettingsAuthorityService.class), + mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + return new Harness(service, launchDescriptorService, completeLaunchBindingService); + } + + private static ResolveLaunchDescriptorRequest resolveRequest() { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(TENANT_ID) + .setGameTemplateId(77L) + .setControlPlaneRequestId("launch-auth-control-plane") + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID) + .setExpectedAuthoredWorldSourceEvidenceDigest(DIGEST) + .build(); + } + + private static GetLaunchDescriptorRequest readRequest() { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(REQUEST_ID) + .setCanonicalTenantId(TENANT_ID) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("launch-auth-control-plane") + .setExpectedRequestDigest(DIGEST) + .setExpectedResultDigest(DIGEST) + .build(); + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private record Harness( + GameDesignGrpcService service, + LaunchDescriptorService launchDescriptorService, + CompleteLaunchBindingService completeLaunchBindingService) {} + + private record DispatchResult( + boolean dispatched, Status.Code closedStatus, ResponseT response) {} + + @FunctionalInterface + private interface HandlerCall { + void invoke( + GameDesignGrpcService service, + RequestT request, + StreamObserver responseObserver); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index 94bce5de72..c76256c058 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -52,14 +52,27 @@ class TenantIdentityGrpcAuthWiringTest { private static final String FRESH_CREATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; - private static final List CONFIGURED_PUBLIC_METHODS = + private static final String POLICY_RESOLVE_METHOD = + PublishedRealmEntryPolicyServiceGrpc.getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(); + private static final String POLICY_LIST_METHOD = + PublishedRealmEntryPolicyServiceGrpc.getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName(); + private static final String RESOLVE_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor"; + private static final String GET_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/GetLaunchDescriptor"; + private static final String GET_COMPLETE_LAUNCH_BINDING_METHOD = + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding"; + private static final String OTHER_METHOD = "gamedesign.v1.TenantIdentityService/UnlistedMethod"; + private static final List ALLOWLISTED_METHODS = List.of( FRESH_CREATION_METHOD, - PublishedRealmEntryPolicyServiceGrpc.getResolvePublishedRealmEntryPolicyMethod() - .getFullMethodName(), - PublishedRealmEntryPolicyServiceGrpc.getListPublishedRealmEntryPoliciesMethod() - .getFullMethodName()); - private static final String OTHER_METHOD = "gamedesign.v1.TenantIdentityService/UnlistedMethod"; + POLICY_RESOLVE_METHOD, + POLICY_LIST_METHOD, + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + GET_LAUNCH_DESCRIPTOR_METHOD, + GET_COMPLETE_LAUNCH_BINDING_METHOD); private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String SOURCE_KEY = "fresh-owner-key-91"; @@ -70,10 +83,10 @@ class TenantIdentityGrpcAuthWiringTest { GameTenantCreationDigest.requestDigest("test", REQUEST_ID, SOURCE_KEY, "Fresh Realm", null); @Test - void defaultAndProductionProfilesAllowOnlyFreshReadAndRequireClientTls() throws IOException { + void defaultAndProductionProfilesKeepExactReadAllowlistAndRequireClientTls() throws IOException { for (String file : List.of("application.yml", "application-prod.yml")) { GrpcConfiguration config = load(file); - assertThat(config.publicMethods()).containsExactlyElementsOf(CONFIGURED_PUBLIC_METHODS); + assertThat(config.publicMethods()).containsExactlyElementsOf(ALLOWLISTED_METHODS); assertThat(config.clientAuth()).isEqualTo("REQUIRE"); } } @@ -188,7 +201,7 @@ private static void withConfiguredInterceptor(Consumer act context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactlyElementsOf(CONFIGURED_PUBLIC_METHODS); + .containsExactlyElementsOf(ALLOWLISTED_METHODS); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 19771f2919..2d81d48ebd 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.protobuf.UnknownFieldSet; import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -12,6 +13,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; @@ -51,6 +53,8 @@ import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -97,6 +101,8 @@ class GameDesignGrpcServiceTest { UUID.fromString("12345678-1234-4234-8234-123456789abc"); private static final UUID CANONICAL_VERSION_ID = UUID.fromString("82345678-1234-4234-8234-123456789abc"); + private static final UUID AUTHORED_SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); @@ -1197,6 +1203,18 @@ void resolveLaunchDescriptorRejectsUnboundLegacyRequestBeforeOwnerRead() { Mockito.verifyNoInteractions(launchDescriptorService); } + @Test + void resolveLaunchDescriptorRejectsNonCanonicalTenantUuidBeforeOwnerRead() { + var request = + resolveRequest("cp-invalid-uuid").toBuilder().setCanonicalTenantId("not-a-uuid").build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + @Test void createTemplateRemapSetReturnsCreatedSet() { Mockito.when( @@ -1486,6 +1504,194 @@ public void onCompleted() {} assertEquals("wf-1", ref.get().getArtifactState().getLastWorkflowId()); } + @Test + void resolveLaunchDescriptorReturnsDeterministicDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-1"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) + .thenReturn(launchDto(evidence)); + + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-1"), observerFor(ref))); + + assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); + assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService).resolveLaunchDescriptor(request); + } + + @Test + void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) + .thenThrow( + new IllegalArgumentException( + "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); + + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-2"), observerFor(ref))); + + assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); + } + + @Test + void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) + .thenThrow( + new IllegalArgumentException( + "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); + + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-3"), observerFor(ref))); + + assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + } + + @Test + void resolveLaunchDescriptorRequiresWorkloadIdentityBeforeOwnerRead() { + AtomicReference ref = new AtomicReference<>(); + service.resolveLaunchDescriptor(resolveRequest("cp-no-peer"), observerFor(ref)); + + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void getLaunchDescriptorReturnsExactBoundReadback() { + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-read"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + UUID readRequestId = UUID.fromString("32345678-1234-4234-8234-123456789abc"); + Mockito.when( + launchDescriptorService.getLaunchDescriptor( + readRequestId, + CANONICAL_TENANT_ID, + "silver-march", + "cp-read", + evidence.requestDigest(), + evidence.resultDigest())) + .thenReturn(launchDto(evidence)); + + var readRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(readRequestId.toString()) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest(evidence.requestDigest()) + .setExpectedResultDigest(evidence.resultDigest()) + .build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "world-management-service", + () -> service.getLaunchDescriptor(readRequest, observerFor(ref))); + + assertEquals(readRequestId.toString(), ref.get().getRequestId()); + assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService) + .getLaunchDescriptor( + readRequestId, + CANONICAL_TENANT_ID, + "silver-march", + "cp-read", + evidence.requestDigest(), + evidence.resultDigest()); + } + + @Test + void resolveLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + var request = + resolveRequest("cp-unknown").toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void getLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", () -> service.getLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void completeLaunchBindingRejectsUnlistedPeerBeforeOwnerRead() { + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-complete") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); + AtomicReference ref = + new AtomicReference<>(); + underLaunchPeer( + "automation-scripting-service", + () -> service.getCompleteLaunchBinding(request, observerFor(ref))); + + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(completeLaunchBindingService); + } + + @Test + void completeLaunchBindingDeniesCandidateBeforeRequestValidationOrOwnerRead() { + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-complete") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + AtomicReference ref = + new AtomicReference<>(); + underLaunchPeer( + "game-session-service", () -> service.getCompleteLaunchBinding(request, observerFor(ref))); + + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(completeLaunchBindingService); + } + @Test void compareAndSetVersionStateSameStateNoOpReturnsCurrentStateWithoutUpdatedFlag() { Mockito.when( @@ -1563,6 +1769,72 @@ private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } + private AuthoredWorldLaunchDescriptorEvidence.Request launchRequest( + String controlPlaneRequestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + controlPlaneRequestId, + CANONICAL_TENANT_ID, + "silver-march", + AUTHORED_SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence launchEvidence( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:" + CANONICAL_TENANT_ID + ":7:11", + false, + null); + } + + private net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto launchDto( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return new net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private ResolveLaunchDescriptorRequest resolveRequest(String controlPlaneRequestId) { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setGameTemplateId(9L) + .setControlPlaneRequestId(controlPlaneRequestId) + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId(AUTHORED_SOURCE_OPERATION_ID.toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(); + } + private TemplateRemapSetDto sampleRemapSetDto( TemplateRemapSetStatus status, String approvalReason, LocalDateTime approvedAt) { return new TemplateRemapSetDto( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java new file mode 100644 index 0000000000..c6da9e621d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -0,0 +1,677 @@ +package net.firedevops.firemud.gamesession.client; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.ManagedChannel; +import jakarta.annotation.PostConstruct; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Default-off, authenticated point-in-time reader for Entity's persisted PRESEEDED roster. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.canonical-gameplay-roster-owner-read", + name = "enabled", + havingValue = "true") +public final class CanonicalGameplayRosterClient + extends AbstractReloadingBlockingGrpcClient< + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + // Matches Entity's bounded CanonicalGameplayRosterSnapshotDigest contract. + public static final int MAX_ROSTER_SIZE = 100; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String SNAPSHOT_DIGEST_DOMAIN = + "firemud.entity.canonical-gameplay-roster.v3"; + + private final String workloadNamespace; + + public CanonicalGameplayRosterClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProperties), + channelFactory, + CanonicalGameplayRosterClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + @PostConstruct + void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub buildStub( + ManagedChannel channel) { + return CanonicalGameplayRosterServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service")) + .withCompression("gzip"); + } + + /** + * Reads one complete Entity snapshot for an exact current published route. The result is + * discovery evidence only: it does not establish Account membership, admission, or PLAY. + */ + public PreseededRosterSnapshot listPreseededRoster( + CanonicalPublishedPlayerRoute publishedRoute, PlayerExecutionContext playerExecutionContext) { + Objects.requireNonNull(publishedRoute, "publishedRoute"); + CanonicalGameplayRosterTarget expectedTarget = expectedTarget(publishedRoute); + UUID canonicalAccountUuid = + validatePlayerExecutionContext(playerExecutionContext, expectedTarget, false); + UUID requestUuid = parseContextUuid(playerExecutionContext.getRequestId(), "request_id"); + CanonicalGameplayRosterRequest request = + CanonicalGameplayRosterRequest.newBuilder() + .setRequestUuid(requestUuid.toString()) + .setCanonicalAccountUuid(canonicalAccountUuid.toString()) + .setExpectedTarget(expectedTarget) + .setPlayerExecutionContext(playerExecutionContext) + .build(); + + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Entity canonical gameplay roster client is not initialized"); + } + CanonicalGameplayRosterResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .listPreseededRoster(request); + return validateResponse(canonicalAccountUuid, expectedTarget, response); + } + + /** + * Reads Entity's owner-issued assignment reference for the actor selected in the typed context + * from the exact previously validated SHARED PRESEEDED_ONLY roster snapshot. This point-in-time + * reference is not Account eligibility or admission evidence; the later World hold revalidates + * assignment. + */ + public VerifiedPreseededAssignment readSelectedPreseededAssignment( + PreseededRosterSnapshot roster, PlayerExecutionContext playerExecutionContext) { + requireOutsideTransactionAndSynchronization(); + Objects.requireNonNull(roster, "roster"); + requireValidSelectedRosterSnapshot(roster); + CanonicalGameplayRosterTarget expectedTarget = roster.target(); + UUID contextAccountUuid = + validatePlayerExecutionContext(playerExecutionContext, expectedTarget, true); + if (!roster.canonicalAccountUuid().equals(contextAccountUuid)) { + throw new IllegalArgumentException( + "Player execution context account does not match the validated Entity roster"); + } + UUID selectedCharacterUuid = + parseContextUuid(playerExecutionContext.getCharacterId(), "character_id"); + long actorMatches = + roster.actors().stream() + .filter(actor -> actor.characterUuid().equals(selectedCharacterUuid)) + .count(); + if (actorMatches != 1L) { + throw new IllegalArgumentException( + "Selected character must occur exactly once in the validated Entity roster"); + } + + UUID requestUuid = parseContextUuid(playerExecutionContext.getRequestId(), "request_id"); + CanonicalGameplayRosterSelectedAssignmentRequest request = + CanonicalGameplayRosterSelectedAssignmentRequest.newBuilder() + .setRequestUuid(requestUuid.toString()) + .setCanonicalAccountUuid(roster.canonicalAccountUuid().toString()) + .setSelectedCharacterUuid(selectedCharacterUuid.toString()) + .setExpectedTarget(expectedTarget) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.snapshotUuid().toString()) + .setSnapshotDigest(roster.snapshotDigest())) + .setPlayerExecutionContext(playerExecutionContext) + .build(); + + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Entity canonical gameplay roster client is not initialized"); + } + CanonicalGameplayRosterSelectedAssignmentResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedPreseededAssignment(request); + return validateSelectedAssignmentResponse(requestUuid, roster, selectedCharacterUuid, response); + } + + private static UUID validatePlayerExecutionContext( + PlayerExecutionContext context, + CanonicalGameplayRosterTarget expectedTarget, + boolean selectedCharacterRequired) { + if (context == null) { + throw new IllegalArgumentException("Player execution context is required"); + } + if (!context.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Player execution context contains unknown fields"); + } + + UUID accountUuid = parseContextUuid(context.getAccountId(), "account_id"); + parseContextUuid(context.getSessionId(), "session_id"); + parseContextUuid(context.getRequestId(), "request_id"); + requireContextUuidEquals(context.getTenantId(), expectedTarget.getTenantUuid(), "tenant_id"); + requireContextUuidEquals(context.getRealmId(), expectedTarget.getRealmUuid(), "realm_id"); + requireContextUuidEquals( + context.getPlayableStateNamespaceId(), + expectedTarget.getPlayableStateNamespaceUuid(), + "playable_state_namespace_id"); + requireContextUuidEquals( + context.getGameInstanceId(), expectedTarget.getGameInstanceUuid(), "game_instance_id"); + + PlayableStateScope contextScope = + switch (context.getPlayableStateScope()) { + case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + default -> + throw new IllegalArgumentException( + "Player execution context playable_state_scope must be exact SHARED or ISOLATED"); + }; + if (contextScope != expectedTarget.getPlayableStateScope()) { + throw new IllegalArgumentException( + "Player execution context playable_state_scope does not match the expected target"); + } + + if (selectedCharacterRequired) { + parseContextUuid(context.getCharacterId(), "character_id"); + } else if (!context.getCharacterId().isEmpty()) { + throw new IllegalArgumentException( + "Initial roster reads must not select an actor in player execution context"); + } + return accountUuid; + } + + private static void requireContextUuidEquals(String value, String expected, String fieldName) { + UUID parsed = parseContextUuid(value, fieldName); + if (!parsed.toString().equals(expected)) { + throw new IllegalArgumentException( + "Player execution context " + fieldName + " does not match the expected target"); + } + } + + private static UUID parseContextUuid(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Player execution context " + fieldName + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Player execution context " + fieldName + " must be a canonical non-nil UUID", malformed); + } + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException( + "Player execution context " + fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireOutsideTransactionAndSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Entity selected assignment reads cannot run inside a Game Session transaction " + + "or synchronization"); + } + } + + private static void requireValidSelectedRosterSnapshot(PreseededRosterSnapshot roster) { + CanonicalGameplayRosterTarget target = Objects.requireNonNull(roster.target(), "roster.target"); + if (!target.getUnknownFields().asMap().isEmpty() + || target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) { + throw new IllegalArgumentException( + "Selected assignment reads require an exact SHARED PRESEEDED_ONLY roster target"); + } + requireValidActors(roster.actors()); + if (!roster + .snapshotDigest() + .equals(calculateSnapshotDigest(roster.canonicalAccountUuid(), target, roster.actors()))) { + throw new IllegalArgumentException( + "Selected assignment input is not the exact validated Entity roster snapshot"); + } + } + + private static VerifiedPreseededAssignment validateSelectedAssignmentResponse( + UUID requestUuid, + PreseededRosterSnapshot roster, + UUID selectedCharacterUuid, + CanonicalGameplayRosterSelectedAssignmentResponse response) { + if (response == null) { + throw invalidSelectedAssignmentResponse("response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidSelectedAssignmentResponse("response contains unknown fields"); + } + if (!requestUuid.toString().equals(response.getRequestUuid())) { + throw invalidSelectedAssignmentResponse("response changed the request correlation"); + } + if (!roster.canonicalAccountUuid().toString().equals(response.getCanonicalAccountUuid())) { + throw invalidSelectedAssignmentResponse("response changed the canonical account UUID"); + } + if (!selectedCharacterUuid.toString().equals(response.getSelectedCharacterUuid())) { + throw invalidSelectedAssignmentResponse("response changed the selected character UUID"); + } + if (!response.hasTarget() + || !response.getTarget().getUnknownFields().asMap().isEmpty() + || !roster.target().equals(response.getTarget())) { + throw invalidSelectedAssignmentResponse("response changed the complete expected target"); + } + if (!response.hasSnapshot() || !response.getSnapshot().getUnknownFields().asMap().isEmpty()) { + throw invalidSelectedAssignmentResponse("response snapshot is absent or malformed"); + } + UUID echoedSnapshotUuid = + parseCanonicalUuid(response.getSnapshot().getSnapshotUuid(), "snapshot_uuid"); + String echoedSnapshotDigest = response.getSnapshot().getSnapshotDigest(); + if (!roster.snapshotUuid().equals(echoedSnapshotUuid) + || !roster.snapshotDigest().equals(echoedSnapshotDigest)) { + throw invalidSelectedAssignmentResponse( + "response changed the exact roster snapshot UUID or digest"); + } + UUID assignmentOperationId = + parseCanonicalUuid(response.getAssignmentUuid(), "assignment_uuid"); + String intentDigest = response.getIntentDigest(); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw invalidSelectedAssignmentResponse( + "intent_digest is not bare canonical lowercase SHA-256 hex"); + } + return new VerifiedPreseededAssignment( + roster.canonicalAccountUuid(), + selectedCharacterUuid, + roster.target(), + roster.snapshotUuid(), + roster.snapshotDigest(), + assignmentOperationId, + intentDigest); + } + + private static IllegalStateException invalidSelectedAssignmentResponse(String message) { + return new IllegalStateException("Entity selected assignment response is invalid: " + message); + } + + private static PreseededRosterSnapshot validateResponse( + UUID expectedAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterResponse response) { + if (response == null) { + throw invalidResponse("response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("response contains unknown fields"); + } + if (!expectedAccountUuid.toString().equals(response.getCanonicalAccountUuid())) { + throw invalidResponse("response changed the canonical account UUID"); + } + if (!response.hasTarget() + || !response.getTarget().getUnknownFields().asMap().isEmpty() + || !expectedTarget.equals(response.getTarget())) { + throw invalidResponse("response changed the complete expected target"); + } + UUID snapshotUuid = parseCanonicalUuid(response.getSnapshotUuid(), "snapshot_uuid"); + String snapshotDigest = response.getSnapshotDigest(); + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw invalidResponse("snapshot_digest is not canonical lowercase SHA-256 hex"); + } + if (response.getActorsCount() > MAX_ROSTER_SIZE) { + throw invalidResponse("actor roster exceeds its maximum size"); + } + + List actors = new ArrayList<>(response.getActorsCount()); + for (CanonicalGameplayRosterActor actor : response.getActorsList()) { + if (!actor.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("actor contains unknown fields"); + } + UUID characterUuid = parseCanonicalUuid(actor.getCharacterUuid(), "character_uuid"); + if (actor.getActorKind() + != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) { + throw invalidResponse("actor roster contains an unsupported actor kind"); + } + String displayName = actor.getDisplayName(); + actors.add(new RosterActor(characterUuid, displayName)); + } + try { + requireValidActors(actors); + } catch (IllegalArgumentException malformedActors) { + throw invalidResponse(malformedActors.getMessage()); + } + if (!snapshotDigest.equals( + calculateSnapshotDigest(expectedAccountUuid, expectedTarget, actors))) { + throw invalidResponse("snapshot_digest does not bind the returned target and roster"); + } + return new PreseededRosterSnapshot( + expectedAccountUuid, snapshotUuid, snapshotDigest, expectedTarget, actors); + } + + /** + * Builds the exact Entity source target for a validated current SHARED PRESEEDED_ONLY route. + * Policy and digest evidence are validated before the target is returned. + */ + public static CanonicalGameplayRosterTarget expectedTarget( + CanonicalPublishedPlayerRoute publishedRoute) { + CanonicalPlayableTarget route = publishedRoute.route(); + RealmEntryPolicy policy = publishedRoute.entryPolicy(); + if (policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !"SHARED".equals(route.playableStateScope())) { + throw new IllegalArgumentException( + "Canonical roster reads require the exact published SHARED PRESEEDED_ONLY route"); + } + PublishedRealmEntryPolicyEvidence selectedPolicy = publishedRoute.selectedPolicyEvidence(); + publishedRoute.policySetEvidence().requireValidDigest(); + selectedPolicy.requireValidDigest(publishedRoute.policySetEvidence()); + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(route.canonicalTenantId().toString()) + .setRealmUuid(route.realmId().toString()) + .setWorldSlug(route.worldSlug()) + .setRealmSlug(route.realmSlug()) + .setGameInstanceUuid(route.canonicalGameInstanceId().toString()) + .setCatalogRevision(route.catalogRevision()) + .setPublishedPolicyDigest(rawPublishedPolicyDigest(selectedPolicy.policyDigest())) + .setPublishedReleaseBundleRef( + publishedRoute.policySetEvidence().publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest(route.admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest(rawOwnerProofDigest(route.ownerProofDigest())) + .setPlayableStateNamespaceUuid(route.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .setCanonicalVersionUuid(route.canonicalVersionId().toString()) + .setPointerVersion(route.pointerVersion()) + .setActiveWorldEpoch(route.activeWorldEpoch()) + .build(); + } + + /** Requires a typed Entity roster to satisfy the shared actor-list contract. */ + public static void requireValidActors(List actors) { + if (actors == null) { + throw new IllegalArgumentException("Validated Entity roster is absent"); + } + if (actors.size() > MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Validated Entity roster exceeds its maximum size"); + } + Set characterUuids = new HashSet<>(); + for (RosterActor actor : actors) { + if (actor == null) { + throw new IllegalArgumentException("Validated Entity roster contains an absent actor"); + } + UUID characterUuid = actor.characterUuid(); + requireNonNil(characterUuid, "roster character UUID"); + if (!characterUuids.add(characterUuid)) { + throw new IllegalArgumentException("duplicate actor: duplicate character UUID"); + } + if (!isCanonicalDisplayName(actor.displayName())) { + throw new IllegalArgumentException("display name is malformed"); + } + } + } + + private static boolean isCanonicalDisplayName(String value) { + return value != null + && !value.isBlank() + && value.equals(value.trim()) + && value.length() <= 100 + && value.codePoints().noneMatch(Character::isISOControl); + } + + private static String rawOwnerProofDigest(String prefixedDigest) { + if (prefixedDigest == null || !prefixedDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical route owner-proof digest is malformed"); + } + return prefixedDigest.substring("sha256:".length()); + } + + private static String rawPublishedPolicyDigest(String prefixedDigest) { + if (prefixedDigest == null || !prefixedDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Published route policy digest is malformed"); + } + return prefixedDigest.substring("sha256:".length()); + } + + private static String calculateSnapshotDigest( + UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target, List actors) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + // Mirrors Entity's canonical roster digest/v3; divergence fails closed at the client. + write(output, SNAPSHOT_DIGEST_DOMAIN); + write(output, canonicalAccountUuid.toString()); + write(output, target.getTenantUuid()); + write(output, target.getRealmUuid()); + write(output, target.getWorldSlug()); + write(output, target.getRealmSlug()); + write(output, target.getGameInstanceUuid()); + write(output, Long.toString(target.getCatalogRevision())); + write(output, Long.toString(target.getPointerVersion())); + write(output, Long.toString(target.getActiveWorldEpoch())); + write(output, target.getCanonicalVersionUuid()); + write(output, target.getPublishedPolicyDigest()); + write(output, target.getPublishedReleaseBundleRef()); + write(output, target.getAdmissionPointerSnapshotDigest()); + write(output, target.getPublishedOwnerProofDigest()); + write(output, target.getPlayableStateNamespaceUuid()); + write(output, target.getPlayableStateScope().name()); + write(output, "PRESEEDED_ONLY"); + write(output, Integer.toString(actors.size())); + for (RosterActor actor : actors) { + write(output, actor.characterUuid().toString()); + write(output, actor.displayName()); + } + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException | IOException impossible) { + throw new IllegalStateException( + "Unable to validate Entity roster snapshot digest", impossible); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } + + private static UUID parseCanonicalUuid(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw invalidResponse(fieldName + " is missing"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw invalidResponse(fieldName + " is not a canonical UUID", malformed); + } + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw invalidResponse(fieldName + " is not a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + } + + private static IllegalStateException invalidResponse(String message) { + return new IllegalStateException( + "Entity canonical gameplay roster response is invalid: " + message); + } + + private static IllegalStateException invalidResponse(String message, Throwable cause) { + return new IllegalStateException( + "Entity canonical gameplay roster response is invalid: " + message, cause); + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Canonical roster reads require Game Session workload mTLS"); + } + if (!hasText(tlsProperties.getCertChain()) + || !hasText(tlsProperties.getPrivateKey()) + || !hasText(tlsProperties.getCaCert())) { + throw new IllegalArgumentException( + "Canonical roster reads require Game Session certificate, key, and CA files"); + } + if (tlsProperties.getCertChain().trim().startsWith("classpath:") + || tlsProperties.getPrivateKey().trim().startsWith("classpath:") + || tlsProperties.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Canonical roster reads require file-backed Game Session workload mTLS"); + } + return tlsProperties; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + /** Entity-authenticated assignment reference bound to one exact roster actor and target. */ + public static final class VerifiedPreseededAssignment { + private final UUID canonicalAccountUuid; + private final UUID selectedCharacterUuid; + private final CanonicalGameplayRosterTarget target; + private final UUID rosterSnapshotUuid; + private final String rosterSnapshotDigest; + private final UUID assignmentOperationId; + private final String intentDigest; + + private VerifiedPreseededAssignment( + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + CanonicalGameplayRosterTarget target, + UUID rosterSnapshotUuid, + String rosterSnapshotDigest, + UUID assignmentOperationId, + String intentDigest) { + this.canonicalAccountUuid = + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + this.selectedCharacterUuid = + Objects.requireNonNull(selectedCharacterUuid, "selectedCharacterUuid"); + this.target = Objects.requireNonNull(target, "target"); + this.rosterSnapshotUuid = Objects.requireNonNull(rosterSnapshotUuid, "rosterSnapshotUuid"); + this.rosterSnapshotDigest = + Objects.requireNonNull(rosterSnapshotDigest, "rosterSnapshotDigest"); + this.assignmentOperationId = + Objects.requireNonNull(assignmentOperationId, "assignmentOperationId"); + this.intentDigest = Objects.requireNonNull(intentDigest, "intentDigest"); + } + + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + public UUID selectedCharacterUuid() { + return selectedCharacterUuid; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The target is an immutable generated protobuf message.") + public CanonicalGameplayRosterTarget target() { + return target; + } + + public UUID rosterSnapshotUuid() { + return rosterSnapshotUuid; + } + + public String rosterSnapshotDigest() { + return rosterSnapshotDigest; + } + + public UUID assignmentOperationId() { + return assignmentOperationId; + } + + public String intentDigest() { + return intentDigest; + } + } + + public record RosterActor(UUID characterUuid, String displayName) {} + + /** Entity's exact source snapshot; its UUID is not admission or controller authority. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The target is an immutable built protobuf message; actor lists are copied.") + public record PreseededRosterSnapshot( + UUID canonicalAccountUuid, + UUID snapshotUuid, + String snapshotDigest, + CanonicalGameplayRosterTarget target, + List actors) { + public PreseededRosterSnapshot { + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(snapshotUuid, "snapshotUuid"); + Objects.requireNonNull(target, "target"); + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "snapshotDigest must be canonical lowercase SHA-256 hex"); + } + actors = List.copyOf(Objects.requireNonNull(actors, "actors")); + if (actors.size() > MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Roster exceeds the maximum supported size"); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java new file mode 100644 index 0000000000..3faa05af4f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; + +/** Unwired Game Session receiver for complete immutable Game Design realm-policy sets. */ +public final class GameDesignPublishedRealmPolicyClient + extends AbstractReloadingBlockingGrpcClient< + PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String workloadNamespace; + + public GameDesignPublishedRealmPolicyClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProps), + channelFactory, + GameDesignPublishedRealmPolicyClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes the owner client only when an explicit caller owns this handoff. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + buildStub(ManagedChannel channel) { + return PublishedRealmEntryPolicyServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) + .withCompression("gzip"); + } + + /** Reads and verifies the complete bounded owner set for an exact published tenant version. */ + public PublishedRealmEntryPolicySetEvidence listPublishedRealmEntryPolicies( + UUID canonicalTenantId, UUID canonicalVersionId) { + requireNonNil(canonicalTenantId, "canonical tenant ID"); + requireNonNil(canonicalVersionId, "canonical version ID"); + var currentStub = stub(); + if (currentStub == null) { + throw new UninitializedClientException( + "Game Design published realm policy client is not initialized"); + } + + PublishedRealmEntryPolicyReadGrpcCodec.ListRequest request = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + workloadNamespace, UUID.randomUUID(), canonicalTenantId, canonicalVersionId); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .listPublishedRealmEntryPolicies( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(request)); + try { + return PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new InvalidResponseException( + "Game Design published realm policy response is invalid", invalid); + } + } + + public static final class UninitializedClientException extends RuntimeException { + public UninitializedClientException(String message) { + super(message); + } + } + + public static final class InvalidResponseException extends RuntimeException { + public InvalidResponseException(String message, Throwable cause) { + super(message, cause); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Published realm policy reads require Game Session workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Published realm policy reads require Game Session certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Published realm policy reads require file-backed Game Session workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java new file mode 100644 index 0000000000..a62581684b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java @@ -0,0 +1,219 @@ +package net.firedevops.firemud.gamesession.command.text; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; + +/** + * Validates and selects actors only from one Account- and route-bound canonical roster snapshot. + */ +public final class CanonicalGameplayActorSelection { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private CanonicalGameplayActorSelection() {} + + /** + * Returns an opaque validated view only when the complete Entity snapshot matches the trusted + * Account and the exact current published route. A rejected snapshot must not reach PLAY. + */ + public static Optional validate( + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot, + UUID expectedAccountUuid, + CanonicalPublishedPlayerRoute expectedRoute) { + try { + if (snapshot == null + || !isNonNil(expectedAccountUuid) + || !expectedAccountUuid.equals(snapshot.canonicalAccountUuid()) + || !isNonNil(snapshot.snapshotUuid()) + || !isCanonicalDigest(snapshot.snapshotDigest()) + || expectedRoute == null + || snapshot.target() == null + || !snapshot.target().getUnknownFields().asMap().isEmpty() + || !CanonicalGameplayRosterClient.expectedTarget(expectedRoute) + .equals(snapshot.target())) { + return Optional.empty(); + } + List actors = snapshot.actors(); + CanonicalGameplayRosterClient.requireValidActors(actors); + return Optional.of(new ValidatedRoster(snapshot, expectedAccountUuid, expectedRoute)); + } catch (RuntimeException malformed) { + return Optional.empty(); + } + } + + /** + * Resolves an optional one-based menu ordinal. Actor UUIDs and actor names are never accepted as + * user selectors; the selected UUID remains internal output from this exact validated snapshot. + */ + public static SelectionResult select(ValidatedRoster roster, String selector) { + if (roster == null) { + return new Denied(Denial.INVALID_SNAPSHOT); + } + List actors = roster.snapshot().actors(); + if (actors.isEmpty()) { + return new Denied(Denial.NO_PRESEEDED_ACTOR); + } + if (selector == null || selector.isBlank()) { + if (actors.size() == 1) { + return selected(roster, 1, actors.getFirst()); + } + return new SelectionRequired( + actors.stream() + .map(actor -> new Choice(actors.indexOf(actor) + 1, actor.displayName())) + .toList()); + } + if (!selector.matches("[1-9][0-9]{0,2}")) { + return new Denied(Denial.INVALID_SELECTOR); + } + int ordinal; + try { + ordinal = Integer.parseInt(selector); + } catch (NumberFormatException malformed) { + return new Denied(Denial.INVALID_SELECTOR); + } + if (ordinal > actors.size()) { + return new Denied(Denial.SELECTOR_OUT_OF_RANGE); + } + return selected(roster, ordinal, actors.get(ordinal - 1)); + } + + private static Selected selected( + ValidatedRoster roster, int ordinal, CanonicalGameplayRosterClient.RosterActor actor) { + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot = roster.snapshot(); + return new Selected( + roster.canonicalAccountUuid(), + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + snapshot.target(), + actor.characterUuid(), + actor.displayName(), + ordinal); + } + + private static boolean isCanonicalDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private static boolean isNonNil(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + /** Snapshot-bound selection data; instances can only be created by {@link #validate}. */ + public static final class ValidatedRoster { + private final CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot; + private final UUID canonicalAccountUuid; + private final CanonicalPublishedPlayerRoute route; + + private ValidatedRoster( + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot, + UUID canonicalAccountUuid, + CanonicalPublishedPlayerRoute route) { + this.snapshot = snapshot; + this.canonicalAccountUuid = canonicalAccountUuid; + this.route = route; + } + + public CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot() { + return snapshot; + } + + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + public CanonicalPublishedPlayerRoute route() { + return route; + } + + public List actors() { + return snapshot.actors(); + } + } + + public sealed interface SelectionResult permits Selected, SelectionRequired, Denied {} + + /** The UUID is usable only as internal input to downstream exact target/account validation. */ + public static final class Selected implements SelectionResult { + private final UUID canonicalAccountUuid; + private final UUID rosterSnapshotUuid; + private final String rosterSnapshotDigest; + private final CanonicalGameplayRosterTarget target; + private final UUID characterUuid; + private final String displayName; + private final int ordinal; + + private Selected( + UUID canonicalAccountUuid, + UUID rosterSnapshotUuid, + String rosterSnapshotDigest, + CanonicalGameplayRosterTarget target, + UUID characterUuid, + String displayName, + int ordinal) { + this.canonicalAccountUuid = canonicalAccountUuid; + this.rosterSnapshotUuid = rosterSnapshotUuid; + this.rosterSnapshotDigest = rosterSnapshotDigest; + this.target = target; + this.characterUuid = characterUuid; + this.displayName = displayName; + this.ordinal = ordinal; + } + + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + public UUID rosterSnapshotUuid() { + return rosterSnapshotUuid; + } + + public String rosterSnapshotDigest() { + return rosterSnapshotDigest; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "CanonicalGameplayRosterTarget is an immutable generated protobuf message.") + public CanonicalGameplayRosterTarget target() { + return target; + } + + public UUID characterUuid() { + return characterUuid; + } + + public String displayName() { + return displayName; + } + + public int ordinal() { + return ordinal; + } + } + + public record Choice(int ordinal, String displayName) {} + + public record SelectionRequired(List choices) implements SelectionResult { + public SelectionRequired { + choices = List.copyOf(Objects.requireNonNull(choices, "choices")); + } + } + + public record Denied(Denial reason) implements SelectionResult { + public Denied { + Objects.requireNonNull(reason, "reason"); + } + } + + public enum Denial { + INVALID_SNAPSHOT, + NO_PRESEEDED_ACTOR, + INVALID_SELECTOR, + SELECTOR_OUT_OF_RANGE + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java new file mode 100644 index 0000000000..e14e9cb902 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Default-off composition for exact canonical route reads. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-gameplay-roster-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalPlayerRouteReadConfiguration { + @Bean(initMethod = "init", destroyMethod = "close") + GameDesignPublishedRealmPolicyClient canonicalPlayerRoutePolicyClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameDesignPublishedRealmPolicyClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean + CanonicalPlayerRouteReadService canonicalPlayerRouteReadService( + ObjectProvider catalogRepositoryProvider, + ObjectProvider admissionRepositoryProvider, + ObjectProvider launchRepositoryProvider, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + GameSessionCanonicalRealmCatalogRepository catalogRepository = + catalogRepositoryProvider.getIfAvailable(); + CanonicalInitialAdmissionRepository admissionRepository = + admissionRepositoryProvider.getIfAvailable(); + CanonicalGameInstanceLaunchAssociationRepository launchRepository = + launchRepositoryProvider.getIfAvailable(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || catalogRepository == null + || admissionRepository == null + || launchRepository == null) { + return CanonicalPlayerRouteReadService.unavailable(); + } + return new CanonicalPlayerRouteReadService( + workloadNamespace, catalogRepository, admissionRepository, launchRepository); + } + + @Bean + CanonicalPublishedPlayerRouteReadService canonicalPublishedPlayerRouteReadService( + CanonicalPlayerRouteReadService routeReader, + ObjectProvider catalogRepositoryProvider, + ObjectProvider launchRepositoryProvider, + GameDesignPublishedRealmPolicyClient policyClient, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + GameSessionCanonicalRealmCatalogRepository catalogRepository = + catalogRepositoryProvider.getIfAvailable(); + CanonicalGameInstanceLaunchAssociationRepository launchRepository = + launchRepositoryProvider.getIfAvailable(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || catalogRepository == null + || launchRepository == null) { + return CanonicalPublishedPlayerRouteReadService.unavailable(); + } + return new CanonicalPublishedPlayerRouteReadService( + workloadNamespace, routeReader, catalogRepository, launchRepository, policyClient); + } + + @Bean + CanonicalGameplayRosterSelectionService canonicalGameplayRosterSelectionService( + CanonicalPlayerRouteReadService routeReader, + CanonicalPublishedPlayerRouteReadService publishedRouteReader, + CanonicalGameplayRosterClient rosterClient) { + return new CanonicalGameplayRosterSelectionService( + routeReader, publishedRouteReader, rosterClient); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java index 3d8be169e7..afa6518c09 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java @@ -67,7 +67,7 @@ public enum OriginKind { throw new IllegalArgumentException( "EXPECT_CLOSED requires a positive exact expectedPriorPointerVersion"); } - // Match the 128-character owner attempt and immutable intent ledgers. + // The retained owner attempt and compatibility audit both support 128 code points. requireText(initialAdmissionRequestId, "initialAdmissionRequestId", 128); if (!REQUEST_DIGEST.matcher(Objects.requireNonNull(requestDigest, "requestDigest")).matches()) { throw new IllegalArgumentException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPublishedPlayerRoute.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPublishedPlayerRoute.java new file mode 100644 index 0000000000..34b196e6d0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPublishedPlayerRoute.java @@ -0,0 +1,39 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** + * Source-only current route plus its exact selected row from Game Design's complete sealed policy + * set. This evidence is not gameplay admission or actor-entry authorization. + */ +public record CanonicalPublishedPlayerRoute( + CanonicalPlayableTarget route, + PublishedRealmEntryPolicySetEvidence policySetEvidence, + PublishedRealmEntryPolicyEvidence selectedPolicyEvidence) { + public CanonicalPublishedPlayerRoute { + Objects.requireNonNull(route, "route"); + Objects.requireNonNull(policySetEvidence, "policySetEvidence"); + Objects.requireNonNull(selectedPolicyEvidence, "selectedPolicyEvidence"); + RealmEntryPolicy policy = selectedPolicyEvidence.policy(); + if (!policySetEvidence.policies().contains(selectedPolicyEvidence) + || !policySetEvidence.target().canonicalTenantId().equals(route.canonicalTenantId()) + || !policySetEvidence.target().canonicalVersionId().equals(route.canonicalVersionId()) + || !policy.worldSlug().equals(route.worldSlug()) + || !policy.realmSlug().equals(route.realmSlug()) + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !"SHARED".equals(route.playableStateScope())) { + throw new IllegalArgumentException( + "Selected PRESEEDED_ONLY policy does not belong to the exact public route and set"); + } + } + + public RealmEntryPolicy entryPolicy() { + return selectedPolicyEvidence.policy(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java new file mode 100644 index 0000000000..398ca8e8a4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamesession.security; + +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Set; + +/** Allows only health and exact owner-read methods in the protected LOGIN composition. */ +public final class ProtectedGameSessionLoginGrpcInterceptor implements ServerInterceptor { + // Do not derive this from AuthTokenInterceptor's public-method configuration: each owner-read + // entry below is also guarded by its existing exact workload/method handler check. + private static final Set ALLOWED_METHODS = + Set.of( + "game_session.v1.GameSessionService/Ping", + "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", + "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", + "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof", + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead"); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (ALLOWED_METHODS.contains(call.getMethodDescriptor().getFullMethodName())) { + return next.startCall(call, headers); + } + call.close( + Status.PERMISSION_DENIED.withDescription( + "Game Session LOGIN-only composition denies this gRPC method"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java new file mode 100644 index 0000000000..f80c5e7ad6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Exact independent World read selector for one committed Game Session launch association. */ +public record CanonicalGameInstanceLaunchAssociationReadRequest( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID gameInstanceUuid, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalGameInstanceLaunchAssociationReadRequest { + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank() || value.length() > 256) { + throw new IllegalArgumentException(name + " must be non-blank and bounded"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java new file mode 100644 index 0000000000..36847fbe6d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; + +/** Reads and qualifies exact durable Game Session owner evidence without changing it. */ +public final class CanonicalGameInstanceLaunchAssociationReadService { + private final CanonicalGameInstanceLaunchAssociationRepository repository; + private final String configuredNamespace; + + public CanonicalGameInstanceLaunchAssociationReadService( + CanonicalGameInstanceLaunchAssociationRepository repository, String configuredNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.configuredNamespace = Objects.requireNonNull(configuredNamespace, "configuredNamespace"); + } + + public CanonicalGameInstanceLaunchAssociation read( + CanonicalGameInstanceLaunchAssociationReadRequest request) { + Objects.requireNonNull(request, "request"); + if (!configuredNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("Read namespace does not match this Game Session owner"); + } + CanonicalGameInstanceLaunchAssociation association = + repository + .read(request.controlPlaneRequestId()) + .orElseThrow( + () -> new IllegalStateException("Canonical launch association is unavailable")); + CompleteLaunchBindingEvidence binding = association.launchBindingEvidence(); + var descriptor = binding.descriptor(); + var attestation = binding.releaseAttestation(); + descriptor.requireValid(); + attestation.requireValid(descriptor); + if (request.readRequestId().equals(descriptor.authoredWorldSourceOperationId()) + || request.readRequestId().toString().equals(descriptor.controlPlaneRequestId()) + || !configuredNamespace.equals(association.targetNamespace()) + || !request.targetNamespace().equals(association.targetNamespace()) + || !request.canonicalTenantId().equals(association.canonicalTenantId()) + || !request.worldSlug().equals(association.worldSlug()) + || !request.gameInstanceUuid().equals(association.gameInstanceUuid()) + || !request.controlPlaneRequestId().equals(association.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(association.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(attestation.evidenceDigest())) { + throw new IllegalStateException( + "Canonical launch association does not match the exact read selector"); + } + return association; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java new file mode 100644 index 0000000000..d5ca70d8d8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java @@ -0,0 +1,330 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.command.text.CanonicalGameplayActorSelection; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Non-admitting composition of the current published route and Entity's preseeded roster reads. The + * execution context must already have been constructed from authenticated Game Session state; this + * unsigned scope carrier is not authentication, Account eligibility, or gameplay authority. + */ +public final class CanonicalGameplayRosterSelectionService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SNAPSHOT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + private final CanonicalPlayerRouteReadService routeReader; + private final CanonicalPublishedPlayerRouteReadService publishedRouteReader; + private final CanonicalGameplayRosterClient rosterClient; + + public CanonicalGameplayRosterSelectionService( + CanonicalPlayerRouteReadService routeReader, + CanonicalPublishedPlayerRouteReadService publishedRouteReader, + CanonicalGameplayRosterClient rosterClient) { + this.routeReader = Objects.requireNonNull(routeReader, "routeReader"); + this.publishedRouteReader = + Objects.requireNonNull(publishedRouteReader, "publishedRouteReader"); + this.rosterClient = Objects.requireNonNull(rosterClient, "rosterClient"); + } + + /** + * Reads a route-bound roster, accepts only an optional one-based ordinal, and obtains Entity's + * original selected-assignment reference. An explicit ordinal must carry the identity returned + * with its menu so a refreshed roster cannot silently rebind that choice. No result from this + * method authorizes or activates gameplay. + */ + public Result select( + PlayerExecutionContext authenticatedContext, + String selector, + SelectionMenuIdentity expectedMenuIdentity) { + if (hasAmbientTransaction()) { + return new Denied(Denial.AMBIENT_TRANSACTION); + } + Optional accountUuid = validateContext(authenticatedContext); + if (accountUuid.isEmpty()) { + return new Denied(Denial.INVALID_CONTEXT); + } + + CanonicalPublishedPlayerRoute current; + try { + CanonicalPlayableTarget selectedTarget = + routeReader.readCurrentTarget(parseCanonicalUuid(authenticatedContext.getTenantId())); + if (selectedTarget == null || !matchesContext(authenticatedContext, selectedTarget)) { + return new Denied(Denial.ROUTE_MISMATCH); + } + current = publishedRouteReader.readCurrent(selectedTarget); + if (current == null || !matchesContext(authenticatedContext, current.route())) { + return new Denied(Denial.ROUTE_MISMATCH); + } + } catch (RuntimeException unavailableOrInvalid) { + return new Denied(routeFailure(unavailableOrInvalid)); + } + + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot; + try { + snapshot = rosterClient.listPreseededRoster(current, authenticatedContext); + } catch (StatusRuntimeException failure) { + return new Denied(rosterFailure(failure)); + } catch (RuntimeException invalidOrUnavailable) { + return new Denied(Denial.INVALID_ROSTER_PROOF); + } + Denial listFreshnessFailure = requireExactCurrentRoute(current); + if (listFreshnessFailure != null) { + return new Denied(listFreshnessFailure); + } + + Optional validated = + CanonicalGameplayActorSelection.validate(snapshot, accountUuid.orElseThrow(), current); + if (validated.isEmpty()) { + return new Denied(Denial.INVALID_ROSTER_PROOF); + } + + if (selector != null && !selector.isBlank()) { + if (expectedMenuIdentity == null) { + return new Denied(Denial.MISSING_MENU_IDENTITY); + } + if (!expectedMenuIdentity.matches(snapshot)) { + return new Denied(Denial.STALE_MENU_IDENTITY); + } + } + + CanonicalGameplayActorSelection.SelectionResult selection = + CanonicalGameplayActorSelection.select(validated.orElseThrow(), selector); + if (selection instanceof CanonicalGameplayActorSelection.SelectionRequired required) { + return new SelectionRequired( + required.choices(), + new SelectionMenuIdentity(snapshot.snapshotUuid(), snapshot.snapshotDigest())); + } + if (selection instanceof CanonicalGameplayActorSelection.Denied denied) { + return new Denied(mapSelectionDenial(denied.reason())); + } + + CanonicalGameplayActorSelection.Selected selected = + (CanonicalGameplayActorSelection.Selected) selection; + PlayerExecutionContext selectedContext = + authenticatedContext.toBuilder() + .setRequestId(UUID.randomUUID().toString()) + .setCharacterId(selected.characterUuid().toString()) + .build(); + + CanonicalGameplayRosterClient.VerifiedPreseededAssignment ownerReference; + try { + ownerReference = rosterClient.readSelectedPreseededAssignment(snapshot, selectedContext); + } catch (StatusRuntimeException failure) { + return new Denied(assignmentFailure(failure, expectedMenuIdentity != null)); + } catch (RuntimeException invalidOrUnavailable) { + return new Denied(Denial.INVALID_ASSIGNMENT_PROOF); + } + if (!matchesOwnerReference(ownerReference, selected)) { + return new Denied(Denial.INVALID_ASSIGNMENT_PROOF); + } + + Denial assignmentFreshnessFailure = requireExactCurrentRoute(current); + if (assignmentFreshnessFailure != null) { + return new Denied(assignmentFreshnessFailure); + } + return new SelectedOwnerReference(ownerReference, selected.displayName(), selected.ordinal()); + } + + private Denial requireExactCurrentRoute(CanonicalPublishedPlayerRoute expected) { + try { + CanonicalPublishedPlayerRoute current = publishedRouteReader.readCurrent(expected.route()); + return expected.equals(current) ? null : Denial.ROUTE_CHANGED; + } catch (RuntimeException unavailableOrInvalid) { + return routeFailure(unavailableOrInvalid); + } + } + + private static Denial routeFailure(RuntimeException failure) { + if (failure instanceof CanonicalPublishedPlayerRouteReadService.StaleAuthorityException) { + return Denial.ROUTE_CHANGED; + } + if (failure instanceof CanonicalPlayerRouteReadService.ReadUnavailableException + || failure instanceof CanonicalPublishedPlayerRouteReadService.StorageUnavailableException + || failure + instanceof CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + || failure instanceof StatusRuntimeException status && isTransient(status.getStatus())) { + return Denial.ROUTE_UNAVAILABLE; + } + if (failure instanceof StatusRuntimeException status + && status.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + return Denial.ROUTE_CHANGED; + } + return Denial.INVALID_ROUTE_PROOF; + } + + private static Denial rosterFailure(StatusRuntimeException failure) { + Status status = failure.getStatus(); + if (isTransient(status)) { + return Denial.ROSTER_UNAVAILABLE; + } + if (status.getCode() == Status.Code.FAILED_PRECONDITION) { + return Denial.ROUTE_CHANGED; + } + return Denial.INVALID_ROSTER_PROOF; + } + + private static Denial assignmentFailure( + StatusRuntimeException failure, boolean menuIdentitySupplied) { + Status status = failure.getStatus(); + if (isTransient(status)) { + return Denial.ASSIGNMENT_UNAVAILABLE; + } + if (status.getCode() == Status.Code.FAILED_PRECONDITION) { + return menuIdentitySupplied ? Denial.STALE_MENU_IDENTITY : Denial.ROUTE_CHANGED; + } + return Denial.INVALID_ASSIGNMENT_PROOF; + } + + private static boolean isTransient(Status status) { + return switch (status.getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, ABORTED -> true; + default -> false; + }; + } + + private static Optional validateContext(PlayerExecutionContext context) { + if (context == null || !context.getUnknownFields().asMap().isEmpty()) { + return Optional.empty(); + } + try { + UUID accountUuid = parseCanonicalUuid(context.getAccountId()); + parseCanonicalUuid(context.getSessionId()); + parseCanonicalUuid(context.getRequestId()); + parseCanonicalUuid(context.getTenantId()); + parseCanonicalUuid(context.getRealmId()); + parseCanonicalUuid(context.getPlayableStateNamespaceId()); + parseCanonicalUuid(context.getGameInstanceId()); + if ((!"SHARED".equals(context.getPlayableStateScope()) + && !"ISOLATED".equals(context.getPlayableStateScope())) + || !context.getCharacterId().isEmpty()) { + return Optional.empty(); + } + return Optional.of(accountUuid); + } catch (IllegalArgumentException malformed) { + return Optional.empty(); + } + } + + private static UUID parseCanonicalUuid(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Canonical UUID is required"); + } + UUID parsed = UUID.fromString(value); + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical UUID is malformed"); + } + return parsed; + } + + private static boolean matchesContext( + PlayerExecutionContext context, CanonicalPlayableTarget route) { + return context.getTenantId().equals(route.canonicalTenantId().toString()) + && context.getRealmId().equals(route.realmId().toString()) + && context.getPlayableStateNamespaceId().equals(route.playableStateNamespaceId().toString()) + && context.getPlayableStateScope().equals(route.playableStateScope()) + && context.getGameInstanceId().equals(route.canonicalGameInstanceId().toString()); + } + + private static boolean matchesOwnerReference( + CanonicalGameplayRosterClient.VerifiedPreseededAssignment ownerReference, + CanonicalGameplayActorSelection.Selected selected) { + return ownerReference != null + && ownerReference.canonicalAccountUuid().equals(selected.canonicalAccountUuid()) + && ownerReference.selectedCharacterUuid().equals(selected.characterUuid()) + && ownerReference.target().equals(selected.target()) + && ownerReference.rosterSnapshotUuid().equals(selected.rosterSnapshotUuid()) + && ownerReference.rosterSnapshotDigest().equals(selected.rosterSnapshotDigest()); + } + + private static Denial mapSelectionDenial(CanonicalGameplayActorSelection.Denial reason) { + return switch (reason) { + case INVALID_SNAPSHOT -> Denial.INVALID_ROSTER_PROOF; + case NO_PRESEEDED_ACTOR -> Denial.NO_PRESEEDED_ACTOR; + case INVALID_SELECTOR -> Denial.INVALID_SELECTOR; + case SELECTOR_OUT_OF_RANGE -> Denial.SELECTOR_OUT_OF_RANGE; + }; + } + + private static boolean hasAmbientTransaction() { + return TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive(); + } + + public sealed interface Result permits SelectedOwnerReference, SelectionRequired, Denied {} + + /** + * Entity's original committed owner reference, still only source evidence for later revalidation. + */ + public record SelectedOwnerReference( + CanonicalGameplayRosterClient.VerifiedPreseededAssignment ownerReference, + String displayName, + int ordinal) + implements Result { + public SelectedOwnerReference { + Objects.requireNonNull(ownerReference, "ownerReference"); + Objects.requireNonNull(displayName, "displayName"); + if (ordinal < 1) { + throw new IllegalArgumentException("ordinal must be one-based"); + } + } + } + + public record SelectionMenuIdentity(UUID snapshotUuid, String snapshotDigest) { + public SelectionMenuIdentity { + Objects.requireNonNull(snapshotUuid, "snapshotUuid"); + Objects.requireNonNull(snapshotDigest, "snapshotDigest"); + if (NIL_UUID.equals(snapshotUuid) || !SNAPSHOT_DIGEST.matcher(snapshotDigest).matches()) { + throw new IllegalArgumentException("Selection menu identity is malformed"); + } + } + + private boolean matches(CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot) { + return snapshotUuid.equals(snapshot.snapshotUuid()) + && snapshotDigest.equals(snapshot.snapshotDigest()); + } + } + + public record SelectionRequired( + List choices, SelectionMenuIdentity menuIdentity) + implements Result { + public SelectionRequired { + choices = List.copyOf(Objects.requireNonNull(choices, "choices")); + Objects.requireNonNull(menuIdentity, "menuIdentity"); + } + } + + public record Denied(Denial reason) implements Result { + public Denied { + Objects.requireNonNull(reason, "reason"); + } + } + + public enum Denial { + AMBIENT_TRANSACTION, + INVALID_CONTEXT, + ROUTE_UNAVAILABLE, + INVALID_ROUTE_PROOF, + ROUTE_MISMATCH, + ROUTE_CHANGED, + ROSTER_UNAVAILABLE, + INVALID_ROSTER_PROOF, + NO_PRESEEDED_ACTOR, + INVALID_SELECTOR, + SELECTOR_OUT_OF_RANGE, + MISSING_MENU_IDENTITY, + STALE_MENU_IDENTITY, + ASSIGNMENT_UNAVAILABLE, + INVALID_ASSIGNMENT_PROOF + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java new file mode 100644 index 0000000000..5e47274f8c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.jooq.exception.DataAccessException; + +/** + * Read-only composition of current Game Session catalog, OPEN proof, and owner-qualified runtime. + */ +public final class CanonicalPlayerRouteReadService { + private final String targetNamespace; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final CanonicalInitialAdmissionRepository admissionRepository; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected repository collaborators are retained only for this service's read composition") + public CanonicalPlayerRouteReadService( + String targetNamespace, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalInitialAdmissionRepository admissionRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository) { + this.targetNamespace = targetNamespace; + this.catalogRepository = catalogRepository; + this.admissionRepository = admissionRepository; + this.launchRepository = launchRepository; + } + + /** + * A default-off identity configuration produces unavailable authority without a startup error. + */ + public static CanonicalPlayerRouteReadService unavailable() { + return new CanonicalPlayerRouteReadService(null, null, null, null); + } + + /** Lists only current visible public-production routes from canonical owner evidence. */ + public List readVisiblePublicProductionTargets() { + requireConfigured(); + List catalogs; + try { + catalogs = catalogRepository.readVisiblePublicProductionSnapshots(targetNamespace); + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical realm catalog read is unavailable", ex); + } catch (RuntimeException ex) { + throw new InvalidAuthorityException("Canonical realm catalog is invalid", ex); + } + if (catalogs == null) { + throw new ReadUnavailableException("Canonical realm catalog read returned no result"); + } + + Set tenantIds = new HashSet<>(); + ArrayList targets = new ArrayList<>(catalogs.size()); + for (CanonicalRealmCatalogSnapshot catalog : catalogs) { + if (catalog == null || !tenantIds.add(catalog.tenantId())) { + throw new InvalidAuthorityException( + "Canonical public-production catalog has duplicate tenant authority"); + } + targets.add(readTargetForCatalog(catalog)); + } + return List.copyOf(targets); + } + + /** Rereads the selected tenant's unique catalog, current OPEN pointer proof, and launch row. */ + public CanonicalPlayableTarget readCurrentTarget(CanonicalPlayableTarget expected) { + Objects.requireNonNull(expected, "expected"); + requireConfigured(); + if (!targetNamespace.equals(expected.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + return readCurrentTarget(expected.canonicalTenantId()); + } + + /** + * Reads one current target by its canonical tenant selector, without trusting caller counters. + */ + public CanonicalPlayableTarget readCurrentTarget(UUID canonicalTenantId) { + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + if (new UUID(0L, 0L).equals(canonicalTenantId)) { + throw new InvalidAuthorityException("Canonical tenant selector must be non-nil"); + } + requireConfigured(); + CanonicalRealmCatalogSnapshot catalog; + try { + catalog = + catalogRepository + .readUniqueVisiblePublicProduction(targetNamespace, canonicalTenantId) + .orElseThrow( + () -> + new InvalidAuthorityException( + "Canonical public-production realm catalog is missing")); + } catch (ReadUnavailableException | InvalidAuthorityException ex) { + throw ex; + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical realm catalog read is unavailable", ex); + } catch (RuntimeException ex) { + throw new InvalidAuthorityException("Canonical realm catalog is invalid", ex); + } + return readTargetForCatalog(catalog); + } + + /** + * Returns false for reachable stale or malformed authority; transport/storage failure escapes. + */ + public boolean matchesCurrentTarget(CanonicalPlayableTarget expected) { + try { + return expected.equals(readCurrentTarget(expected)); + } catch (ReadUnavailableException ex) { + throw ex; + } catch (InvalidAuthorityException ex) { + return false; + } + } + + private CanonicalPlayableTarget readTargetForCatalog(CanonicalRealmCatalogSnapshot catalog) { + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot openSnapshot; + try { + openSnapshot = + admissionRepository.readCurrentOpenSnapshotForRealm( + targetNamespace, catalog.tenantId(), catalog.realmId()); + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical admission owner read is unavailable", ex); + } catch (RuntimeException ex) { + throw new InvalidAuthorityException( + "Canonical OPEN pointer or terminal owner proof is invalid", ex); + } + CanonicalInitialAdmissionOwnerProof proof = openSnapshot.ownerProof(); + requireCatalogMatchesProof(catalog, proof); + + CanonicalInitialAdmissionLaunchTarget launch; + try { + launch = + launchRepository + .readForInitialAdmission( + targetNamespace, + catalog.tenantId(), + catalog.realmId(), + proof.canonicalGameInstanceId()) + .orElseThrow( + () -> + new InvalidAuthorityException( + "Canonical OPEN target has no owner-qualified launch association")); + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical launch association read is unavailable", ex); + } catch (InvalidAuthorityException | ReadUnavailableException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new InvalidAuthorityException("Canonical launch association is invalid", ex); + } + requireLaunchMatchesCatalogAndProof(catalog, proof, launch); + + return new CanonicalPlayableTarget( + targetNamespace, + catalog.tenantSlug(), + catalog.tenantId(), + catalog.worldSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + launch.association().gameSessionTenantId(), + launch.gameInstanceId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + proof.canonicalGameInstanceId(), + proof.canonicalVersionId(), + launch.runtimeVersionId(), + catalog.catalogRevision(), + proof.committedPointerVersion(), + openSnapshot.admissionPointerSnapshotDigest(), + proof.activeLifecycleEpoch(), + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.originKind(), + proof.expectedPriorPointerVersion(), + proof.holdId(), + proof.holdFence(), + proof.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + proof.outcome(), + proof.positiveDurableAbort(), + proof.terminalAt(), + catalog.characterCreationPolicy()); + } + + private void requireCatalogMatchesProof( + CanonicalRealmCatalogSnapshot catalog, CanonicalInitialAdmissionOwnerProof proof) { + if (proof == null + || !proof.provesCommit() + || !targetNamespace.equals(proof.targetNamespace()) + || !targetNamespace.equals(catalog.targetNamespace()) + || !catalog.tenantId().equals(proof.canonicalTenantId()) + || !catalog.worldSlug().equals(proof.worldSlug()) + || !catalog.realmId().equals(proof.realmId()) + || !catalog.playableStateNamespaceId().equals(proof.playableStateNamespaceId()) + || !catalog.stateScope().equals(proof.playableStateScope()) + || catalog.catalogRevision() != proof.expectedCatalogRevision() + || proof.committedPointerVersion() == null + || proof.auditEventId() == null + || proof.proofDigest() == null + || proof.terminalAt() == null) { + throw new InvalidAuthorityException( + "Canonical catalog does not match the committed current OPEN proof"); + } + } + + private void requireLaunchMatchesCatalogAndProof( + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionOwnerProof proof, + CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + if (association.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !association.targetNamespace().equals(targetNamespace) + || !association.canonicalTenantId().equals(catalog.tenantId()) + || !association.worldSlug().equals(catalog.worldSlug()) + || !association.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !association.playableStateScope().name().equals(catalog.stateScope()) + || !association.publicProduction() + || !association.gameInstanceUuid().equals(proof.canonicalGameInstanceId()) + || !launch.realmId().equals(catalog.realmId()) + || !launch.canonicalVersionId().equals(proof.canonicalVersionId())) { + throw new InvalidAuthorityException( + "Canonical launch association does not match the current catalog and OPEN proof"); + } + } + + private void requireConfigured() { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || catalogRepository == null + || admissionRepository == null + || launchRepository == null) { + throw new ReadUnavailableException("Canonical player route authority is not configured"); + } + } + + public static final class ReadUnavailableException extends RuntimeException { + public ReadUnavailableException(String message) { + super(message); + } + + public ReadUnavailableException(String message, RuntimeException cause) { + super(message, cause); + } + } + + public static final class InvalidAuthorityException extends RuntimeException { + public InvalidAuthorityException(String message) { + super(message); + } + + public InvalidAuthorityException(String message, RuntimeException cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java new file mode 100644 index 0000000000..1fd447c38f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java @@ -0,0 +1,538 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.jooq.exception.DataAccessException; + +/** + * Read-only composition of current Game Session routing and a fresh complete Game Design policy + * set. A result is source evidence only and does not enable PLAY or actor admission. + */ +public final class CanonicalPublishedPlayerRouteReadService { + private final String targetNamespace; + private final CanonicalPlayerRouteReadService routeReader; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + private final GameDesignPublishedRealmPolicyClient policyClient; + + public CanonicalPublishedPlayerRouteReadService( + String targetNamespace, + CanonicalPlayerRouteReadService routeReader, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameDesignPublishedRealmPolicyClient policyClient) { + this.targetNamespace = targetNamespace; + this.routeReader = routeReader; + this.catalogRepository = catalogRepository; + this.launchRepository = launchRepository; + this.policyClient = policyClient; + } + + /** Default-off source client: absent composition produces unavailable, never an open route. */ + public static CanonicalPublishedPlayerRouteReadService unavailable() { + return new CanonicalPublishedPlayerRouteReadService(null, null, null, null, null); + } + + /** + * Reads fresh owner policy for an exact current route, checks the original source and launch + * bindings, then rereads the full current route before returning the sealed evidence. + */ + public CanonicalPublishedPlayerRoute readCurrent(CanonicalPlayableTarget expected) { + Objects.requireNonNull(expected, "expected"); + return readCurrent(expected, null); + } + + /** + * Reads an exact caller-selected tenant target and returns complete source evidence for Entity. + * The Account UUID is echoed only; this method does not establish Account membership or PLAY + * authority. + */ + public CanonicalGameplayRosterOwnerReadEvidence readCurrent( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + CanonicalPublishedPlayerRoute route = readCurrent(null, request); + return new CanonicalGameplayRosterOwnerReadEvidence( + request, + route.route().admissionPointerSnapshotDigest(), + ownerProof(route.route()), + route.policySetEvidence()); + } + + /** + * Reads assignment source evidence from exact immutable selectors while deriving current pointer + * and lifecycle counters from Game Session-owned route evidence. This is a staging-only source + * read; the Account selectors are correlation data and do not establish membership or admission. + */ + public PreseededActorAssignmentOwnerReadEvidence readCurrentForAssignment( + PreseededActorAssignmentOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireConfigured(); + if (!targetNamespace.equals(request.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + + CanonicalPlayableTarget current = readRoute(request.canonicalTenantUuid()); + requireAssignmentSelectors(request, current); + var sourceRequest = + PreseededActorAssignmentOwnerReadEvidence.sourceRequest(request, ownerProof(current)); + CanonicalGameplayRosterOwnerReadEvidence sourceEvidence = readCurrent(sourceRequest); + return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); + } + + private CanonicalPublishedPlayerRoute readCurrent( + CanonicalPlayableTarget expected, CanonicalGameplayRosterOwnerReadEvidence.Request request) { + if ((expected == null) == (request == null)) { + throw new IllegalArgumentException("Exactly one canonical route selector is required"); + } + requireConfigured(); + if (expected != null && !targetNamespace.equals(expected.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + if (request != null && !targetNamespace.equals(request.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + + CanonicalPlayableTarget before = + expected == null ? readRoute(request.canonicalTenantUuid()) : readRoute(expected); + if (expected != null) { + requireExpectedRoute(expected, before); + } else { + requireExpectedRequest(request, before); + } + CanonicalRealmCatalogSnapshot catalogBefore = readCatalog(before); + CanonicalInitialAdmissionLaunchTarget launchBefore = readLaunch(before); + requireCurrentRouteBinding(before, catalogBefore, launchBefore); + + PublishedRealmEntryPolicySetEvidence policySet = + readPolicy(before.canonicalTenantId(), before.canonicalVersionId()); + PublishedRealmEntryPolicySetEvidence complete = verifySet(policySet); + PublishedRealmEntryPolicyEvidence selected = + requirePublishedPreseededPolicy(complete, before, catalogBefore, launchBefore); + + CanonicalPlayableTarget after = + expected == null ? readRoute(request.canonicalTenantUuid()) : readRoute(before); + if (!before.equals(after)) { + throw new StaleAuthorityException("Canonical player route changed during policy read"); + } + if (request != null) { + requireExpectedRequest(request, after); + } + CanonicalRealmCatalogSnapshot catalogAfter = readCatalog(after); + CanonicalInitialAdmissionLaunchTarget launchAfter = readLaunch(after); + if (!catalogBefore.equals(catalogAfter) + || !sameCurrentLaunchBinding(launchBefore, launchAfter)) { + throw new StaleAuthorityException( + "Canonical source or complete launch binding changed during policy read"); + } + requireCurrentRouteBinding(after, catalogAfter, launchAfter); + + PublishedRealmEntryPolicySetEvidence confirmedPolicySet = + verifySet(readPolicy(after.canonicalTenantId(), after.canonicalVersionId())); + if (!complete.equals(confirmedPolicySet)) { + throw new StaleAuthorityException( + "Game Design policy source or capture changed during owner read"); + } + + return new CanonicalPublishedPlayerRoute(after, complete, selected); + } + + private GameSessionCanonicalInitialAdmissionOwnerProof ownerProof(CanonicalPlayableTarget route) { + if (route.ownerProofOutcome() != CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + throw new InvalidAuthorityException("Current route lacks terminal COMMITTED owner proof"); + } + WorldCanonicalInitialAdmissionHold.Request request = + new WorldCanonicalInitialAdmissionHold.Request( + route.targetNamespace(), + route.canonicalTenantId(), + route.worldSlug(), + route.realmId(), + route.playableStateNamespaceId(), + route.playableStateScope(), + route.canonicalGameInstanceId(), + route.canonicalVersionId(), + route.activeWorldEpoch(), + route.initialAdmissionRequestId(), + route.initialAdmissionRequestDigest(), + route.initialAdmissionOriginKind() + == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + ? WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER + : WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED, + route.catalogRevision(), + route.expectedPriorPointerVersion()); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, route.holdId(), route.holdFence()); + if (!hold.holdBindingDigest().equals(route.holdBindingDigest())) { + throw new InvalidAuthorityException( + "Current route hold digest differs from the complete World-held request"); + } + GameSessionCanonicalInitialAdmissionOwnerProof proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + route.pointerVersion(), + route.auditEventId(), + route.ownerProofDigest(), + false, + route.ownerProofTerminalAt()); + return GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof)); + } + + private static void requireExpectedRequest( + CanonicalGameplayRosterOwnerReadEvidence.Request expected, CanonicalPlayableTarget current) { + if (current == null + || !expected.targetNamespace().equals(current.targetNamespace()) + || !expected.canonicalTenantUuid().equals(current.canonicalTenantId()) + || !expected.worldSlug().equals(current.worldSlug()) + || !expected.realmUuid().equals(current.realmId()) + || !expected.realmSlug().equals(current.realmSlug()) + || !expected.playableStateNamespaceUuid().equals(current.playableStateNamespaceId()) + || !expected.playableStateScope().equals(current.playableStateScope()) + || !expected.canonicalGameInstanceUuid().equals(current.canonicalGameInstanceId()) + || !expected.canonicalVersionUuid().equals(current.canonicalVersionId()) + || expected.expectedCatalogRevision() != current.catalogRevision() + || expected.expectedPointerVersion() != current.pointerVersion() + || expected.expectedActiveWorldEpoch() != current.activeWorldEpoch()) { + throw new StaleAuthorityException( + "Canonical current route differs from the exact requested selectors and counters"); + } + } + + private static void requireAssignmentSelectors( + PreseededActorAssignmentOwnerReadEvidence.Request expected, CanonicalPlayableTarget current) { + if (current == null + || !expected.targetNamespace().equals(current.targetNamespace()) + || !expected.canonicalTenantUuid().equals(current.canonicalTenantId()) + || !expected.worldSlug().equals(current.worldSlug()) + || !expected.realmUuid().equals(current.realmId()) + || !expected.realmSlug().equals(current.realmSlug()) + || !expected.playableStateNamespaceUuid().equals(current.playableStateNamespaceId()) + || !expected.playableStateScope().equals(current.playableStateScope()) + || !expected.canonicalGameInstanceUuid().equals(current.canonicalGameInstanceId()) + || !expected.canonicalVersionUuid().equals(current.canonicalVersionId()) + || expected.expectedCatalogRevision() != current.catalogRevision()) { + throw new StaleAuthorityException( + "Canonical current route differs from the exact actor-assignment selectors"); + } + } + + private CanonicalPlayableTarget readRoute(CanonicalPlayableTarget expected) { + try { + return routeReader.readCurrentTarget(expected); + } catch (CanonicalPlayerRouteReadService.ReadUnavailableException unavailable) { + throw new StorageUnavailableException("Canonical route storage is unavailable", unavailable); + } catch (CanonicalPlayerRouteReadService.InvalidAuthorityException invalid) { + throw new InvalidAuthorityException("Canonical route authority is invalid", invalid); + } + } + + private CanonicalPlayableTarget readRoute(UUID canonicalTenantId) { + try { + return routeReader.readCurrentTarget(canonicalTenantId); + } catch (CanonicalPlayerRouteReadService.ReadUnavailableException unavailable) { + throw new StorageUnavailableException("Canonical route storage is unavailable", unavailable); + } catch (CanonicalPlayerRouteReadService.InvalidAuthorityException invalid) { + throw new InvalidAuthorityException("Canonical route authority is invalid", invalid); + } + } + + private CanonicalRealmCatalogSnapshot readCatalog(CanonicalPlayableTarget route) { + try { + return catalogRepository + .readUniqueVisiblePublicProduction(targetNamespace, route.canonicalTenantId()) + .orElseThrow( + () -> new StaleAuthorityException("Canonical public-production catalog is missing")); + } catch (DataAccessException unavailable) { + throw new StorageUnavailableException( + "Canonical catalog storage is unavailable", unavailable); + } catch (StaleAuthorityException stale) { + throw stale; + } catch (RuntimeException invalid) { + throw new InvalidAuthorityException("Canonical catalog source evidence is invalid", invalid); + } + } + + private CanonicalInitialAdmissionLaunchTarget readLaunch(CanonicalPlayableTarget route) { + try { + return launchRepository + .readForInitialAdmission( + targetNamespace, + route.canonicalTenantId(), + route.realmId(), + route.canonicalGameInstanceId()) + .orElseThrow( + () -> new StaleAuthorityException("Current canonical launch binding is missing")); + } catch (DataAccessException unavailable) { + throw new StorageUnavailableException("Canonical launch storage is unavailable", unavailable); + } catch (StaleAuthorityException stale) { + throw stale; + } catch (RuntimeException invalid) { + throw new InvalidAuthorityException("Canonical launch binding is invalid", invalid); + } + } + + private PublishedRealmEntryPolicySetEvidence readPolicy( + UUID canonicalTenantId, UUID canonicalVersionId) { + try { + return policyClient.listPublishedRealmEntryPolicies(canonicalTenantId, canonicalVersionId); + } catch (StatusRuntimeException failure) { + if (isTransient(failure.getStatus())) { + throw new GameDesignUnavailableException( + "Game Design policy transport is unavailable", failure); + } + if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + throw new StaleAuthorityException("Game Design policy owner read is stale"); + } + throw new InvalidAuthorityException("Game Design policy owner read was rejected", failure); + } catch (GameDesignPublishedRealmPolicyClient.UninitializedClientException unavailable) { + throw new GameDesignUnavailableException( + "Game Design policy transport is unavailable", unavailable); + } catch (GameDesignPublishedRealmPolicyClient.InvalidResponseException invalid) { + throw new InvalidAuthorityException("Game Design policy response is invalid", invalid); + } catch (IllegalArgumentException rejected) { + throw new InvalidAuthorityException("Game Design policy owner read was rejected", rejected); + } + } + + private static boolean isTransient(io.grpc.Status status) { + return switch (status.getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, ABORTED -> true; + default -> false; + }; + } + + private PublishedRealmEntryPolicySetEvidence verifySet( + PublishedRealmEntryPolicySetEvidence policySet) { + if (policySet == null) { + throw new InvalidAuthorityException("Game Design returned no published policy set"); + } + try { + return PublishedRealmEntryPolicySetEvidence.fromStored(policySet.canonicalBytes()); + } catch (RuntimeException invalid) { + throw new InvalidAuthorityException( + "Game Design policy set is not complete closed evidence", invalid); + } + } + + private PublishedRealmEntryPolicyEvidence requirePublishedPreseededPolicy( + PublishedRealmEntryPolicySetEvidence complete, + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch) { + var source = catalog.sourceIntakeReceipt().source(); + var targetProof = complete.target(); + var operation = GameDesignPublicationOperationBinding.fromStored(complete.operationBytes()); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(complete.terminalEvidenceBytes()); + var association = launch.association(); + var descriptor = association.launchBindingEvidence().descriptor(); + var release = association.launchBindingEvidence().releaseAttestation(); + if (!operation.account().input().selection().target().equals(targetProof) + || !targetNamespace.equals(operation.world().request().targetNamespace()) + || !targetNamespace.equals(terminal.worldEvidence().request().targetNamespace()) + || !route.canonicalTenantId().equals(operation.world().request().canonicalTenantId()) + || !route.canonicalVersionId().equals(operation.world().request().canonicalVersionId()) + || !complete.target().canonicalTenantId().equals(route.canonicalTenantId()) + || !complete.target().canonicalVersionId().equals(route.canonicalVersionId()) + || !targetNamespace.equals(source.targetNamespace()) + || !route.canonicalTenantId().equals(source.canonicalTenantId()) + || targetProof.sourceGameRowId() != source.sourceGameRowId() + || !targetProof.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !targetProof.gameDesignVersionTenantKey().equals(source.sourceGameTenantKey()) + || !targetProof.sourceProvenanceKind().equals(source.provenanceKind()) + || !release.authoredWorldSourceOperationId().equals(source.operationId()) + || !release.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || !release.commitId().equals(complete.sourceCommitId().toString()) + || !release.publishedReleaseBundleRef().equals(complete.publishedReleaseBundleRef()) + || !release.publishWorkflowId().equals(complete.publishWorkflowId()) + || !release.manifestHash().equals(complete.manifestHash()) + || release.versionStateEpoch() != complete.publicationVersionStateEpoch() + || !terminal.publishedReleaseBundleRef().equals(complete.publishedReleaseBundleRef()) + || !terminal.publishedReleaseBundleDigest().equals(complete.publishedReleaseBundleDigest()) + || !terminal.releaseContent().publishWorkflowId().equals(complete.publishWorkflowId()) + || !terminal.releaseContent().manifestHash().equals(complete.manifestHash()) + || terminal.publicationVersionStateEpoch() != complete.publicationVersionStateEpoch() + || !descriptor.publishedReleaseBundleRef().equals(complete.publishedReleaseBundleRef()) + || descriptor.versionStateEpoch() != complete.publicationVersionStateEpoch()) { + throw new InvalidAuthorityException( + "Published policy source or release does not match the current complete launch binding"); + } + + var matches = + complete.policies().stream() + .filter( + evidence -> + evidence.policy().worldSlug().equals(route.worldSlug()) + && evidence.policy().realmSlug().equals(route.realmSlug())) + .toList(); + if (matches.size() != 1) { + throw new InvalidAuthorityException("Published policy set lacks the exact current selector"); + } + PublishedRealmEntryPolicyEvidence selected = matches.getFirst(); + RealmEntryPolicy policy = selected.policy(); + if (!policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !catalog.visible() + || !catalog.publicProduction() + || !"SHARED".equals(catalog.stateScope())) { + throw new InvalidAuthorityException( + "Published policy and current public-production route do not match PRESEEDED_ONLY"); + } + return selected; + } + + private void requireCurrentRouteBinding( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + var source = catalog.sourceIntakeReceipt().source(); + var descriptor = association.launchBindingEvidence().descriptor(); + var release = association.launchBindingEvidence().releaseAttestation(); + if (!targetNamespace.equals(route.targetNamespace()) + || !targetNamespace.equals(catalog.targetNamespace()) + || !route.canonicalTenantId().equals(catalog.tenantId()) + || !route.worldSlug().equals(catalog.worldSlug()) + || !route.realmId().equals(catalog.realmId()) + || !route.realmSlug().equals(catalog.realmSlug()) + || !route.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !route.playableStateScope().equals(catalog.stateScope()) + || !catalog.visible() + || !catalog.publicProduction() + || !"SHARED".equals(catalog.stateScope()) + || !route.canonicalTenantId().equals(association.canonicalTenantId()) + || !route.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !route.worldSlug().equals(association.worldSlug()) + || !route.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || association.playableStateScope() != RealmEntryPolicy.StateScope.SHARED + || !association.publicProduction() + || association.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !route.realmId().equals(launch.realmId()) + || route.gameInstanceId() != launch.gameInstanceId() + || route.runtimeVersionId() != launch.runtimeVersionId() + || !route.canonicalVersionId().equals(launch.canonicalVersionId()) + || !targetNamespace.equals(descriptor.targetNamespace()) + || !route.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !route.worldSlug().equals(descriptor.worldSlug()) + || !route.canonicalTenantId().equals(release.canonicalTenantId()) + || !route.canonicalVersionId().equals(release.canonicalVersionId()) + || !route.worldSlug().equals(release.worldSlug()) + || !targetNamespace.equals(release.targetNamespace()) + || !source.operationId().equals(descriptor.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !source.operationId().equals(release.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) + || descriptor.versionId() != route.runtimeVersionId() + || descriptor.versionStateEpoch() != release.versionStateEpoch() + || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) + || !association.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !association.launchDescriptorId().equals(descriptor.launchDescriptorId())) { + throw new InvalidAuthorityException( + "Canonical catalog, route, and complete launch binding disagree"); + } + } + + private static void requireExpectedRoute( + CanonicalPlayableTarget expected, CanonicalPlayableTarget current) { + if (current == null || !expected.equals(current)) { + throw new StaleAuthorityException( + "Selected canonical player route changed before policy read"); + } + } + + private static boolean sameCurrentLaunchBinding( + CanonicalInitialAdmissionLaunchTarget left, CanonicalInitialAdmissionLaunchTarget right) { + if (right == null + || !left.realmId().equals(right.realmId()) + || left.gameInstanceId() != right.gameInstanceId() + || left.runtimeVersionId() != right.runtimeVersionId()) { + return false; + } + CanonicalGameInstanceLaunchAssociation first = left.association(); + CanonicalGameInstanceLaunchAssociation second = right.association(); + return first.targetNamespace().equals(second.targetNamespace()) + && first.gameSessionTenantId() == second.gameSessionTenantId() + && first.tenantAssociationOperationId().equals(second.tenantAssociationOperationId()) + && first.canonicalTenantId().equals(second.canonicalTenantId()) + && first.gameInstanceUuid().equals(second.gameInstanceUuid()) + && first.worldSlug().equals(second.worldSlug()) + && first.playableStateNamespaceId().equals(second.playableStateNamespaceId()) + && first.playableStateScope() == second.playableStateScope() + && first.publicProduction() == second.publicProduction() + && first.controlPlaneRequestId().equals(second.controlPlaneRequestId()) + && first.launchDescriptorId().equals(second.launchDescriptorId()) + && first.capturedStartingRowVersion() == second.capturedStartingRowVersion() + && first.currentRowVersion() == second.currentRowVersion() + && first.launchBindingEvidence().equals(second.launchBindingEvidence()) + && first.currentGameInstanceStatus() == second.currentGameInstanceStatus(); + } + + private void requireConfigured() { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || routeReader == null + || catalogRepository == null + || launchRepository == null + || policyClient == null) { + throw new StorageUnavailableException("Canonical published player-route reader is disabled"); + } + } + + public static class InvalidAuthorityException extends RuntimeException { + public InvalidAuthorityException(String message) { + super(message); + } + + public InvalidAuthorityException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class StaleAuthorityException extends InvalidAuthorityException { + public StaleAuthorityException(String message) { + super(message); + } + } + + public static final class StorageUnavailableException extends RuntimeException { + public StorageUnavailableException(String message, Throwable cause) { + super(message, cause); + } + + public StorageUnavailableException(String message) { + super(message); + } + } + + public static final class GameDesignUnavailableException extends RuntimeException { + public GameDesignUnavailableException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapter.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapter.java new file mode 100644 index 0000000000..d1eb68ea5b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapter.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadGrpcCodec; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.grpc.server.service.GrpcService; + +/** + * Entity-only source read adapter. Its Game Session and Game Design evidence does not replace the + * Account staging snapshot supplied to Entity and never enables PLAY, actor entry, bootstrap, OPEN, + * or generation. + */ +@GrpcService +public final class CanonicalGameplayRosterOwnerReadGrpcAdapter + extends CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase { + private final ObjectProvider sourceReaderProvider; + private final CanonicalGameplayRosterOwnerReadWorkloadGuard workloadGuard; + + public CanonicalGameplayRosterOwnerReadGrpcAdapter( + ObjectProvider sourceReaderProvider, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.sourceReaderProvider = sourceReaderProvider; + this.workloadGuard = new CanonicalGameplayRosterOwnerReadWorkloadGuard(workloadNamespace); + } + + @Override + public void getCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest request, + StreamObserver responseObserver) { + CanonicalGameplayRosterOwnerReadEvidence.Request typedRequest; + try { + workloadGuard.requireEntityOwnerReadCaller(); + typedRequest = CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(request); + workloadGuard.requireConfiguredTargetNamespace(typedRequest.targetNamespace()); + } catch (AdminAuthorizationException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Canonical gameplay roster owner read is not authorized") + .asRuntimeException()); + return; + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical gameplay roster owner read request is invalid") + .asRuntimeException()); + return; + } + try { + CanonicalPublishedPlayerRouteReadService sourceReader = sourceReaderProvider.getIfAvailable(); + if (sourceReader == null) { + throw new SourceUnavailableException(); + } + CanonicalGameplayRosterOwnerReadEvidence evidence = sourceReader.readCurrent(typedRequest); + responseObserver.onNext( + CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(typedRequest, evidence)); + responseObserver.onCompleted(); + } catch (CanonicalPublishedPlayerRouteReadService.StaleAuthorityException stale) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical gameplay roster route is stale") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException invalid) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical gameplay roster authority is invalid") + .asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical gameplay roster authority is invalid") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.StorageUnavailableException + | CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + | CanonicalPlayerRouteReadService.ReadUnavailableException + | SourceUnavailableException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Canonical gameplay roster owner read is unavailable") + .asRuntimeException()); + } catch (RuntimeException unexpected) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Canonical gameplay roster owner read failed") + .asRuntimeException()); + } + } + + @Override + public void getPreseededActorAssignmentOwnerRead( + GetPreseededActorAssignmentOwnerReadRequest request, + StreamObserver responseObserver) { + PreseededActorAssignmentOwnerReadEvidence.Request typedRequest; + try { + workloadGuard.requireEntityAssignmentOwnerReadCaller(); + typedRequest = PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(request); + workloadGuard.requireConfiguredTargetNamespace(typedRequest.targetNamespace()); + } catch (AdminAuthorizationException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Actor assignment owner read is not authorized") + .asRuntimeException()); + return; + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Actor assignment owner read request is invalid") + .asRuntimeException()); + return; + } + try { + CanonicalPublishedPlayerRouteReadService sourceReader = sourceReaderProvider.getIfAvailable(); + if (sourceReader == null) { + throw new SourceUnavailableException(); + } + PreseededActorAssignmentOwnerReadEvidence evidence = + sourceReader.readCurrentForAssignment(typedRequest); + responseObserver.onNext( + PreseededActorAssignmentOwnerReadGrpcCodec.toResponse(typedRequest, evidence)); + responseObserver.onCompleted(); + } catch (CanonicalPublishedPlayerRouteReadService.StaleAuthorityException stale) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical actor assignment route is stale") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException invalid) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical actor assignment authority is invalid") + .asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical actor assignment authority is invalid") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.StorageUnavailableException + | CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + | CanonicalPlayerRouteReadService.ReadUnavailableException + | SourceUnavailableException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Actor assignment owner read is unavailable") + .asRuntimeException()); + } catch (RuntimeException unexpected) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Actor assignment owner read failed") + .asRuntimeException()); + } + } + + private static final class SourceUnavailableException extends RuntimeException {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadWorkloadGuard.java new file mode 100644 index 0000000000..6731e61ade --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadWorkloadGuard.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; + +/** Exact same-namespace Entity workload authorization for roster and assignment owner reads. */ +public final class CanonicalGameplayRosterOwnerReadWorkloadGuard { + private static final String ROSTER_METHOD_NAME = + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead"; + private static final String ASSIGNMENT_METHOD_NAME = + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead"; + private static final String ENTITY_MANAGEMENT_SERVICE = "entity-management-service"; + + private final String trustedNamespace; + + public CanonicalGameplayRosterOwnerReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireEntityOwnerReadCaller() { + requireEntityOwnerReadCaller( + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetCanonicalGameplayRosterOwnerReadMethod() + .getFullMethodName()); + } + + public void requireEntityAssignmentOwnerReadCaller() { + requireEntityOwnerReadCaller( + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetPreseededActorAssignmentOwnerReadMethod() + .getFullMethodName()); + } + + private void requireEntityOwnerReadCaller(String expectedMethod) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if ((!ROSTER_METHOD_NAME.equals(expectedMethod) + && !ASSIGNMENT_METHOD_NAME.equals(expectedMethod)) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peer == null + || !ENTITY_MANAGEMENT_SERVICE.equals(peer.service()) + || !trustedNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + ENTITY_MANAGEMENT_SERVICE) + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Game Session owner read requires the exact same-namespace " + + "Entity Management workload without caller context"); + } + } + + public void requireConfiguredTargetNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Game Session owner-read target namespace is not configured here"); + } + } +} diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index cebb269764..9f724ecca8 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -132,6 +132,8 @@ firemud: force-internal-service-outbound: true public-methods: - game_session.v1.GameSessionService/Ping + - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead + - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead - game_session.v1.GameSessionService/AuthorizeStartSession grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 720a2b087f..ce3c40a7fa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -8,6 +8,11 @@ import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.when; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import net.firedevops.firemud.common.ApiResponse; @@ -22,8 +27,10 @@ import net.firedevops.firemud.gamesession.client.WorldManagementClient; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.FiremudAuthTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -93,6 +100,43 @@ static void configure(DynamicPropertyRegistry registry) { @org.springframework.beans.factory.annotation.Autowired private SessionContextService sessionContextService; + @org.springframework.beans.factory.annotation.Autowired + private GameInstanceRepository gameInstanceRepository; + + @Test + void legacyNumericStartIsDeniedBeforePersistenceOrWorldPreparation() throws Exception { + when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) + .thenReturn( + net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("Numeric Game Session launch selectors are not authorizing") + .build()) + .build()); + StartSessionRequest request = new StartSessionRequest(42L, 7L, "cp-1", 100L); + int existingGameInstances = gameInstanceRepository.findAll().size(); + + HttpRequest.Builder httpRequest = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/sessions")) + .header("Content-Type", "application/json"); + privilegedHeaders().forEach(httpRequest::header); + HttpResponse response = + HttpClient.newHttpClient() + .send( + httpRequest + .POST( + HttpRequest.BodyPublishers.ofString( + OBJECT_MAPPER.writeValueAsString(request), StandardCharsets.UTF_8)) + .build(), + HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + + assertThat(response.statusCode()).isEqualTo(400); + assertThat(response.body()).contains("FAILED_PRECONDITION"); + assertThat(gameInstanceRepository.findAll()).hasSize(existingGameInstances); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient); + } + @Test void startSessionUsesRealHttpAndPersistencePath() throws Exception { when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 74f802f4bb..bd8579d5d7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -449,6 +449,35 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { .isZero(); } + @Test + void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { + Fixture fixture = fixture(); + PreparedAdmission prepared = prepareAdmission(fixture); + String requestId = "r".repeat(128); + CanonicalInitialAdmissionRequest request = + initialAdmissionRequest( + prepared.catalog(), + prepared.binding(), + requestId, + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + uuid(115), + uuid(116)); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(request); + return null; + }); + + CanonicalInitialAdmissionOwnerProof retained = + fixture.initialAdmissionRepository.read(NAMESPACE, requestId).orElseThrow(); + assertThat(retained.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertThat(retained.initialAdmissionRequestId()).isEqualTo(requestId); + assertThat(retained.holdId()).isEqualTo(request.holdId()); + assertThat(retained.holdFence()).isEqualTo(request.holdFence()); + } + @Test void newNoPriorPointerReservationRejectsAnAlreadyOpenRealmWithoutLeavingPendingAttempt() { Fixture fixture = fixture(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index f0a3c40e7f..9812ffd5a5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -31,6 +32,7 @@ import net.firedevops.firemud.gamesession.service.CommandService; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionStateService; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -368,6 +370,85 @@ void setUp() throws Exception { .build()); } + @Test + void numericStartIsDeniedBeforeStateOrWorldMutation() { + when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) + .thenReturn(deniedNumericLaunchResponse()); + assertThatThrownBy(() -> service.startSession(new StartSessionRequest(42L, 7L, "cp-1", 100L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FAILED_PRECONDITION"); + + assertThat(repository.findAll()).isEmpty(); + verifyNoInteractions(sessionStateService, worldManagementClient); + } + + @Test + void numericReplacementLaunchIsDeniedBeforeChangingPriorRunningSession() { + when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-2")) + .thenReturn(deniedNumericLaunchResponse()); + GameInstance existing = new GameInstance(); + existing.setTenantId(42L); + existing.setRuntimeVersion("1.0.0"); + existing.setScriptPatchVersion("patch-1"); + existing.setScriptPinEpoch(1L); + existing.setScriptPatchPinnedControlPlaneRequestId("pin-request-1"); + existing.setOwnerAccountId(100L); + existing.setStatus("RUNNING"); + existing = repository.saveAndFlush(existing); + long existingId = existing.getId(); + + assertThatThrownBy( + () -> service.startSession(new StartSessionRequest(42L, 7L, "cp-2", 100L), true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FAILED_PRECONDITION"); + + assertThat(repository.findAll()).hasSize(1); + GameInstance restored = repository.findById(existingId).orElseThrow(); + assertThat(restored.getStatus()).isEqualTo("RUNNING"); + assertThat(restored.getRuntimeVersion()).isEqualTo("1.0.0"); + assertThat(restored.getScriptPatchVersion()).isEqualTo("patch-1"); + assertThat(restored.getScriptPinEpoch()).isEqualTo(1L); + assertThat(restored.getScriptPatchPinnedControlPlaneRequestId()).isEqualTo("pin-request-1"); + assertThat(restored.getOwnerAccountId()).isEqualTo(100L); + verifyNoInteractions(sessionStateService, worldManagementClient); + } + + @Test + void numericReplacementLaunchIsDeniedBeforePriorWorldTermination() { + when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-2")) + .thenReturn(deniedNumericLaunchResponse()); + GameInstance existing = new GameInstance(); + existing.setTenantId(42L); + existing.setRuntimeVersion("1.0.0"); + existing.setScriptPatchVersion("patch-1"); + existing.setScriptPinEpoch(1L); + existing.setScriptPatchPinnedControlPlaneRequestId("pin-request-1"); + existing.setOwnerAccountId(100L); + existing.setStatus("RUNNING"); + existing = repository.saveAndFlush(existing); + long existingId = existing.getId(); + + assertThatThrownBy( + () -> service.startSession(new StartSessionRequest(42L, 7L, "cp-2", 100L), true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FAILED_PRECONDITION"); + assertThat(repository.findById(existingId)).isPresent(); + assertThat(repository.findById(existingId).orElseThrow().getStatus()).isEqualTo("RUNNING"); + assertThat(repository.findAll()).hasSize(1); + verifyNoInteractions(sessionStateService, worldManagementClient); + } + + private static net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse + deniedNumericLaunchResponse() { + return net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("Numeric Game Session launch selectors cannot authorize a launch") + .build()) + .build(); + } + @Test void startSessionRollsBackWhenStatePropagationFails() { doThrow(new IllegalStateException("state propagation failed")) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java new file mode 100644 index 0000000000..a64ba478a8 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java @@ -0,0 +1,1018 @@ +package unit.net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.lang.reflect.Field; +import java.security.MessageDigest; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayRosterClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_UUID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_UUID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID SESSION_UUID = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID LIST_REQUEST_UUID = uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID SELECT_REQUEST_UUID = uuid("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID ACTOR_UUID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID SNAPSHOT_UUID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ASSIGNMENT_UUID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + // Golden v3 vector from Entity's CanonicalGameplayRosterSnapshotDigest.compute contract. + private static final String ENTITY_OWNED_ROSTER_DIGEST_VECTOR = + "a567381a308464fb6f6b5d18fcd7caa1eb29faf5c37903b130f98ef351a0060f"; + + @Test + void sendsExactPublishedTargetWithAccountAndValidatesSourceSnapshot() throws Exception { + var route = publishedRoute(); + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + var actor = actor(ACTOR_UUID, "Pilot One"); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of(ACTOR_UUID.toString(), "Pilot One"))) + .addActors(actor) + .build(); + }); + var client = newClient(stub); + + var roster = client.listPreseededRoster(route, listContext()); + + assertThat(roster.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(roster.snapshotUuid()).isEqualTo(SNAPSHOT_UUID); + assertThat(roster.target().getTenantUuid()).isEqualTo(TENANT_UUID.toString()); + assertThat(roster.target().getPublishedPolicyDigest()) + .isEqualTo(route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())); + assertThat(roster.target().getPublishedPolicyDigest()).matches("[0-9a-f]{64}"); + assertThat(roster.target().getPublishedReleaseBundleRef()) + .isEqualTo(route.policySetEvidence().publishedReleaseBundleRef()); + assertThat(roster.target().getPublishedOwnerProofDigest()).isEqualTo("f".repeat(64)); + assertThat(roster.actors()) + .containsExactly(new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One")); + + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + var requestCaptor = org.mockito.ArgumentCaptor.forClass(CanonicalGameplayRosterRequest.class); + verify(stub).listPreseededRoster(requestCaptor.capture()); + var request = requestCaptor.getValue(); + assertThat(UUID.fromString(request.getRequestUuid()).toString()) + .isEqualTo(request.getRequestUuid()); + assertThat(request.getCanonicalAccountUuid()).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(request.getExpectedTarget()).isEqualTo(roster.target()); + assertThat(request.getRequestUuid()).isEqualTo(listContext().getRequestId()); + assertThat(request.hasPlayerExecutionContext()).isTrue(); + assertThat(request.getPlayerExecutionContext()).isEqualTo(listContext()); + assertThat(request.getExpectedTarget().getPublishedPolicyDigest()) + .isEqualTo(route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())); + } + + @Test + void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var unknown = + UnknownFieldSet.newBuilder() + .addField(101, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertThatThrownBy(() -> client.listPreseededRoster(publishedRoute(), null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("context is required"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setAccountId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setSessionId("").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("session_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setRequestId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder() + .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("playable_state_namespace_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setTenantId(ACCOUNT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenant_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setRealmId(ACCOUNT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("realm_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setGameInstanceId(ACCOUNT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("game_instance_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setPlayableStateScope("2").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact SHARED or ISOLATED"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setPlayableStateScope("ISOLATED").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the expected target"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setCharacterId(ACTOR_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not select an actor"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown fields"); + + verify(stub, never()).listPreseededRoster(any()); + } + + @Test + void matchesEntityOwnedRosterDigestV3GoldenVector() throws Exception { + var target = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid("11111111-1111-4111-8111-111111111111") + .setRealmUuid("22222222-2222-4222-8222-222222222222") + .setWorldSlug("earth") + .setRealmSlug("main") + .setGameInstanceUuid("44444444-4444-4444-8444-444444444444") + .setCatalogRevision(1L) + .setPointerVersion(7L) + .setActiveWorldEpoch(82L) + .setCanonicalVersionUuid("33333333-3333-4333-8333-333333333333") + .setPublishedPolicyDigest("a".repeat(64)) + .setPublishedReleaseBundleRef("release/fixture-v1") + .setAdmissionPointerSnapshotDigest("d".repeat(64)) + .setPublishedOwnerProofDigest("f".repeat(64)) + .setPlayableStateNamespaceUuid("55555555-5555-4555-8555-555555555555") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + var calculateDigest = + CanonicalGameplayRosterClient.class.getDeclaredMethod( + "calculateSnapshotDigest", UUID.class, CanonicalGameplayRosterTarget.class, List.class); + calculateDigest.setAccessible(true); + + String digest = + (String) + calculateDigest.invoke( + null, + ACCOUNT_UUID, + target, + List.of(new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"))); + + assertThat(digest).isEqualTo(ENTITY_OWNED_ROSTER_DIGEST_VECTOR); + } + + @Test + void rejectsChangedAccountAndCompleteTargetEcho() throws Exception { + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(TENANT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .build(); + }); + + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("canonical account UUID"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget().toBuilder().setPointerVersion(99L).build()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + } + + @Test + void rejectsDuplicateMalformedAndUnsupportedActors() throws Exception { + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + var duplicate = actor(ACTOR_UUID, "Pilot One"); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of( + ACTOR_UUID.toString(), + "Pilot One", + ACTOR_UUID.toString(), + "Pilot One"))) + .addActors(duplicate) + .addActors(duplicate) + .build(); + }); + + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("duplicate character UUID"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .addActors( + actor(ACTOR_UUID, "Pilot One").toBuilder().setDisplayName(" Pilot ").build()) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("display name is malformed"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .addActors( + actor(ACTOR_UUID, "Pilot One").toBuilder() + .setActorKind( + CanonicalGameplayRosterActorKind + .CANONICAL_ROSTER_ACTOR_KIND_UNSPECIFIED) + .build()) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsupported actor kind"); + } + + @Test + void rejectsBadSnapshotDigestAndPropagatesEntityTransportFailures() throws Exception { + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .addActors(actor(ACTOR_UUID, "Pilot One")) + .build(); + }); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("snapshot_digest does not bind"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA") + .setSnapshotDigest("a".repeat(64)) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("snapshot_uuid is not a canonical non-nil UUID"); + + var transportFailure = + Status.UNAVAILABLE.withDescription("owner unavailable").asRuntimeException(); + doThrow(transportFailure).when(stub).listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isSameAs(transportFailure); + } + + @Test + void readsExactSelectedAssignmentAndReturnsBoundNonAdmissionCapability() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request); + }); + + var verified = client.readSelectedPreseededAssignment(roster, selectedContext()); + + assertThat(verified.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(verified.selectedCharacterUuid()).isEqualTo(ACTOR_UUID); + assertThat(verified.target()).isEqualTo(roster.target()); + assertThat(verified.rosterSnapshotUuid()).isEqualTo(SNAPSHOT_UUID); + assertThat(verified.rosterSnapshotDigest()).isEqualTo(roster.snapshotDigest()); + assertThat(verified.assignmentOperationId()).isEqualTo(ASSIGNMENT_UUID); + assertThat(verified.intentDigest()).isEqualTo("c".repeat(64)); + + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(CanonicalGameplayRosterSelectedAssignmentRequest.class); + verify(stub).readSelectedPreseededAssignment(requestCaptor.capture()); + var request = requestCaptor.getValue(); + UUID requestUuid = UUID.fromString(request.getRequestUuid()); + assertThat(requestUuid.toString()).isEqualTo(request.getRequestUuid()); + assertThat(requestUuid).isEqualTo(SELECT_REQUEST_UUID); + assertThat(request.getCanonicalAccountUuid()).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(request.getSelectedCharacterUuid()).isEqualTo(ACTOR_UUID.toString()); + assertThat(request.getExpectedTarget()).isEqualTo(roster.target()); + assertThat(request.getExpectedSnapshot()) + .isEqualTo( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.snapshotUuid().toString()) + .setSnapshotDigest(roster.snapshotDigest()) + .build()); + assertThat(request.getPlayerExecutionContext()).isEqualTo(selectedContext()); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsSelectedContextAccountNamespaceAndActorSubstitutionBeforeRpc() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, + selectedContext().toBuilder().setAccountId(TENANT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account does not match"); + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, + selectedContext().toBuilder() + .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("playable_state_namespace_id"); + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, + selectedContext().toBuilder().setCharacterId(SNAPSHOT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exactly once"); + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, selectedContext().toBuilder().setRequestId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request_id"); + + verify(stub, never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsSelectedReadbackSnapshotUuidOrDigestSubstitution() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var responseNumber = new AtomicInteger(); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + var response = selectedAssignmentResponse(request).toBuilder(); + return switch (responseNumber.getAndIncrement()) { + case 0 -> + response + .setSnapshot( + request.getExpectedSnapshot().toBuilder() + .setSnapshotUuid(ASSIGNMENT_UUID.toString())) + .build(); + default -> + response + .setSnapshot( + request.getExpectedSnapshot().toBuilder() + .setSnapshotDigest("a".repeat(64))) + .build(); + }; + }); + + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact roster snapshot UUID or digest"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact roster snapshot UUID or digest"); + } + + @Test + void rejectsChangedAssignmentCorrelationAccountActorAndCompleteTarget() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var responseNumber = new AtomicInteger(); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + var response = selectedAssignmentResponse(request).toBuilder(); + return switch (responseNumber.getAndIncrement()) { + case 0 -> response.setRequestUuid(UUID.randomUUID().toString()).build(); + case 1 -> response.setCanonicalAccountUuid(TENANT_UUID.toString()).build(); + case 2 -> response.setSelectedCharacterUuid(SNAPSHOT_UUID.toString()).build(); + default -> + response + .setTarget(request.getExpectedTarget().toBuilder().setPointerVersion(99L)) + .build(); + }; + }); + + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request correlation"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("canonical account UUID"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("selected character UUID"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + } + + @Test + void rejectsUnknownFieldsAndMissingSelectedAssignmentFields() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var unknown = + UnknownFieldSet.newBuilder() + .addField(101, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setUnknownFields(unknown) + .build(); + }); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unknown fields"); + + var transportFailure = + Status.FAILED_PRECONDITION.withDescription("roster snapshot changed").asRuntimeException(); + doThrow(transportFailure).when(stub).readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isSameAs(transportFailure); + + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder().clearTarget().build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder().clearSnapshot().build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("response snapshot is absent"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + var unknownSnapshot = + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.snapshotUuid().toString()) + .setSnapshotDigest(roster.snapshotDigest()) + .setUnknownFields(unknown) + .build(); + return selectedAssignmentResponse(request).toBuilder() + .setSnapshot(unknownSnapshot) + .build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("response snapshot is absent or malformed"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setTarget(request.getExpectedTarget().toBuilder().setUnknownFields(unknown)) + .build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + } + + @Test + void rejectsNilOrMalformedAssignmentReferenceAndIntentDigest() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + + for (String assignmentUuid : + List.of( + "00000000-0000-0000-0000-000000000000", + "BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB", + "not-an-assignment-uuid")) { + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = + invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setAssignmentUuid(assignmentUuid) + .build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("assignment_uuid"); + } + + for (String intentDigest : List.of("", "C".repeat(64), "sha256:" + "c".repeat(64))) { + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = + invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setIntentDigest(intentDigest) + .build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("intent_digest"); + } + } + + @Test + void rejectsAbsentOrDuplicateSelectedActorInRosterInput() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var absentRoster = + rosterWithActors( + roster, + List.of( + new CanonicalGameplayRosterClient.RosterActor( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), "Other Pilot"))); + var duplicateRoster = + rosterWithActors( + roster, + List.of( + new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"), + new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"))); + + assertThatThrownBy( + () -> client.readSelectedPreseededAssignment(absentRoster, selectedContext())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exactly once"); + assertThatThrownBy( + () -> client.readSelectedPreseededAssignment(duplicateRoster, selectedContext())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate actor"); + verify(stub, never()).readSelectedPreseededAssignment(any()); + } + + @Test + void refusesSelectedAssignmentReadInsideTransactionOrSynchronization() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + + try { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + verify(stub, never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsNilAccountBeforeClientUseAndRequiresWorkloadMtls() { + var factory = mock(GrpcChannelFactory.class); + var uninitialized = newClientWithoutStub(factory); + assertThatThrownBy( + () -> + uninitialized.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setAccountId(new UUID(0L, 0L).toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil"); + verifyNoInteractions(factory); + + var plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), plaintext, factory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), mtlsProperties(), factory, "invalid.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(factory); + } + + @Test + void rejectsResponsesFromOtherEntityWorkloadIdentity() throws Exception { + ManagedChannel channel = mock(ManagedChannel.class); + SSLSession sslSession = mock(SSLSession.class); + X509Certificate peerCertificate = mock(X509Certificate.class); + when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] {peerCertificate}); + when(peerCertificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/other/sa/entity-management-service"))); + Attributes attributes = + Attributes.newBuilder().set(io.grpc.Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build(); + @SuppressWarnings("unchecked") + ClientCall call = + mock(ClientCall.class); + when(call.getAttributes()).thenReturn(attributes); + doAnswer( + invocation -> { + @SuppressWarnings("unchecked") + ClientCall.Listener listener = + invocation.getArgument(0); + listener.onMessage(CanonicalGameplayRosterResponse.getDefaultInstance()); + listener.onClose(Status.OK, new Metadata()); + return null; + }) + .when(call) + .start(any(), any()); + when(channel.newCall( + any(), any())) + .thenReturn(call); + + var client = newClientWithChannel(channel); + assertThatThrownBy(() -> client.listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + } + + private static PlayerExecutionContext listContext() { + return playerExecutionContext(LIST_REQUEST_UUID, ""); + } + + private static PlayerExecutionContext selectedContext() { + return playerExecutionContext(SELECT_REQUEST_UUID, ACTOR_UUID.toString()); + } + + private static PlayerExecutionContext playerExecutionContext( + UUID requestUuid, String characterId) { + CanonicalPlayableTarget route = publishedRoute().route(); + return PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT_UUID.toString()) + .setTenantId(route.canonicalTenantId().toString()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setGameInstanceId(route.canonicalGameInstanceId().toString()) + .setCharacterId(characterId) + .setSessionId(SESSION_UUID.toString()) + .setRealmId(route.realmId().toString()) + .setRequestId(requestUuid.toString()) + .setPlayableStateScope(route.playableStateScope()) + .build(); + } + + private static CanonicalPublishedPlayerRoute publishedRoute() { + var fixture = + PublishedRealmPolicyEvidenceFixture.fixture( + PublishedRealmPolicyEvidenceFixture.policy("main", true, true, "SHARED")); + var policySet = fixture.set(); + PublishedRealmEntryPolicyEvidence selected = policySet.policies().getFirst(); + var route = + new CanonicalPlayableTarget( + NAMESPACE, + "tenant-key", + TENANT_UUID, + "earth", + "Earth", + uuid("22222222-2222-4222-8222-222222222222"), + "main", + "main", + 101L, + 202L, + uuid("33333333-3333-4333-8333-333333333333"), + "SHARED", + uuid("44444444-4444-4444-8444-444444444444"), + fixture.target().canonicalVersionId(), + 303L, + 1L, + 7L, + "d".repeat(64), + 82L, + "first-open-operation-17", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + uuid("99999999-9999-4999-8999-999999999999"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "sha256:" + "c".repeat(64), + 27L, + "sha256:" + "f".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.parse("2026-10-07T00:00:00Z"), + "ALLOW_NEW"); + return new CanonicalPublishedPlayerRoute(route, policySet, selected); + } + + private static net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor actor( + UUID characterUuid, String displayName) { + return net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(characterUuid.toString()) + .setDisplayName(displayName) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build(); + } + + private static CanonicalGameplayRosterClient.PreseededRosterSnapshot validatedRoster( + CanonicalGameplayRosterClient client, + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) { + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of(ACTOR_UUID.toString(), "Pilot One"))) + .addActors(actor(ACTOR_UUID, "Pilot One")) + .build(); + }); + return client.listPreseededRoster(publishedRoute(), listContext()); + } + + private static CanonicalGameplayRosterSelectedAssignmentResponse selectedAssignmentResponse( + CanonicalGameplayRosterSelectedAssignmentRequest request) { + return CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshot(request.getExpectedSnapshot()) + .setAssignmentUuid(ASSIGNMENT_UUID.toString()) + .setIntentDigest("c".repeat(64)) + .build(); + } + + private static CanonicalGameplayRosterClient.PreseededRosterSnapshot rosterWithActors( + CanonicalGameplayRosterClient.PreseededRosterSnapshot source, + List actors) + throws Exception { + List digestEntries = new ArrayList<>(actors.size() * 2); + for (var actor : actors) { + digestEntries.add(actor.characterUuid().toString()); + digestEntries.add(actor.displayName()); + } + return new CanonicalGameplayRosterClient.PreseededRosterSnapshot( + source.canonicalAccountUuid(), + source.snapshotUuid(), + snapshotDigest(source.canonicalAccountUuid(), source.target(), digestEntries), + source.target(), + actors); + } + + private static String snapshotDigest( + UUID accountUuid, + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget target, + List actors) + throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + for (String value : + List.of( + "firemud.entity.canonical-gameplay-roster.v3", + accountUuid.toString(), + target.getTenantUuid(), + target.getRealmUuid(), + target.getWorldSlug(), + target.getRealmSlug(), + target.getGameInstanceUuid(), + Long.toString(target.getCatalogRevision()), + Long.toString(target.getPointerVersion()), + Long.toString(target.getActiveWorldEpoch()), + target.getCanonicalVersionUuid(), + target.getPublishedPolicyDigest(), + target.getPublishedReleaseBundleRef(), + target.getAdmissionPointerSnapshotDigest(), + target.getPublishedOwnerProofDigest(), + target.getPlayableStateNamespaceUuid(), + target.getPlayableStateScope().name(), + "PRESEEDED_ONLY", + Integer.toString(actors.size() / 2))) { + write(output, value); + } + for (String actorValue : actors) { + write(output, actorValue); + } + } + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } + + private static void write(DataOutputStream output, String value) throws Exception { + byte[] encoded = value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } + + private static CanonicalGameplayRosterClient newClient( + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static CanonicalGameplayRosterClient newClientWithChannel(ManagedChannel channel) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + var buildStub = + CanonicalGameplayRosterClient.class.getDeclaredMethod("buildStub", ManagedChannel.class); + buildStub.setAccessible(true); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, buildStub.invoke(client, channel)); + return client; + } + + private static CanonicalGameplayRosterClient newClientWithoutStub(GrpcChannelFactory factory) { + return new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), mtlsProperties(), factory, NAMESPACE); + } + + private static CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub + mockStub() { + var stub = + mock(CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static CommonGrpcClientProperties mtlsProperties() { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/entity-management-ca.crt"); + return tls; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java new file mode 100644 index 0000000000..9df3bf5565 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import org.junit.jupiter.api.Test; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class GameDesignPublishedRealmPolicyClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("55555555-5555-4555-8555-555555555551"); + + @Test + void returnsCompleteTypedEvidenceAndSendsExactRequestWithDeadline() throws Exception { + var evidence = evidence(); + var stub = mockStub(); + when(stub.listPublishedRealmEntryPolicies(any())) + .thenAnswer( + invocation -> { + var request = + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + invocation.getArgument(0, ListPublishedRealmEntryPoliciesRequest.class)); + return PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); + }); + var client = newClient(stub); + + PublishedRealmEntryPolicySetEvidence result = + client.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID); + + assertThat(result).isEqualTo(evidence); + assertThat(result.hasValidDigest()).isTrue(); + assertThat(result.policies()).hasSize(2); + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(ListPublishedRealmEntryPoliciesRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).listPublishedRealmEntryPolicies(requestCaptor.capture()); + var exactRequest = requestCaptor.getValue(); + assertThat(exactRequest.getSchemaVersion()).isEqualTo(1); + assertThat(exactRequest.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(UUID.fromString(exactRequest.getReadRequestId()).toString()) + .isEqualTo(exactRequest.getReadRequestId()); + assertThat(exactRequest.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(exactRequest.getCanonicalVersionId()).isEqualTo(VERSION_ID.toString()); + } + + @Test + void rejectsMalformedCanonicalTenantOrVersionBeforeStubUse() { + var channelFactory = mock(GrpcChannelFactory.class); + var client = newClientWithoutStub(channelFactory); + + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(null, VERSION_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(TENANT_ID, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(new UUID(0L, 0L), VERSION_ID)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsUninitializedClientAndPropagatesUnavailableOwner() throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var uninitialized = newClientWithoutStub(channelFactory); + assertThatThrownBy(() -> uninitialized.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(GameDesignPublishedRealmPolicyClient.UninitializedClientException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + + var stub = mockStub(); + StatusRuntimeException unavailable = + Status.UNAVAILABLE.withDescription("Game Design unavailable").asRuntimeException(); + when(stub.listPublishedRealmEntryPolicies(any())).thenThrow(unavailable); + var client = newClient(stub); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isSameAs(unavailable); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsChangedRequestUnknownFieldsAndMalformedClosedEvidence() throws Exception { + var expectedEvidence = evidence(); + var stub = mockStub(); + when(stub.listPublishedRealmEntryPolicies(any())) + .thenAnswer( + invocation -> { + ListPublishedRealmEntryPoliciesRequest request = invocation.getArgument(0); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest( + request.toBuilder().setCanonicalVersionId(TENANT_ID.toString()).build()) + .setPolicySetEvidence(ByteString.copyFrom(expectedEvidence.canonicalBytes())) + .build(); + }); + assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(GameDesignPublishedRealmPolicyClient.InvalidResponseException.class) + .hasMessageContaining("response is invalid"); + + doAnswer( + invocation -> { + var request = (ListPublishedRealmEntryPoliciesRequest) invocation.getArgument(0); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(request) + .setPolicySetEvidence(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + }) + .when(stub) + .listPublishedRealmEntryPolicies(any()); + assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(GameDesignPublishedRealmPolicyClient.InvalidResponseException.class); + + doAnswer( + invocation -> { + var request = (ListPublishedRealmEntryPoliciesRequest) invocation.getArgument(0); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(request) + .setPolicySetEvidence(ByteString.copyFrom(expectedEvidence.canonicalBytes())) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + }) + .when(stub) + .listPublishedRealmEntryPolicies(any()); + assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(GameDesignPublishedRealmPolicyClient.InvalidResponseException.class); + } + + @Test + void rejectsResponseFromDifferentMtlsWorkloadNamespace() throws Exception { + ManagedChannel channel = mock(ManagedChannel.class); + SSLSession sslSession = mock(SSLSession.class); + X509Certificate peerCertificate = mock(X509Certificate.class); + when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] {peerCertificate}); + when(peerCertificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/other/sa/game-design-service"))); + Attributes attributes = + Attributes.newBuilder().set(io.grpc.Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build(); + @SuppressWarnings("unchecked") + ClientCall + call = mock(ClientCall.class); + when(call.getAttributes()).thenReturn(attributes); + doAnswer( + invocation -> { + @SuppressWarnings("unchecked") + ClientCall.Listener listener = + invocation.getArgument(0); + var request = + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(UUID.randomUUID().toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setCanonicalVersionId(VERSION_ID.toString()) + .build()); + listener.onMessage( + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence())); + listener.onClose(Status.OK, new Metadata()); + return null; + }) + .when(call) + .start(any(), any()); + when(channel + . + newCall(any(), any())) + .thenReturn(call); + + var client = newClientWithChannel(channel); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + } + + @Test + void rejectsPlaintextIncompleteClasspathTlsAndInvalidNamespaceBeforeChannelCreation() { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + var classpath = mtlsProperties(); + classpath.setPrivateKey("classpath:certs/client.key"); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(channelFactory); + } + + private static PublishedRealmEntryPolicySetEvidence evidence() { + return PublishedRealmPolicyEvidenceFixture.fixture( + PublishedRealmPolicyEvidenceFixture.policy("main", true, true, "SHARED"), + PublishedRealmPolicyEvidenceFixture.policy("playtest", true, false, "ISOLATED")) + .set(); + } + + private static GameDesignPublishedRealmPolicyClient newClient( + PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub stub) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static GameDesignPublishedRealmPolicyClient newClientWithChannel(ManagedChannel channel) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + var buildStub = + GameDesignPublishedRealmPolicyClient.class.getDeclaredMethod( + "buildStub", ManagedChannel.class); + buildStub.setAccessible(true); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, buildStub.invoke(client, channel)); + return client; + } + + private static GameDesignPublishedRealmPolicyClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + } + + private static PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + mockStub() { + var stub = + mock( + PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + .class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static CommonGrpcClientProperties mtlsProperties() { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/game-design-ca.crt"); + return tls; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelectionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelectionTest.java new file mode 100644 index 0000000000..4810b7c5b2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelectionTest.java @@ -0,0 +1,135 @@ +package net.firedevops.firemud.gamesession.command.text; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import org.junit.jupiter.api.Test; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayActorSelectionTest { + private static final UUID ACCOUNT_UUID = + PublishedRealmPolicyEvidenceFixture.uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID FIRST_ACTOR_UUID = + PublishedRealmPolicyEvidenceFixture.uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID SECOND_ACTOR_UUID = + PublishedRealmPolicyEvidenceFixture.uuid("99999999-9999-4999-8999-999999999999"); + + @Test + void automaticallySelectsTheOnlyActorAndCarriesItsExactSnapshotBinding() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"))); + var validated = + CanonicalGameplayActorSelection.validate(snapshot, ACCOUNT_UUID, route).orElseThrow(); + + var selection = CanonicalGameplayActorSelection.select(validated, null); + + assertThat(selection) + .isInstanceOfSatisfying( + CanonicalGameplayActorSelection.Selected.class, + selected -> { + assertThat(selected.characterUuid()).isEqualTo(FIRST_ACTOR_UUID); + assertThat(selected.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(selected.rosterSnapshotUuid()).isEqualTo(snapshot.snapshotUuid()); + assertThat(selected.rosterSnapshotDigest()).isEqualTo(snapshot.snapshotDigest()); + assertThat(selected.target()).isEqualTo(snapshot.target()); + assertThat(selected.ordinal()).isEqualTo(1); + }); + } + + @Test + void deniesZeroActorsAndRequiresAnOrdinalForMultipleActors() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var emptySnapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot(route, ACCOUNT_UUID, List.of()); + var emptyRoster = + CanonicalGameplayActorSelection.validate(emptySnapshot, ACCOUNT_UUID, route).orElseThrow(); + assertThat(CanonicalGameplayActorSelection.select(emptyRoster, null)) + .isEqualTo( + new CanonicalGameplayActorSelection.Denied( + CanonicalGameplayActorSelection.Denial.NO_PRESEEDED_ACTOR)); + + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of( + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"), + new CanonicalGameplayRosterClient.RosterActor(SECOND_ACTOR_UUID, "Pilot Two"))); + var roster = + CanonicalGameplayActorSelection.validate(snapshot, ACCOUNT_UUID, route).orElseThrow(); + assertThat(CanonicalGameplayActorSelection.select(roster, null)) + .isEqualTo( + new CanonicalGameplayActorSelection.SelectionRequired( + List.of( + new CanonicalGameplayActorSelection.Choice(1, "Pilot One"), + new CanonicalGameplayActorSelection.Choice(2, "Pilot Two")))); + assertThat(CanonicalGameplayActorSelection.select(roster, "2")) + .isInstanceOfSatisfying( + CanonicalGameplayActorSelection.Selected.class, + selected -> assertThat(selected.characterUuid()).isEqualTo(SECOND_ACTOR_UUID)); + } + + @Test + void rejectsUuidNameAndNonCanonicalOrdinalSelectors() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"))); + var roster = + CanonicalGameplayActorSelection.validate(snapshot, ACCOUNT_UUID, route).orElseThrow(); + + for (String selector : List.of(FIRST_ACTOR_UUID.toString(), "Pilot One", "01", "+1", "2")) { + assertThat(CanonicalGameplayActorSelection.select(roster, selector)) + .isInstanceOf(CanonicalGameplayActorSelection.Denied.class); + } + } + + @Test + void rejectsCrossAccountChangedTargetAndMalformedActors() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var actor = new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"); + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot(route, ACCOUNT_UUID, List.of(actor)); + + assertThat(CanonicalGameplayActorSelection.validate(snapshot, SECOND_ACTOR_UUID, route)) + .isEmpty(); + + CanonicalGameplayRosterTarget changedTarget = + snapshot.target().toBuilder() + .setPointerVersion(snapshot.target().getPointerVersion() + 1L) + .build(); + var changedSnapshot = + new CanonicalGameplayRosterClient.PreseededRosterSnapshot( + ACCOUNT_UUID, + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + changedTarget, + snapshot.actors()); + assertThat(CanonicalGameplayActorSelection.validate(changedSnapshot, ACCOUNT_UUID, route)) + .isEmpty(); + + var duplicateActorSnapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, ACCOUNT_UUID, List.of(actor, actor)); + assertThat( + CanonicalGameplayActorSelection.validate(duplicateActorSnapshot, ACCOUNT_UUID, route)) + .isEmpty(); + + var malformedNameSnapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, " Pilot "))); + assertThat(CanonicalGameplayActorSelection.validate(malformedNameSnapshot, ACCOUNT_UUID, route)) + .isEmpty(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java new file mode 100644 index 0000000000..9b4d1bf107 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java @@ -0,0 +1,171 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.config.CanonicalPlayerRouteReadConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class CanonicalPlayerRouteReadConfigurationTest { + @Test + void defaultConfigurationLeavesCanonicalRosterRouteSourceUnregistered() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); + }); + } + + @Test + void explicitlyDisabledConfigurationLeavesCanonicalRosterRouteSourceUnregistered() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .withPropertyValues("firemud.canonical-gameplay-roster-owner-read.enabled=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); + }); + } + + // Composition proof only: repositories and the channel are controlled doubles; no owner read or + // database read is performed. The client-level test owns RPC identity and deadline proof. + @Test + void enabledConfigurationComposesRealRouteSourcesWithFileBackedTlsAndExactTarget( + @TempDir Path directory) throws IOException { + Path clientCertificate = Files.createFile(directory.resolve("game-session-client.crt")); + Path clientKey = Files.createFile(directory.resolve("game-session-client.key")); + Path serverCa = Files.createFile(directory.resolve("game-design-ca.crt")); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.test:7654"); + var tlsProperties = new CommonGrpcClientProperties(); + tlsProperties.setCertChain(clientCertificate.toString()); + tlsProperties.setPrivateKey(clientKey.toString()); + tlsProperties.setCaCert(serverCa.toString()); + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + anyString(), anyInt(), any(CommonGrpcClientProperties.class), anyBoolean())) + .thenReturn(channel); + + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .withBean(ServiceEndpointsProperties.class, () -> endpoints) + .withBean(CommonGrpcClientProperties.class, () -> tlsProperties) + .withBean(GrpcChannelFactory.class, () -> channelFactory) + .withBean( + CanonicalGameplayRosterClient.class, () -> mock(CanonicalGameplayRosterClient.class)) + .withBean( + GameSessionCanonicalRealmCatalogRepository.class, + () -> mock(GameSessionCanonicalRealmCatalogRepository.class)) + .withBean( + CanonicalInitialAdmissionRepository.class, + () -> mock(CanonicalInitialAdmissionRepository.class)) + .withBean( + CanonicalGameInstanceLaunchAssociationRepository.class, + () -> mock(CanonicalGameInstanceLaunchAssociationRepository.class)) + .withPropertyValues( + "firemud.canonical-gameplay-roster-owner-read.enabled=true", + "firemud.grpc.workload-namespace=games") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).hasSingleBean(CanonicalPlayerRouteReadService.class); + assertThat(context).hasSingleBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).hasSingleBean(CanonicalGameplayRosterSelectionService.class); + assertThat( + Mockito.mockingDetails( + context.getBean(GameDesignPublishedRealmPolicyClient.class)) + .isMock()) + .isFalse(); + assertThat( + Mockito.mockingDetails(context.getBean(CanonicalPlayerRouteReadService.class)) + .isMock()) + .isFalse(); + assertThat( + Mockito.mockingDetails( + context.getBean(CanonicalPublishedPlayerRouteReadService.class)) + .isMock()) + .isFalse(); + verify(channelFactory) + .buildChannel(eq("game-design.test:7654"), eq(6565), eq(tlsProperties), eq(true)); + verifyNoInteractions( + context.getBean(GameSessionCanonicalRealmCatalogRepository.class), + context.getBean(CanonicalInitialAdmissionRepository.class), + context.getBean(CanonicalGameInstanceLaunchAssociationRepository.class)); + }); + } + + @Test + void enabledConfigurationRejectsInvalidNamespaceBeforeOpeningChannel(@TempDir Path directory) + throws IOException { + Path clientCertificate = Files.createFile(directory.resolve("game-session-client.crt")); + Path clientKey = Files.createFile(directory.resolve("game-session-client.key")); + Path serverCa = Files.createFile(directory.resolve("game-design-ca.crt")); + var tlsProperties = new CommonGrpcClientProperties(); + tlsProperties.setCertChain(clientCertificate.toString()); + tlsProperties.setPrivateKey(clientKey.toString()); + tlsProperties.setCaCert(serverCa.toString()); + var channelFactory = mock(GrpcChannelFactory.class); + + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .withBean(ServiceEndpointsProperties.class, ServiceEndpointsProperties::new) + .withBean(CommonGrpcClientProperties.class, () -> tlsProperties) + .withBean(GrpcChannelFactory.class, () -> channelFactory) + .withBean( + CanonicalGameplayRosterClient.class, () -> mock(CanonicalGameplayRosterClient.class)) + .withBean( + GameSessionCanonicalRealmCatalogRepository.class, + () -> mock(GameSessionCanonicalRealmCatalogRepository.class)) + .withBean( + CanonicalInitialAdmissionRepository.class, + () -> mock(CanonicalInitialAdmissionRepository.class)) + .withBean( + CanonicalGameInstanceLaunchAssociationRepository.class, + () -> mock(CanonicalGameInstanceLaunchAssociationRepository.class)) + .withPropertyValues( + "firemud.canonical-gameplay-roster-owner-read.enabled=true", + "firemud.grpc.workload-namespace=games.invalid") + .run( + context -> { + assertThat(context).hasFailed(); + verifyNoInteractions(channelFactory); + }); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java index 87790d4fc6..8ee230ea6a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java @@ -1,68 +1,205 @@ -package net.firedevops.firemud.gamesession.dto; +package unit.net.firedevops.firemud.gamesession.dto; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.service.impl.DefaultDeniedCanonicalInitialAdmissionWorldVerifier; import org.junit.jupiter.api.Test; class CanonicalInitialAdmissionRequestTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void gameSessionRequestDigestIsBareAndWorldBindingDigestRemainsDistinct() { + CanonicalInitialAdmissionRequest request = noPriorRequest(); + + assertThat(request.requestDigest()).matches("[0-9a-f]{64}").doesNotStartWith("sha256:"); + assertThat(request.holdBindingDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(request.holdBindingDigest()).isNotEqualTo("sha256:" + request.requestDigest()); + assertThat(request.canonicalVersionId()).isEqualTo(CANONICAL_VERSION); + } + @Test - void initialAdmissionRequestIdMatches128CharacterOwnerAndIntentBounds() { - for (int length : new int[] {120, 121, 128}) { - request("r".repeat(length)); - } + void requestIdentityAccepts121And128CodePointsAndRejects129() { + assertThat(requestWithId("r".repeat(121)).initialAdmissionRequestId()).hasSize(121); + assertThat(requestWithId("r".repeat(128)).initialAdmissionRequestId()).hasSize(128); - assertThatThrownBy(() -> request("r".repeat(129))) + assertThatThrownBy(() -> requestWithId("r".repeat(129))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("initialAdmissionRequestId must contain 1..128 characters"); + .hasMessageContaining("1..128 characters"); } - private static CanonicalInitialAdmissionRequest request(String requestId) { - String targetNamespace = "firemud-prod"; - UUID tenantId = UUID.randomUUID(); - String worldSlug = "world"; - UUID realmId = UUID.randomUUID(); - UUID playableStateNamespaceId = UUID.randomUUID(); - String playableStateScope = "SHARED"; - UUID gameInstanceId = UUID.randomUUID(); - UUID versionId = UUID.randomUUID(); - long lifecycleEpoch = 1L; - long catalogRevision = 1L; - CanonicalInitialAdmissionRequest.OriginKind originKind = - CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER; - String requestDigest = + @Test + void requestIdentityLimitCountsUnicodeCodePoints() { + String requestId = "😀".repeat(128); + + assertThat(requestId).hasSize(256); + assertThat(requestWithId(requestId).initialAdmissionRequestId()).isEqualTo(requestId); + assertThatThrownBy(() -> requestWithId("😀".repeat(129))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("1..128 characters"); + } + + @Test + void bothOriginsRequireTheirExactPriorPointerShape() { + assertThatThrownBy( + () -> + new CanonicalInitialAdmissionRequest( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.NO_PRIOR_POINTER, + 13L, + "gs-initial-admission-17", + noPriorRequest().requestDigest(), + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not carry"); + + assertThatThrownBy( + () -> + new CanonicalInitialAdmissionRequest( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.EXPECT_CLOSED, + null, + "gs-initial-admission-17", + noPriorRequest().requestDigest(), + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires a positive"); + } + + @Test + void worldProofMustMatchCanonicalVersionOriginCatalogAndHoldBinding() { + CanonicalInitialAdmissionRequest request = noPriorRequest(); + CanonicalInitialAdmissionWorldProof proof = + new CanonicalInitialAdmissionWorldProof( + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + "ACTIVE", + request.activeLifecycleEpoch(), + request.originKind(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + + proof.requireMatches(request); + assertThatThrownBy( + () -> + new CanonicalInitialAdmissionWorldProof( + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.targetNamespace(), + proof.canonicalTenantId(), + proof.worldSlug(), + proof.realmId(), + proof.playableStateNamespaceId(), + proof.playableStateScope(), + proof.canonicalGameInstanceId(), + uuid("66666666-6666-4666-8666-666666666666"), + proof.lifecycleState(), + proof.activeLifecycleEpoch(), + proof.originKind(), + proof.expectedCatalogRevision(), + proof.expectedPriorPointerVersion(), + proof.holdId(), + proof.holdFence(), + proof.holdBindingDigest()) + .requireMatches(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + } + + @Test + void unauthenticatedDefaultWorldVerifierNeverTreatsCallerTupleAsOwnerProof() { + assertThatThrownBy( + () -> + new DefaultDeniedCanonicalInitialAdmissionWorldVerifier().verify(noPriorRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("denied until authenticated World"); + } + + private static CanonicalInitialAdmissionRequest noPriorRequest() { + return requestWithId("gs-initial-admission-17"); + } + + private static CanonicalInitialAdmissionRequest requestWithId(String requestId) { + String digest = CanonicalInitialAdmissionRequest.computeRequestDigest( - targetNamespace, - tenantId, - worldSlug, - realmId, - playableStateNamespaceId, - playableStateScope, - gameInstanceId, - versionId, - lifecycleEpoch, - catalogRevision, - originKind, + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.NO_PRIOR_POINTER, null, requestId); - return new CanonicalInitialAdmissionRequest( - targetNamespace, - tenantId, - worldSlug, - realmId, - playableStateNamespaceId, - playableStateScope, - gameInstanceId, - versionId, - lifecycleEpoch, - catalogRevision, - originKind, + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.NO_PRIOR_POINTER, null, requestId, - requestDigest, - UUID.randomUUID(), - UUID.randomUUID(), - "sha256:" + "a".repeat(64)); + digest, + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java new file mode 100644 index 0000000000..08f92fe291 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java @@ -0,0 +1,325 @@ +package unit.net.firedevops.firemud.gamesession.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayInputStream; +import java.nio.file.Path; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Comparator; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.FileSystemResource; + +/** + * Exercises the configured JWT and TLS-peer gRPC interceptors around the Entity-only owner read. + */ +class CanonicalGameplayRosterOwnerReadInterceptorChainTest { + private static final String NAMESPACE = "gameplay"; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final String METHOD = + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetCanonicalGameplayRosterOwnerReadMethod() + .getFullMethodName(); + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void exactEntityCertificatePassesJwtBypassAndAbsentSourceRemainsUnavailable() { + var provider = sourceReaderProvider(); + var response = new CapturingObserver(); + + invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter(provider), request(), response); + + assertThat(response.errorWasStatusRuntimeException).isTrue(); + assertThat(response.errorCode).isEqualTo(Status.Code.UNAVAILABLE); + verify(provider).getIfAvailable(); + } + + @Test + void absentWrongServiceCrossNamespaceAndPlayerCallerContextAreDenied() { + var provider = sourceReaderProvider(); + var adapter = adapter(provider); + + var absent = new CapturingObserver(); + invokeThroughConfiguredChain(null, adapter, request(), absent); + assertPermissionDenied(absent); + + var wrongService = new CapturingObserver(); + invokeThroughConfiguredChain( + peerIdentity(NAMESPACE, "game-session-service"), adapter, request(), wrongService); + assertPermissionDenied(wrongService); + + var otherNamespace = new CapturingObserver(); + invokeThroughConfiguredChain(entityIdentity("other"), adapter, request(), otherNamespace); + assertPermissionDenied(otherNamespace); + + var callerContext = new CapturingObserver(); + invokeThroughConfiguredChain( + entityIdentity(NAMESPACE), adapter, request(), callerContext, true); + assertPermissionDenied(callerContext); + + verifyNoInteractions(provider); + } + + private static ObjectProvider sourceReaderProvider() { + @SuppressWarnings("unchecked") + ObjectProvider provider = mock(ObjectProvider.class); + when(provider.getIfAvailable()).thenReturn(null); + return provider; + } + + private static CanonicalGameplayRosterOwnerReadGrpcAdapter adapter( + ObjectProvider provider) { + return new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + } + + private static AuthTokenInterceptor configuredAuthInterceptor() { + Properties properties = applicationProperties(); + List configured = publicMethods(properties); + assertThat(configured) + .containsExactly( + "game_session.v1.GameSessionService/Ping", + METHOD, + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead", + "game_session.v1.GameSessionService/AuthorizeStartSession") + .doesNotContain("game_session.v1.*"); + Set publicMethods = Set.copyOf(configured); + return new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), publicMethods); + } + + private static List publicMethods(Properties properties) { + List indexes = + properties.stringPropertyNames().stream() + .filter(name -> name.startsWith("firemud.auth.grpc.public-methods[")) + .map(name -> name.substring(name.indexOf('[') + 1, name.indexOf(']'))) + .map(Integer::parseInt) + .sorted(Comparator.naturalOrder()) + .toList(); + return indexes.stream() + .map(index -> properties.getProperty("firemud.auth.grpc.public-methods[" + index + "]")) + .toList(); + } + + private static Properties applicationProperties() { + var yaml = new YamlPropertiesFactoryBean(); + yaml.setResources(new FileSystemResource(Path.of("src/main/resources/application.yml"))); + Properties properties = yaml.getObject(); + if (properties == null) { + throw new IllegalStateException("Game Session application properties are unavailable"); + } + return properties; + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetCanonicalGameplayRosterOwnerReadRequest request, + CapturingObserver response) { + invokeThroughConfiguredChain(peerUri, adapter, request, response, false); + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetCanonicalGameplayRosterOwnerReadRequest request, + CapturingObserver response, + boolean authenticatedCallerContext) { + ServerCall call = new TestServerCall(METHOD, sslSession(peerUri)); + Metadata headers = new Metadata(); + ServerInterceptor peer = new GrpcPeerIdentityInterceptor(); + ServerCallHandler handler = + (nextCall, ignoredHeaders) -> { + adapter.getCanonicalGameplayRosterOwnerRead(request, response); + return new ServerCall.Listener<>() {}; + }; + configuredAuthInterceptor() + .interceptCall( + call, + headers, + (authCall, authHeaders) -> { + if (authenticatedCallerContext) { + SessionContext.setContext( + ACCOUNT.toString(), List.of("player"), java.util.Map.of()); + } + return peer.interceptCall(authCall, authHeaders, handler); + }); + } + + private static GetCanonicalGameplayRosterOwnerReadRequest request() { + return GetCanonicalGameplayRosterOwnerReadRequest.newBuilder() + .setSchemaVersion(1) + .setRequestUuid(uuid("66666666-6666-4666-8666-666666666666").toString()) + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantUuid(TENANT.toString()) + .setWorldSlug("earth") + .setRealmUuid(REALM.toString()) + .setRealmSlug("main") + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceUuid(INSTANCE.toString()) + .setCanonicalVersionUuid(VERSION.toString()) + .setExpectedCatalogRevision(71L) + .setExpectedPointerVersion(73L) + .setExpectedActiveWorldEpoch(82L) + .build(); + } + + private static String entityIdentity(String namespace) { + return peerIdentity(namespace, ENTITY_SERVICE); + } + + private static String peerIdentity(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static SSLSession sslSession(String peerUri) { + SSLSession session = mock(SSLSession.class); + if (peerUri == null) { + try { + when(session.getPeerCertificates()) + .thenThrow(new javax.net.ssl.SSLPeerUnverifiedException("No peer certificate")); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + X509Certificate certificate = mock(X509Certificate.class); + try { + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peerUri))); + } catch (java.security.cert.CertificateParsingException impossible) { + throw new IllegalStateException(impossible); + } + try { + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + + private static void assertPermissionDenied(CapturingObserver observer) { + assertThat(observer.errorWasStatusRuntimeException).isTrue(); + assertThat(observer.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class CapturingObserver + implements StreamObserver { + private boolean errorWasStatusRuntimeException; + private Status.Code errorCode; + + @Override + public void onNext(GetCanonicalGameplayRosterOwnerReadResponse response) {} + + @Override + public void onError(Throwable throwable) { + errorWasStatusRuntimeException = throwable instanceof StatusRuntimeException; + errorCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final class TestServerCall extends ServerCall { + private static final MethodDescriptor.Marshaller NOOP_MARSHALLER = + new MethodDescriptor.Marshaller<>() { + @Override + public java.io.InputStream stream(Object value) { + return new ByteArrayInputStream(new byte[0]); + } + + @Override + public Object parse(java.io.InputStream stream) { + return new Object(); + } + }; + + private final String fullMethodName; + private final Attributes attributes; + + private TestServerCall(String fullMethodName, SSLSession peerSession) { + this.fullMethodName = fullMethodName; + this.attributes = + peerSession == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, peerSession).build(); + } + + @Override + public void request(int numMessages) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(Object message) {} + + @Override + public void close(Status status, Metadata trailers) {} + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(NOOP_MARSHALLER) + .setResponseMarshaller(NOOP_MARSHALLER) + .build(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java new file mode 100644 index 0000000000..9d5bd453e3 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java @@ -0,0 +1,331 @@ +package unit.net.firedevops.firemud.gamesession.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayInputStream; +import java.nio.file.Path; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Comparator; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadGrpcCodec; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.FileSystemResource; + +/** Exercises the exact Entity-only assignment method through the configured JWT and TLS guards. */ +class PreseededActorAssignmentOwnerReadInterceptorChainTest { + private static final String NAMESPACE = "gameplay"; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final String METHOD = + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetPreseededActorAssignmentOwnerReadMethod() + .getFullMethodName(); + private static final UUID ASSIGNMENT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID ACCOUNT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_NAMESPACE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID INSTANCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION = uuid("66666666-6666-4666-8666-666666666666"); + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void exactEntityCertificatePassesExactJwtBypassAndReachesOwnerSource() { + var provider = sourceReaderProvider(); + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + var typedRequest = PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(request()); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrentForAssignment(typedRequest)) + .thenThrow( + new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "source unavailable")); + var response = new CapturingObserver(); + + invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter(provider), request(), response); + + assertThat(response.errorWasStatusRuntimeException).isTrue(); + assertThat(response.errorCode).isEqualTo(Status.Code.UNAVAILABLE); + verify(provider).getIfAvailable(); + verify(source).readCurrentForAssignment(typedRequest); + } + + @Test + void absentWrongServiceCrossNamespaceAndCallerContextAreDeniedBeforeSourceRead() { + var provider = sourceReaderProvider(); + var adapter = adapter(provider); + + var absentCertificate = new CapturingObserver(); + invokeThroughConfiguredChain(null, adapter, request(), absentCertificate); + assertPermissionDenied(absentCertificate); + + var wrongService = new CapturingObserver(); + invokeThroughConfiguredChain( + peerIdentity(NAMESPACE, "game-session-service"), adapter, request(), wrongService); + assertPermissionDenied(wrongService); + + var otherNamespace = new CapturingObserver(); + invokeThroughConfiguredChain(entityIdentity("other"), adapter, request(), otherNamespace); + assertPermissionDenied(otherNamespace); + + var callerContext = new CapturingObserver(); + invokeThroughConfiguredChain( + entityIdentity(NAMESPACE), adapter, request(), callerContext, true); + assertPermissionDenied(callerContext); + + verifyNoInteractions(provider); + } + + private static ObjectProvider sourceReaderProvider() { + @SuppressWarnings("unchecked") + ObjectProvider provider = mock(ObjectProvider.class); + return provider; + } + + private static CanonicalGameplayRosterOwnerReadGrpcAdapter adapter( + ObjectProvider provider) { + return new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + } + + private static AuthTokenInterceptor configuredAuthInterceptor() { + List configured = publicMethods(applicationProperties()); + assertThat(configured) + .containsExactly( + "game_session.v1.GameSessionService/Ping", + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", + METHOD, + "game_session.v1.GameSessionService/AuthorizeStartSession") + .doesNotContain("game_session.v1.*"); + Set publicMethods = Set.copyOf(configured); + return new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), publicMethods); + } + + private static List publicMethods(Properties properties) { + List indexes = + properties.stringPropertyNames().stream() + .filter(name -> name.startsWith("firemud.auth.grpc.public-methods[")) + .map(name -> name.substring(name.indexOf('[') + 1, name.indexOf(']'))) + .map(Integer::parseInt) + .sorted(Comparator.naturalOrder()) + .toList(); + return indexes.stream() + .map(index -> properties.getProperty("firemud.auth.grpc.public-methods[" + index + "]")) + .toList(); + } + + private static Properties applicationProperties() { + var yaml = new YamlPropertiesFactoryBean(); + yaml.setResources(new FileSystemResource(Path.of("src/main/resources/application.yml"))); + Properties properties = yaml.getObject(); + if (properties == null) { + throw new IllegalStateException("Game Session application properties are unavailable"); + } + return properties; + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetPreseededActorAssignmentOwnerReadRequest request, + CapturingObserver response) { + invokeThroughConfiguredChain(peerUri, adapter, request, response, false); + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetPreseededActorAssignmentOwnerReadRequest request, + CapturingObserver response, + boolean authenticatedCallerContext) { + ServerCall call = new TestServerCall(METHOD, sslSession(peerUri)); + Metadata headers = new Metadata(); + ServerInterceptor peer = new GrpcPeerIdentityInterceptor(); + ServerCallHandler handler = + (nextCall, ignoredHeaders) -> { + adapter.getPreseededActorAssignmentOwnerRead(request, response); + return new ServerCall.Listener<>() {}; + }; + configuredAuthInterceptor() + .interceptCall( + call, + headers, + (authCall, authHeaders) -> { + if (authenticatedCallerContext) { + SessionContext.setContext( + ACCOUNT.toString(), List.of("player"), java.util.Map.of()); + } + return peer.interceptCall(authCall, authHeaders, handler); + }); + } + + private static GetPreseededActorAssignmentOwnerReadRequest request() { + return GetPreseededActorAssignmentOwnerReadRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(ASSIGNMENT.toString()) + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantUuid(TENANT.toString()) + .setWorldSlug("earth") + .setRealmUuid(REALM.toString()) + .setRealmSlug("main") + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceUuid(INSTANCE.toString()) + .setCanonicalVersionUuid(VERSION.toString()) + .setExpectedCatalogRevision(71L) + .setExpectedPolicyDigest("a".repeat(64)) + .setExpectedPublishedReleaseBundleRef("release:fixture") + .build(); + } + + private static String entityIdentity(String namespace) { + return peerIdentity(namespace, ENTITY_SERVICE); + } + + private static String peerIdentity(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static SSLSession sslSession(String peerUri) { + SSLSession session = mock(SSLSession.class); + if (peerUri == null) { + try { + when(session.getPeerCertificates()) + .thenThrow(new javax.net.ssl.SSLPeerUnverifiedException("No peer certificate")); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + X509Certificate certificate = mock(X509Certificate.class); + try { + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peerUri))); + } catch (java.security.cert.CertificateParsingException impossible) { + throw new IllegalStateException(impossible); + } + try { + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + + private static void assertPermissionDenied(CapturingObserver observer) { + assertThat(observer.errorWasStatusRuntimeException).isTrue(); + assertThat(observer.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class CapturingObserver + implements StreamObserver { + private boolean errorWasStatusRuntimeException; + private Status.Code errorCode; + + @Override + public void onNext(GetPreseededActorAssignmentOwnerReadResponse response) {} + + @Override + public void onError(Throwable throwable) { + errorWasStatusRuntimeException = throwable instanceof StatusRuntimeException; + errorCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final class TestServerCall extends ServerCall { + private static final MethodDescriptor.Marshaller NOOP_MARSHALLER = + new MethodDescriptor.Marshaller<>() { + @Override + public java.io.InputStream stream(Object value) { + return new ByteArrayInputStream(new byte[0]); + } + + @Override + public Object parse(java.io.InputStream stream) { + return new Object(); + } + }; + + private final String fullMethodName; + private final Attributes attributes; + + private TestServerCall(String fullMethodName, SSLSession peerSession) { + this.fullMethodName = fullMethodName; + this.attributes = + peerSession == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, peerSession).build(); + } + + @Override + public void request(int numMessages) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(Object message) {} + + @Override + public void close(Status status, Metadata trailers) {} + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(NOOP_MARSHALLER) + .setResponseMarshaller(NOOP_MARSHALLER) + .build(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java new file mode 100644 index 0000000000..f3205c1ed1 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -0,0 +1,1000 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.command.text.CanonicalGameplayActorSelection; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayRosterSelectionServiceTest { + private static final UUID ACCOUNT = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID FIRST_ACTOR = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID SECOND_ACTOR = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID SNAPSHOT = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID CHANGED_SNAPSHOT = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID ASSIGNMENT = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void returnsMenuForMultipleActorsThenReadsOnlyTheSelectedOrdinalOwnerReference() + throws Exception { + var harness = harness(twoActors()); + + var menu = + harness + .service() + .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); + + assertThat(menu).isInstanceOf(CanonicalGameplayRosterSelectionService.SelectionRequired.class); + var requiredMenu = (CanonicalGameplayRosterSelectionService.SelectionRequired) menu; + assertThat(requiredMenu.choices()) + .isEqualTo( + List.of( + new CanonicalGameplayActorSelection.Choice(1, "Pilot One"), + new CanonicalGameplayActorSelection.Choice(2, "Pilot Two"))); + assertThat(requiredMenu.menuIdentity().snapshotUuid()).isEqualTo(SNAPSHOT); + assertThat(requiredMenu.menuIdentity().snapshotDigest()).matches("[0-9a-f]{64}"); + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + + PlayerExecutionContext input = context(harness.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"); + var selected = harness.service().select(input, "2", requiredMenu.menuIdentity()); + + assertThat(selected) + .isInstanceOfSatisfying( + CanonicalGameplayRosterSelectionService.SelectedOwnerReference.class, + result -> { + assertThat(result.displayName()).isEqualTo("Pilot Two"); + assertThat(result.ordinal()).isEqualTo(2); + assertThat(result.ownerReference().canonicalAccountUuid()).isEqualTo(ACCOUNT); + assertThat(result.ownerReference().selectedCharacterUuid()).isEqualTo(SECOND_ACTOR); + assertThat(result.ownerReference().assignmentOperationId()).isEqualTo(ASSIGNMENT); + assertThat(result.ownerReference().rosterSnapshotUuid()).isEqualTo(SNAPSHOT); + }); + + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(CanonicalGameplayRosterSelectedAssignmentRequest.class); + verify(harness.stub()).readSelectedPreseededAssignment(requestCaptor.capture()); + PlayerExecutionContext selectedContext = requestCaptor.getValue().getPlayerExecutionContext(); + assertThat(selectedContext.getRequestId()).isNotEqualTo(input.getRequestId()); + assertThat(selectedContext.getAccountId()).isEqualTo(input.getAccountId()); + assertThat(selectedContext.getSessionId()).isEqualTo(input.getSessionId()); + assertThat(selectedContext.getTenantId()).isEqualTo(input.getTenantId()); + assertThat(selectedContext.getRealmId()).isEqualTo(input.getRealmId()); + assertThat(selectedContext.getPlayableStateNamespaceId()) + .isEqualTo(input.getPlayableStateNamespaceId()); + assertThat(selectedContext.getPlayableStateScope()).isEqualTo(input.getPlayableStateScope()); + assertThat(selectedContext.getGameInstanceId()).isEqualTo(input.getGameInstanceId()); + assertThat(selectedContext.getCharacterId()).isEqualTo(SECOND_ACTOR.toString()); + assertThat(requestCaptor.getValue().getSelectedCharacterUuid()) + .isEqualTo(SECOND_ACTOR.toString()); + assertThat(requestCaptor.getValue().getExpectedSnapshot().getSnapshotDigest()) + .isEqualTo(requiredMenu.menuIdentity().snapshotDigest()); + + verify(harness.catalogRepository(), atLeastOnce()) + .readUniqueVisiblePublicProduction("test", harness.route().canonicalTenantId()); + verify(harness.admissionRepository(), atLeastOnce()) + .readCurrentOpenSnapshotForRealm( + "test", harness.route().canonicalTenantId(), harness.route().realmId()); + verify(harness.launchRepository(), atLeastOnce()) + .readForInitialAdmission( + "test", + harness.route().canonicalTenantId(), + harness.route().realmId(), + harness.route().canonicalGameInstanceId()); + verify(harness.policyClient(), atLeastOnce()) + .listPublishedRealmEntryPolicies( + harness.route().canonicalTenantId(), harness.route().canonicalVersionId()); + verify(harness.stub(), atLeastOnce()).listPreseededRoster(any()); + verify(harness.stub(), atLeastOnce()).withDeadlineAfter(5L, TimeUnit.SECONDS); + verifyNoMoreInteractions( + harness.catalogRepository(), + harness.admissionRepository(), + harness.launchRepository(), + harness.policyClient(), + harness.stub()); + } + + @Test + void deniesTenantNamespaceRealmAndInstanceContextMismatchesBeforeEntityRead() throws Exception { + var harness = harness(oneActor()); + PlayerExecutionContext valid = context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + UUID foreignTenant = uuid("13131313-1313-4313-8313-131313131313"); + var mainTenantCatalog = + harness + .catalogRepository() + .readUniqueVisiblePublicProduction( + harness.route().targetNamespace(), harness.route().canonicalTenantId()); + // Deliberately return the valid main-tenant owner row for a foreign-tenant query. + when(harness + .catalogRepository() + .readUniqueVisiblePublicProduction(harness.route().targetNamespace(), foreignTenant)) + .thenReturn(mainTenantCatalog); + + assertDenied( + harness + .service() + .select(valid.toBuilder().setTenantId(foreignTenant.toString()).build(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + + assertDenied( + harness + .service() + .select( + valid.toBuilder() + .setPlayableStateNamespaceId( + uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + assertDenied( + harness + .service() + .select( + valid.toBuilder() + .setGameInstanceId(uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + assertDenied( + harness + .service() + .select( + valid.toBuilder() + .setRealmId(uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + + verify(harness.stub(), never()).listPreseededRoster(any()); + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsAnEntitySnapshotWithAnotherAccountOrTargetBeforeSelectedRead() throws Exception { + var accountMismatch = harness(oneActor()); + doAnswer( + invocation -> + rosterResponse( + invocation.getArgument(0), + uuid("12121212-1212-4212-8212-121212121212"), + oneActor())) + .when(accountMismatch.stub()) + .listPreseededRoster(any()); + + assertDenied( + accountMismatch + .service() + .select( + context(accountMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + verify(accountMismatch.stub(), never()).readSelectedPreseededAssignment(any()); + + var targetMismatch = harness(oneActor()); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + CanonicalGameplayRosterTarget changedTarget = + request.getExpectedTarget().toBuilder() + .setGameInstanceUuid(uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(); + return rosterResponse(request, ACCOUNT, changedTarget, oneActor()); + }) + .when(targetMismatch.stub()) + .listPreseededRoster(any()); + + assertDenied( + targetMismatch + .service() + .select( + context(targetMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + verify(targetMismatch.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void returnsExplicitSelectionAndSelectorDenialsWithoutAssignmentReads() throws Exception { + var multiple = harness(twoActors()); + var menu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + multiple + .service() + .select( + context(multiple.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); + assertDenied( + multiple + .service() + .select( + context(multiple.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "Pilot Two", + menu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.INVALID_SELECTOR); + assertDenied( + multiple + .service() + .select( + context(multiple.route(), "abababab-abab-4bab-8bab-abababababab"), + "3", + menu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.SELECTOR_OUT_OF_RANGE); + verify(multiple.stub(), never()).readSelectedPreseededAssignment(any()); + + var empty = harness(List.of()); + assertDenied( + empty + .service() + .select(context(empty.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.NO_PRESEEDED_ACTOR); + verify(empty.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void requiresASelectionMenuIdentityForValidExplicitOrdinals() throws Exception { + var harness = harness(twoActors()); + var menu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + harness + .service() + .select( + context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); + + assertDenied( + harness + .service() + .select(context(harness.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), "2", null), + CanonicalGameplayRosterSelectionService.Denial.MISSING_MENU_IDENTITY); + assertDenied( + harness + .service() + .select( + context(harness.route(), "abababab-abab-4bab-8bab-abababababab"), + "2", + new CanonicalGameplayRosterSelectionService.SelectionMenuIdentity( + menu.menuIdentity().snapshotUuid(), "0".repeat(64))), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsChangedMenuSnapshotUuidAndReorderedRosterBeforeAssignmentRead() throws Exception { + var changedUuid = harness(twoActors()); + AtomicInteger changedUuidReads = new AtomicInteger(); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + UUID snapshotUuid = + changedUuidReads.getAndIncrement() == 0 ? SNAPSHOT : CHANGED_SNAPSHOT; + return rosterResponse( + request, ACCOUNT, request.getExpectedTarget(), twoActors(), snapshotUuid); + }) + .when(changedUuid.stub()) + .listPreseededRoster(any()); + var uuidMenu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + changedUuid + .service() + .select( + context(changedUuid.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null); + assertDenied( + changedUuid + .service() + .select( + context(changedUuid.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "1", + uuidMenu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + verify(changedUuid.stub(), never()).readSelectedPreseededAssignment(any()); + + var reorderedRoster = harness(twoActors()); + AtomicInteger reorderedReads = new AtomicInteger(); + List reorderedActors = + List.of( + new CanonicalGameplayRosterClient.RosterActor(SECOND_ACTOR, "Pilot Two"), + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One")); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + List actors = + reorderedReads.getAndIncrement() == 0 ? twoActors() : reorderedActors; + return rosterResponse( + request, ACCOUNT, request.getExpectedTarget(), actors, SNAPSHOT); + }) + .when(reorderedRoster.stub()) + .listPreseededRoster(any()); + var reorderedMenu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + reorderedRoster + .service() + .select( + context(reorderedRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null); + assertDenied( + reorderedRoster + .service() + .select( + context(reorderedRoster.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "1", + reorderedMenu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + verify(reorderedRoster.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void staleMenuIdentityPrecedesOrdinalResolutionAgainstARefreshedSmallerRoster() throws Exception { + var harness = harness(twoActors()); + AtomicInteger reads = new AtomicInteger(); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + boolean firstRead = reads.getAndIncrement() == 0; + return rosterResponse( + request, + ACCOUNT, + request.getExpectedTarget(), + firstRead + ? twoActors() + : List.of( + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One")), + firstRead ? SNAPSHOT : CHANGED_SNAPSHOT); + }) + .when(harness.stub()) + .listPreseededRoster(any()); + + var menu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + harness + .service() + .select( + context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); + assertDenied( + harness + .service() + .select( + context(harness.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "2", + menu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsMovedRouteAfterRosterAndAfterAssignmentNetworkEvidence() throws Exception { + var changedAfterList = harness(oneActor()); + configureRouteMovement(changedAfterList, 3); + assertDenied( + changedAfterList + .service() + .select( + context(changedAfterList.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + verify(changedAfterList.stub(), never()).readSelectedPreseededAssignment(any()); + + var changedAfterAssignment = harness(oneActor()); + configureRouteMovement(changedAfterAssignment, 5); + assertDenied( + changedAfterAssignment + .service() + .select( + context(changedAfterAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + verify(changedAfterAssignment.stub()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsChangedAssignmentSnapshotAndUnavailableEntityBackend() throws Exception { + var changedSnapshot = harness(oneActor()); + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return assignmentResponse(request, true); + }) + .when(changedSnapshot.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + changedSnapshot + .service() + .select( + context(changedSnapshot.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); + + var unavailable = harness(oneActor()); + doThrow(Status.UNAVAILABLE.withDescription("Entity offline").asRuntimeException()) + .when(unavailable.stub()) + .listPreseededRoster(any()); + assertDenied( + unavailable + .service() + .select( + context(unavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); + verify(unavailable.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void mapsEntityGrpcFailuresByStatusAndReadBoundary() throws Exception { + for (Status.Code code : + List.of( + Status.Code.UNAVAILABLE, + Status.Code.DEADLINE_EXCEEDED, + Status.Code.RESOURCE_EXHAUSTED, + Status.Code.ABORTED)) { + var rosterUnavailable = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("Entity read failed").asRuntimeException()) + .when(rosterUnavailable.stub()) + .listPreseededRoster(any()); + assertDenied( + rosterUnavailable + .service() + .select( + context(rosterUnavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); + + var assignmentUnavailable = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("Entity read failed").asRuntimeException()) + .when(assignmentUnavailable.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + assignmentUnavailable + .service() + .select( + context(assignmentUnavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ASSIGNMENT_UNAVAILABLE); + } + + var staleRouteOrPolicy = harness(oneActor()); + doThrow( + Status.FAILED_PRECONDITION + .withDescription("route changed or policy is no longer PRESEEDED_ONLY") + .asRuntimeException()) + .when(staleRouteOrPolicy.stub()) + .listPreseededRoster(any()); + assertDenied( + staleRouteOrPolicy + .service() + .select( + context(staleRouteOrPolicy.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + + var changedAssignment = harness(oneActor()); + doThrow( + Status.FAILED_PRECONDITION + .withDescription("snapshot changed or selected actor is absent") + .asRuntimeException()) + .when(changedAssignment.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + changedAssignment + .service() + .select( + context(changedAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + + var changedAssignmentWithMenu = harness(twoActors()); + doThrow( + Status.FAILED_PRECONDITION + .withDescription("snapshot changed or selected actor is absent") + .asRuntimeException()) + .when(changedAssignmentWithMenu.stub()) + .readSelectedPreseededAssignment(any()); + var menuResult = + changedAssignmentWithMenu + .service() + .select( + context(changedAssignmentWithMenu.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null); + assertThat(menuResult) + .isInstanceOf(CanonicalGameplayRosterSelectionService.SelectionRequired.class); + var menuIdentity = + ((CanonicalGameplayRosterSelectionService.SelectionRequired) menuResult).menuIdentity(); + assertDenied( + changedAssignmentWithMenu + .service() + .select( + context(changedAssignmentWithMenu.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "1", + menuIdentity), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + + for (Status.Code code : List.of(Status.Code.PERMISSION_DENIED, Status.Code.INVALID_ARGUMENT)) { + var invalidRoster = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("roster rejected").asRuntimeException()) + .when(invalidRoster.stub()) + .listPreseededRoster(any()); + assertDenied( + invalidRoster + .service() + .select( + context(invalidRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + + var invalidAssignment = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("assignment rejected").asRuntimeException()) + .when(invalidAssignment.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + invalidAssignment + .service() + .select( + context(invalidAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); + } + + var staleRoute = harness(oneActor()); + doThrow(Status.FAILED_PRECONDITION.withDescription("route changed").asRuntimeException()) + .when(staleRoute.policyClient()) + .listPublishedRealmEntryPolicies( + staleRoute.route().canonicalTenantId(), staleRoute.route().canonicalVersionId()); + assertDenied( + staleRoute + .service() + .select( + context(staleRoute.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + + var invalidRoute = harness(oneActor()); + doThrow(Status.PERMISSION_DENIED.withDescription("route rejected").asRuntimeException()) + .when(invalidRoute.policyClient()) + .listPublishedRealmEntryPolicies( + invalidRoute.route().canonicalTenantId(), invalidRoute.route().canonicalVersionId()); + assertDenied( + invalidRoute + .service() + .select( + context(invalidRoute.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROUTE_PROOF); + } + + @Test + void deniesAmbientTransactionBeforeAnyRouteOrOwnerRead() throws Exception { + var harness = harness(oneActor()); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertDenied( + harness + .service() + .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.AMBIENT_TRANSACTION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions( + harness.catalogRepository(), + harness.admissionRepository(), + harness.launchRepository(), + harness.policyClient(), + harness.stub()); + } + + private static TestHarness harness(List actors) + throws Exception { + CanonicalPublishedPlayerRoute published = + PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + CanonicalPlayableTarget route = published.route(); + PublishedRealmEntryPolicySetEvidence policySet = published.policySetEvidence(); + TargetProof policyTarget = policySet.target(); + + UUID sourceRegistrationRequest = uuid("abababab-abab-4bab-8bab-abababababab"); + UUID sourceOperation = uuid("acacacac-acac-4cac-8cac-acacacacacac"); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + route.targetNamespace(), + sourceRegistrationRequest, + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.worldDisplayName()); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + route.targetNamespace(), + sourceRegistrationRequest, + sourceOperation, + sourceRequestDigest, + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.worldDisplayName(), + policyTarget.sourceGameRowId(), + policyTarget.sourceGameTenantKey(), + policyTarget.sourceProvenanceKind()); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + route.targetNamespace(), + sourceRegistrationRequest, + sourceOperation, + sourceRequestDigest, + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.worldDisplayName(), + policyTarget.sourceGameRowId(), + policyTarget.sourceGameTenantKey(), + policyTarget.sourceProvenanceKind(), + sourceEvidenceDigest); + IntakeReceipt receipt = mock(IntakeReceipt.class); + when(receipt.source()).thenReturn(source); + CanonicalRealmCatalogSnapshot catalog = + new CanonicalRealmCatalogSnapshot( + route.targetNamespace(), + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.realmId(), + route.realmSlug(), + route.realmDisplayName(), + true, + true, + route.playableStateScope(), + route.playableStateNamespaceId(), + route.characterCreationPolicy(), + route.catalogRevision(), + uuid("adadadad-adad-4dad-8dad-adadadadadad"), + "a".repeat(64), + "sha256:" + "b".repeat(64), + receipt); + + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readUniqueVisiblePublicProduction( + route.targetNamespace(), route.canonicalTenantId())) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm( + route.targetNamespace(), route.canonicalTenantId(), route.realmId())) + .thenReturn(currentOpenSnapshot(route)); + + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + var binding = mock(CompleteLaunchBindingEvidence.class); + when(binding.descriptor()).thenReturn(descriptor); + when(binding.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(route.targetNamespace()); + when(descriptor.canonicalTenantId()).thenReturn(route.canonicalTenantId()); + when(descriptor.worldSlug()).thenReturn(route.worldSlug()); + when(descriptor.authoredWorldSourceOperationId()).thenReturn(sourceOperation); + when(descriptor.authoredWorldSourceEvidenceDigest()).thenReturn(sourceEvidenceDigest); + when(descriptor.versionId()).thenReturn(route.runtimeVersionId()); + when(descriptor.versionStateEpoch()).thenReturn(policySet.publicationVersionStateEpoch()); + when(descriptor.publishedReleaseBundleRef()).thenReturn(policySet.publishedReleaseBundleRef()); + when(descriptor.controlPlaneRequestId()).thenReturn("launch-request"); + when(descriptor.launchDescriptorId()).thenReturn("launch-descriptor"); + when(release.targetNamespace()).thenReturn(route.targetNamespace()); + when(release.canonicalTenantId()).thenReturn(route.canonicalTenantId()); + when(release.canonicalVersionId()).thenReturn(route.canonicalVersionId()); + when(release.worldSlug()).thenReturn(route.worldSlug()); + when(release.authoredWorldSourceOperationId()).thenReturn(sourceOperation); + when(release.authoredWorldSourceEvidenceDigest()).thenReturn(sourceEvidenceDigest); + when(release.publishedReleaseBundleRef()).thenReturn(policySet.publishedReleaseBundleRef()); + when(release.versionStateEpoch()).thenReturn(policySet.publicationVersionStateEpoch()); + when(release.commitId()).thenReturn(policySet.sourceCommitId().toString()); + when(release.publishWorkflowId()).thenReturn(policySet.publishWorkflowId()); + when(release.manifestHash()).thenReturn(policySet.manifestHash()); + + CanonicalGameInstanceLaunchAssociation association = + mock(CanonicalGameInstanceLaunchAssociation.class); + when(association.targetNamespace()).thenReturn(route.targetNamespace()); + when(association.gameSessionTenantId()).thenReturn(route.gameSessionTenantId()); + when(association.tenantAssociationOperationId()) + .thenReturn(uuid("aeaeaeae-aeae-4eae-8eae-aeaeaeaeaeae")); + when(association.canonicalTenantId()).thenReturn(route.canonicalTenantId()); + when(association.gameInstanceUuid()).thenReturn(route.canonicalGameInstanceId()); + when(association.worldSlug()).thenReturn(route.worldSlug()); + when(association.playableStateNamespaceId()).thenReturn(route.playableStateNamespaceId()); + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(association.publicProduction()).thenReturn(true); + when(association.controlPlaneRequestId()).thenReturn("launch-request"); + when(association.launchDescriptorId()).thenReturn("launch-descriptor"); + when(association.capturedStartingRowVersion()).thenReturn(1L); + when(association.currentRowVersion()).thenReturn(2L); + when(association.launchBindingEvidence()).thenReturn(binding); + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + CanonicalInitialAdmissionLaunchTarget launch = + mock(CanonicalInitialAdmissionLaunchTarget.class); + when(launch.association()).thenReturn(association); + when(launch.realmId()).thenReturn(route.realmId()); + when(launch.gameInstanceId()).thenReturn(route.gameInstanceId()); + when(launch.runtimeVersionId()).thenReturn(route.runtimeVersionId()); + when(launch.canonicalVersionId()).thenReturn(route.canonicalVersionId()); + when(launchRepository.readForInitialAdmission( + route.targetNamespace(), + route.canonicalTenantId(), + route.realmId(), + route.canonicalGameInstanceId())) + .thenReturn(Optional.of(launch)); + + var routeReader = + new CanonicalPlayerRouteReadService( + route.targetNamespace(), catalogRepository, admissionRepository, launchRepository); + var policyClient = mock(GameDesignPublishedRealmPolicyClient.class); + when(policyClient.listPublishedRealmEntryPolicies( + route.canonicalTenantId(), route.canonicalVersionId())) + .thenReturn(policySet); + var publishedRouteReader = + new CanonicalPublishedPlayerRouteReadService( + route.targetNamespace(), + routeReader, + catalogRepository, + launchRepository, + policyClient); + + var stub = + mock(CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.listPreseededRoster(any())) + .thenAnswer(invocation -> rosterResponse(invocation.getArgument(0), ACCOUNT, actors)); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer(invocation -> assignmentResponse(invocation.getArgument(0), false)); + CanonicalGameplayRosterClient rosterClient = rosterClient(stub); + var service = + new CanonicalGameplayRosterSelectionService( + routeReader, publishedRouteReader, rosterClient); + return new TestHarness( + service, + route, + catalogRepository, + admissionRepository, + launchRepository, + policyClient, + stub); + } + + private static void configureRouteMovement(TestHarness harness, int initialReadCount) { + CanonicalInitialAdmissionOwnerProof initialProof = proof(harness.route(), 7L); + CanonicalInitialAdmissionOwnerProof changedProof = proof(harness.route(), 8L); + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot initial = + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot( + initialProof, harness.route().admissionPointerSnapshotDigest()); + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot changed = + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(changedProof, "e".repeat(64)); + AtomicInteger reads = new AtomicInteger(); + when(harness + .admissionRepository() + .readCurrentOpenSnapshotForRealm( + harness.route().targetNamespace(), + harness.route().canonicalTenantId(), + harness.route().realmId())) + .thenAnswer(invocation -> reads.incrementAndGet() <= initialReadCount ? initial : changed); + } + + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentOpenSnapshot( + CanonicalPlayableTarget route) { + return new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot( + proof(route, route.pointerVersion()), route.admissionPointerSnapshotDigest()); + } + + private static CanonicalInitialAdmissionOwnerProof proof( + CanonicalPlayableTarget route, long pointerVersion) { + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + route.initialAdmissionRequestId(), + route.initialAdmissionRequestDigest(), + route.targetNamespace(), + route.canonicalTenantId(), + route.worldSlug(), + route.realmId(), + route.playableStateNamespaceId(), + route.playableStateScope(), + route.canonicalGameInstanceId(), + route.canonicalVersionId(), + route.activeWorldEpoch(), + route.catalogRevision(), + route.initialAdmissionOriginKind(), + route.expectedPriorPointerVersion(), + route.holdId(), + route.holdFence(), + route.holdBindingDigest(), + pointerVersion, + route.auditEventId(), + route.ownerProofDigest(), + false, + route.ownerProofTerminalAt()); + } + + private static CanonicalGameplayRosterResponse rosterResponse( + CanonicalGameplayRosterRequest request, + UUID account, + List actors) + throws Exception { + return rosterResponse(request, account, request.getExpectedTarget(), actors, SNAPSHOT); + } + + private static CanonicalGameplayRosterResponse rosterResponse( + CanonicalGameplayRosterRequest request, + UUID account, + CanonicalGameplayRosterTarget target, + List actors) + throws Exception { + return rosterResponse(request, account, target, actors, SNAPSHOT); + } + + private static CanonicalGameplayRosterResponse rosterResponse( + CanonicalGameplayRosterRequest request, + UUID account, + CanonicalGameplayRosterTarget target, + List actors, + UUID snapshotUuid) + throws Exception { + Method calculateDigest = + CanonicalGameplayRosterClient.class.getDeclaredMethod( + "calculateSnapshotDigest", UUID.class, CanonicalGameplayRosterTarget.class, List.class); + calculateDigest.setAccessible(true); + String digest = (String) calculateDigest.invoke(null, account, target, actors); + var builder = + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(account.toString()) + .setTarget(target) + .setSnapshotUuid(snapshotUuid.toString()) + .setSnapshotDigest(digest); + for (CanonicalGameplayRosterClient.RosterActor actor : actors) { + builder.addActors( + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(actor.characterUuid().toString()) + .setDisplayName(actor.displayName()) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER)); + } + return builder.build(); + } + + private static CanonicalGameplayRosterSelectedAssignmentResponse assignmentResponse( + CanonicalGameplayRosterSelectedAssignmentRequest request, boolean changedSnapshot) { + CanonicalGameplayRosterSelectedAssignmentResponse.Builder response = + CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshot(request.getExpectedSnapshot()) + .setAssignmentUuid(ASSIGNMENT.toString()) + .setIntentDigest("c".repeat(64)); + if (changedSnapshot) { + response.setSnapshot( + request.getExpectedSnapshot().toBuilder() + .setSnapshotUuid(uuid("12121212-1212-4212-8212-121212121212").toString())); + } + return response.build(); + } + + private static CanonicalGameplayRosterClient rosterClient( + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("game-session-client.crt"); + tls.setPrivateKey("game-session-client.key"); + tls.setCaCert("entity-management-ca.crt"); + var client = + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "test"); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static PlayerExecutionContext context(CanonicalPlayableTarget route, String requestId) { + return PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT.toString()) + .setTenantId(route.canonicalTenantId().toString()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setGameInstanceId(route.canonicalGameInstanceId().toString()) + .setCharacterId("") + .setSessionId("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setRealmId(route.realmId().toString()) + .setRequestId(requestId) + .setPlayableStateScope(route.playableStateScope()) + .build(); + } + + private static List oneActor() { + return List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One")); + } + + private static List twoActors() { + return List.of( + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One"), + new CanonicalGameplayRosterClient.RosterActor(SECOND_ACTOR, "Pilot Two")); + } + + private static void assertDenied( + CanonicalGameplayRosterSelectionService.Result result, + CanonicalGameplayRosterSelectionService.Denial reason) { + assertThat(result).isEqualTo(new CanonicalGameplayRosterSelectionService.Denied(reason)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record TestHarness( + CanonicalGameplayRosterSelectionService service, + CanonicalPlayableTarget route, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalInitialAdmissionRepository admissionRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameDesignPublishedRealmPolicyClient policyClient, + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java new file mode 100644 index 0000000000..233be28ee5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java @@ -0,0 +1,517 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import org.junit.jupiter.api.Test; + +class CanonicalPlayerRouteReadServiceTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final String REQUEST_ID = "first-open-operation-17"; + + @Test + void composesCanonicalCatalogCurrentOpenProofAndOwnerQualifiedRuntimeReadOnly() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + CanonicalInitialAdmissionOwnerProof proof = committedProof(7L); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget(); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalog)); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(proof)); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + + CanonicalPlayableTarget target = service.readVisiblePublicProductionTargets().getFirst(); + + assertThat(target.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(target.canonicalTenantId()).isEqualTo(TENANT); + assertThat(target.realmId()).isEqualTo(REALM); + assertThat(target.playableStateNamespaceId()).isEqualTo(PLAYABLE_NAMESPACE); + assertThat(target.canonicalGameInstanceId()).isEqualTo(INSTANCE); + assertThat(target.canonicalVersionId()).isEqualTo(VERSION); + assertThat(target.runtimeVersionId()).isEqualTo(303L); + assertThat(target.catalogRevision()).isEqualTo(1L); + assertThat(target.pointerVersion()).isEqualTo(7L); + assertThat(target.admissionPointerSnapshotDigest()).isEqualTo("d".repeat(64)); + assertThat(target.activeWorldEpoch()).isEqualTo(82L); + assertThat(target.initialAdmissionRequestId()).isEqualTo(REQUEST_ID); + assertThat(target.initialAdmissionRequestDigest()).isEqualTo("a".repeat(64)); + assertThat(target.initialAdmissionOriginKind()).isEqualTo(OriginKind.NO_PRIOR_POINTER); + assertThat(target.expectedPriorPointerVersion()).isNull(); + assertThat(target.holdId()).isEqualTo(uuid("77777777-7777-4777-8777-777777777777")); + assertThat(target.holdFence()).isEqualTo(uuid("88888888-8888-4888-8888-888888888888")); + assertThat(target.holdBindingDigest()).isEqualTo("sha256:" + "c".repeat(64)); + assertThat(target.auditEventId()).isEqualTo(27L); + assertThat(target.ownerProofDigest()).isEqualTo("sha256:" + "f".repeat(64)); + assertThat(target.ownerProofOutcome()) + .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(target.positiveDurableAbort()).isFalse(); + assertThat(target.ownerProofTerminalAt()).isEqualTo(Instant.parse("2026-10-07T00:00:00Z")); + assertThat(target.gameSessionTenantId()).isEqualTo(101L); + assertThat(target.gameInstanceId()).isEqualTo(202L); + + assertThat(service.matchesCurrentTarget(target)).isTrue(); + verify(catalogRepository).readVisiblePublicProductionSnapshots(NAMESPACE); + verify(catalogRepository).readUniqueVisiblePublicProduction(NAMESPACE, TENANT); + verify(admissionRepository, times(2)).readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM); + verify(launchRepository, times(2)).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + verifyNoMoreInteractions(catalogRepository, admissionRepository, launchRepository); + } + + @Test + void readsCurrentTargetByCanonicalTenantSelectorWithoutCallerCounters() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var catalog = catalogSnapshot(); + var proof = committedProof(7L); + var launch = launchTarget(); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(proof)); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + CanonicalPlayableTarget current = service.readCurrentTarget(TENANT); + + assertThat(current.canonicalTenantId()).isEqualTo(TENANT); + assertThat(current.canonicalGameInstanceId()).isEqualTo(INSTANCE); + assertThat(current.canonicalVersionId()).isEqualTo(VERSION); + assertThat(current.catalogRevision()).isEqualTo(1L); + assertThat(current.pointerVersion()).isEqualTo(7L); + verify(catalogRepository).readUniqueVisiblePublicProduction(NAMESPACE, TENANT); + verify(admissionRepository).readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM); + verify(launchRepository).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + verifyNoMoreInteractions(catalogRepository, admissionRepository, launchRepository); + } + + @Test + void changedCurrentPointerFenceDoesNotMatchPreviouslyDiscoveredTarget() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalog)); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn( + currentOpenSnapshot(committedProof(7L), "d".repeat(64)), + currentOpenSnapshot(committedProof(8L), "e".repeat(64))); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget(); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + CanonicalPlayableTarget discovered = service.readVisiblePublicProductionTargets().getFirst(); + + assertThat(service.matchesCurrentTarget(discovered)).isFalse(); + } + + @Test + void changedPointerSnapshotDigestDoesNotMatchPreviouslyDiscoveredTarget() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + CanonicalInitialAdmissionOwnerProof proof = committedProof(7L); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalog)); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn( + currentOpenSnapshot(proof, "d".repeat(64)), currentOpenSnapshot(proof, "e".repeat(64))); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget(); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + CanonicalPlayableTarget discovered = service.readVisiblePublicProductionTargets().getFirst(); + + assertThat(service.matchesCurrentTarget(discovered)).isFalse(); + } + + @Test + void missingCurrentOpenOwnerProofFailsWithoutReadingLaunchAssociation() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenThrow(new IllegalStateException("No current OPEN owner proof")); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void abortedCurrentOwnerProofFailsWithoutReadingLaunchAssociation() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalInitialAdmissionOwnerProof proof = abortedProof(); + assertThat(proof.provesAbort()).isTrue(); + assertThat(proof.committedPointerVersion()).isNull(); + assertThat(proof.auditEventId()).isNull(); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenAnswer( + invocation -> + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, "d".repeat(64))); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void proofNamespaceMustMatchConfiguredOwnerNamespace() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L, "another-owner", 1L))); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void catalogNamespaceMustMatchConfiguredOwnerNamespace() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot("another-owner", 1L))); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void catalogRevisionMustMatchCommittedOwnerProof() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L, NAMESPACE, 2L))); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void launchAssociationMustMatchCanonicalTenantAndRealmTarget() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + CanonicalInitialAdmissionLaunchTarget launch = + launchTarget(NAMESPACE, uuid("99999999-9999-4999-8999-999999999999"), VERSION); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + } + + @Test + void launchAssociationNamespaceMustMatchConfiguredOwnerNamespace() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget("another-owner", TENANT, VERSION); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + } + + @Test + void launchVersionMustMatchCommittedOwnerProof() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + CanonicalInitialAdmissionLaunchTarget launch = + launchTarget(NAMESPACE, TENANT, uuid("99999999-9999-4999-8999-999999999999")); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + } + + @Test + void unavailableOwnerSourceFailsClosed() { + assertThatThrownBy( + CanonicalPlayerRouteReadService.unavailable()::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.ReadUnavailableException.class); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot() { + return catalogSnapshot(NAMESPACE, 1L); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot( + String targetNamespace, long catalogRevision) { + IntakeReceipt receipt = sourceReceipt(targetNamespace); + return new CanonicalRealmCatalogSnapshot( + targetNamespace, + TENANT, + "demo-tenant", + "demo-world", + REALM, + "production", + "Production Realm", + true, + true, + "SHARED", + PLAYABLE_NAMESPACE, + "ALLOW_NEW", + catalogRevision, + uuid("66666666-6666-4666-8666-666666666666"), + "a".repeat(64), + "sha256:" + "b".repeat(64), + receipt); + } + + private static CanonicalInitialAdmissionOwnerProof committedProof(long pointerVersion) { + return committedProof(pointerVersion, NAMESPACE, 1L); + } + + private static CanonicalInitialAdmissionOwnerProof committedProof( + long pointerVersion, String targetNamespace, long catalogRevision) { + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + REQUEST_ID, + "a".repeat(64), + targetNamespace, + TENANT, + "demo-world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + catalogRevision, + OriginKind.NO_PRIOR_POINTER, + null, + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + "sha256:" + "c".repeat(64), + pointerVersion, + 27L, + "sha256:" + "f".repeat(64), + false, + Instant.parse("2026-10-07T00:00:00Z")); + } + + private static CanonicalInitialAdmissionOwnerProof abortedProof() { + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + REQUEST_ID, + "a".repeat(64), + NAMESPACE, + TENANT, + "demo-world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + 1L, + OriginKind.NO_PRIOR_POINTER, + null, + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + "sha256:" + "c".repeat(64), + null, + null, + "sha256:" + "f".repeat(64), + true, + Instant.parse("2026-10-07T00:00:00Z")); + } + + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentOpenSnapshot( + CanonicalInitialAdmissionOwnerProof proof) { + return currentOpenSnapshot(proof, "d".repeat(64)); + } + + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentOpenSnapshot( + CanonicalInitialAdmissionOwnerProof proof, String digest) { + return new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, digest); + } + + private static CanonicalPlayerRouteReadService routeReadService( + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalInitialAdmissionRepository admissionRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository) { + return new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + } + + private static CanonicalInitialAdmissionLaunchTarget launchTarget() { + return launchTarget(NAMESPACE, TENANT, VERSION); + } + + private static CanonicalInitialAdmissionLaunchTarget launchTarget( + String targetNamespace, UUID canonicalTenantId, UUID canonicalVersionId) { + CanonicalGameInstanceLaunchAssociation association = + mock(CanonicalGameInstanceLaunchAssociation.class); + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + when(association.targetNamespace()).thenReturn(targetNamespace); + when(association.gameSessionTenantId()).thenReturn(101L); + when(association.canonicalTenantId()).thenReturn(canonicalTenantId); + when(association.worldSlug()).thenReturn("demo-world"); + when(association.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(association.publicProduction()).thenReturn(true); + when(association.gameInstanceUuid()).thenReturn(INSTANCE); + + CanonicalInitialAdmissionLaunchTarget launch = + mock(CanonicalInitialAdmissionLaunchTarget.class); + when(launch.association()).thenReturn(association); + when(launch.realmId()).thenReturn(REALM); + when(launch.gameInstanceId()).thenReturn(202L); + when(launch.runtimeVersionId()).thenReturn(303L); + when(launch.canonicalVersionId()).thenReturn(canonicalVersionId); + return launch; + } + + private static IntakeReceipt sourceReceipt(String targetNamespace) { + UUID intakeOperationId = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + UUID intakeRequestId = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID sourceRegistrationRequestId = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + UUID sourceOperationId = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + String tenantSlug = "demo-tenant"; + String worldSlug = "demo-world"; + String worldDisplayName = "Demo World"; + String sourceTenantKey = "game-design-tenant-42"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + sourceRegistrationRequestId, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + sourceRegistrationRequestId, + sourceOperationId, + sourceRequestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + sourceRegistrationRequestId, + sourceOperationId, + sourceRequestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + String receiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + intakeOperationId, intakeRequestDigest, source.evidenceDigest()); + return new IntakeReceipt( + intakeOperationId, intakeRequestId, intakeRequestDigest, source, receiptDigest); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java new file mode 100644 index 0000000000..eb1954d68b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java @@ -0,0 +1,445 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import org.junit.jupiter.api.Test; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalPublishedPlayerRouteReadServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID SOURCE_OPERATION = uuid("66666666-6666-4666-8666-666666666666"); + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void tenantSelectorOwnerReadRejectsEachChangedCanonicalCounterBeforeGameDesign() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(TENANT)).thenReturn(f.route()); + for (var deltas : + java.util.List.of( + new long[] {1L, 0L, 0L}, new long[] {0L, 1L, 0L}, new long[] {0L, 0L, 1L})) { + assertThatThrownBy( + () -> f.service().readCurrent(exactRequest(deltas[0], deltas[1], deltas[2]))) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + } + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void matchingCurrentRouteReadsAndReturnsCompleteOwnerPolicyEvidence() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(TENANT)).thenReturn(f.route()); + var policies = + PublishedRealmPolicyEvidenceFixture.fixture( + TENANT, + VERSION, + 19L, + 42L, + "game-design-tenant-42", + "NEW_GAME_ROW", + 3, + new PublishedRealmPolicyEvidenceFixture.PolicySpec( + "earth", "Earth", "main", "Main", true, true, "SHARED")); + when(f.release().commitId()).thenReturn(policies.set().sourceCommitId().toString()); + when(f.release().publishWorkflowId()).thenReturn(policies.set().publishWorkflowId()); + when(f.release().manifestHash()).thenReturn(policies.set().manifestHash()); + when(f.release().versionStateEpoch()).thenReturn(policies.set().publicationVersionStateEpoch()); + when(f.descriptor().versionStateEpoch()) + .thenReturn(policies.set().publicationVersionStateEpoch()); + when(f.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenReturn(policies.set()); + + CanonicalGameplayRosterOwnerReadEvidence result = + f.service().readCurrent(exactRequest(0L, 0L, 0L)); + + assertThat(result.publishedPolicySetEvidence()).isEqualTo(policies.set()); + verify(f.policyClient(), times(2)).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void tenantSelectorOwnerReadRejectsChangedTargetNamespaceBeforeOwnerRead() { + var f = fixture(); + var request = exactRequest(0L, 0L, 0L); + var changed = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + "another-owner", + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + request.expectedPointerVersion(), + request.expectedActiveWorldEpoch()); + + assertThatThrownBy(() -> f.service().readCurrent(changed)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.routeReader(), never()).readCurrentTarget(any(UUID.class)); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void assignmentSelectorReadDerivesRouteByTenantAndRejectsChangedSelectorBeforeGameDesign() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(TENANT)).thenReturn(f.route()); + var request = assignmentRequest(uuid("99999999-9999-4999-8999-999999999999")); + + assertThatThrownBy(() -> f.service().readCurrentForAssignment(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + + verify(f.routeReader()).readCurrentTarget(TENANT); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void staleRouteReturnsNoPolicyAndDoesNotContactGameDesign() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(f.route())) + .thenReturn(mock(CanonicalPlayableTarget.class)); + var service = f.service(); + + assertThatThrownBy(() -> service.readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void storageAndGameDesignTransportFailuresRemainDistinctAndReturnNoRoute() { + var storage = fixture(); + when(storage.routeReader().readCurrentTarget(storage.route())) + .thenThrow( + new CanonicalPlayerRouteReadService.ReadUnavailableException("database offline")); + assertThatThrownBy(() -> storage.service().readCurrent(storage.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class); + + var transport = fixture(); + when(transport.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow( + io.grpc.Status.UNAVAILABLE.withDescription("owner offline").asRuntimeException()); + assertThatThrownBy(() -> transport.service().readCurrent(transport.route())) + .isInstanceOf( + CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException.class); + } + + @Test + void classifiesGameDesignPolicyFailuresWithoutTreatingRejectedEvidenceAsUnavailable() { + for (io.grpc.Status.Code code : + java.util.List.of( + io.grpc.Status.Code.UNAVAILABLE, + io.grpc.Status.Code.DEADLINE_EXCEEDED, + io.grpc.Status.Code.RESOURCE_EXHAUSTED, + io.grpc.Status.Code.ABORTED)) { + var f = fixture(); + when(f.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow(io.grpc.Status.fromCode(code).asRuntimeException()); + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf( + CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException.class); + } + + var stale = fixture(); + when(stale.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow(io.grpc.Status.FAILED_PRECONDITION.asRuntimeException()); + assertThatThrownBy(() -> stale.service().readCurrent(stale.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + + for (io.grpc.Status.Code code : + java.util.List.of( + io.grpc.Status.Code.PERMISSION_DENIED, io.grpc.Status.Code.INVALID_ARGUMENT)) { + var rejected = fixture(); + when(rejected.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow(io.grpc.Status.fromCode(code).asRuntimeException()); + assertThatThrownBy(() -> rejected.service().readCurrent(rejected.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + } + + var uninitialized = fixture(); + when(uninitialized.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow( + new GameDesignPublishedRealmPolicyClient.UninitializedClientException( + "not initialized")); + assertThatThrownBy(() -> uninitialized.service().readCurrent(uninitialized.route())) + .isInstanceOf( + CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException.class); + + var invalidResponse = fixture(); + when(invalidResponse.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow( + new GameDesignPublishedRealmPolicyClient.InvalidResponseException( + "malformed response", new IllegalArgumentException("invalid evidence"))); + assertThatThrownBy(() -> invalidResponse.service().readCurrent(invalidResponse.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + } + + @Test + void missingCompleteGameDesignPolicySetFailsClosed() { + var f = fixture(); + + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.policyClient()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void changedCurrentSourceBindingFailsBeforePolicyRead() { + var f = fixture(); + when(f.source().operationId()).thenReturn(uuid("77777777-7777-4777-8777-777777777777")); + + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void changedCanonicalVersionFailsBeforePolicyRead() { + var f = fixture(); + when(f.release().canonicalVersionId()).thenReturn(uuid("99999999-9999-4999-8999-999999999999")); + + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + private static Fixture fixture() { + var routeReader = mock(CanonicalPlayerRouteReadService.class); + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var policyClient = mock(GameDesignPublishedRealmPolicyClient.class); + var route = mock(CanonicalPlayableTarget.class); + var catalog = mock(CanonicalRealmCatalogSnapshot.class); + var receipt = mock(IntakeReceipt.class); + var source = mock(AuthoredWorldSourceEvidence.class); + var launch = mock(CanonicalInitialAdmissionLaunchTarget.class); + var association = mock(CanonicalGameInstanceLaunchAssociation.class); + var completeBinding = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + + when(route.targetNamespace()).thenReturn(NAMESPACE); + when(route.canonicalTenantId()).thenReturn(TENANT); + when(route.worldSlug()).thenReturn("earth"); + when(route.realmId()).thenReturn(REALM); + when(route.realmSlug()).thenReturn("main"); + when(route.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(route.playableStateScope()).thenReturn("SHARED"); + when(route.canonicalGameInstanceId()).thenReturn(INSTANCE); + when(route.gameInstanceId()).thenReturn(202L); + when(route.runtimeVersionId()).thenReturn(303L); + when(route.canonicalVersionId()).thenReturn(VERSION); + when(route.catalogRevision()).thenReturn(1L); + when(route.pointerVersion()).thenReturn(1L); + when(route.admissionPointerSnapshotDigest()).thenReturn("d".repeat(64)); + when(route.activeWorldEpoch()).thenReturn(1L); + when(route.initialAdmissionRequestId()).thenReturn("first-open-operation-17"); + when(route.initialAdmissionRequestDigest()).thenReturn("a".repeat(64)); + when(route.initialAdmissionOriginKind()) + .thenReturn( + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind + .NO_PRIOR_POINTER); + when(route.expectedPriorPointerVersion()).thenReturn(null); + when(route.holdId()).thenReturn(uuid("99999999-9999-4999-8999-999999999999")); + when(route.holdFence()).thenReturn(uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + when(route.holdBindingDigest()).thenReturn(currentHoldRequest().holdBindingDigest()); + when(route.auditEventId()).thenReturn(27L); + when(route.ownerProofDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(route.ownerProofOutcome()) + .thenReturn( + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome + .COMMITTED); + when(route.positiveDurableAbort()).thenReturn(false); + when(route.ownerProofTerminalAt()).thenReturn(java.time.Instant.parse("2026-10-07T00:00:00Z")); + + when(catalog.targetNamespace()).thenReturn(NAMESPACE); + when(catalog.tenantId()).thenReturn(TENANT); + when(catalog.worldSlug()).thenReturn("earth"); + when(catalog.realmId()).thenReturn(REALM); + when(catalog.realmSlug()).thenReturn("main"); + when(catalog.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(catalog.visible()).thenReturn(true); + when(catalog.publicProduction()).thenReturn(true); + when(catalog.stateScope()).thenReturn("SHARED"); + when(catalog.sourceIntakeReceipt()).thenReturn(receipt); + when(receipt.source()).thenReturn(source); + when(source.targetNamespace()).thenReturn(NAMESPACE); + when(source.canonicalTenantId()).thenReturn(TENANT); + when(source.sourceGameRowId()).thenReturn(42L); + when(source.sourceGameTenantKey()).thenReturn("game-design-tenant-42"); + when(source.provenanceKind()).thenReturn("NEW_GAME_ROW"); + when(source.operationId()).thenReturn(SOURCE_OPERATION); + when(source.evidenceDigest()).thenReturn(SOURCE_DIGEST); + + when(launch.association()).thenReturn(association); + when(launch.realmId()).thenReturn(REALM); + when(launch.gameInstanceId()).thenReturn(202L); + when(launch.runtimeVersionId()).thenReturn(303L); + when(launch.canonicalVersionId()).thenReturn(VERSION); + when(association.targetNamespace()).thenReturn(NAMESPACE); + when(association.gameSessionTenantId()).thenReturn(101L); + when(association.tenantAssociationOperationId()) + .thenReturn(uuid("aeaeaeae-aeae-4eae-8eae-aeaeaeaeaeae")); + when(association.canonicalTenantId()).thenReturn(TENANT); + when(association.gameInstanceUuid()).thenReturn(INSTANCE); + when(association.worldSlug()).thenReturn("earth"); + when(association.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(association.publicProduction()).thenReturn(true); + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + when(association.controlPlaneRequestId()).thenReturn("launch-request"); + when(association.launchDescriptorId()).thenReturn("launch-descriptor"); + when(association.capturedStartingRowVersion()).thenReturn(1L); + when(association.currentRowVersion()).thenReturn(2L); + when(association.launchBindingEvidence()).thenReturn(completeBinding); + when(completeBinding.descriptor()).thenReturn(descriptor); + when(completeBinding.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(descriptor.canonicalTenantId()).thenReturn(TENANT); + when(descriptor.worldSlug()).thenReturn("earth"); + when(descriptor.authoredWorldSourceOperationId()).thenReturn(SOURCE_OPERATION); + when(descriptor.authoredWorldSourceEvidenceDigest()).thenReturn(SOURCE_DIGEST); + when(descriptor.versionId()).thenReturn(303L); + when(descriptor.versionStateEpoch()).thenReturn(7L); + when(descriptor.publishedReleaseBundleRef()).thenReturn("bundle:exact"); + when(descriptor.controlPlaneRequestId()).thenReturn("launch-request"); + when(descriptor.launchDescriptorId()).thenReturn("launch-descriptor"); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.canonicalTenantId()).thenReturn(TENANT); + when(release.canonicalVersionId()).thenReturn(VERSION); + when(release.worldSlug()).thenReturn("earth"); + when(release.authoredWorldSourceOperationId()).thenReturn(SOURCE_OPERATION); + when(release.authoredWorldSourceEvidenceDigest()).thenReturn(SOURCE_DIGEST); + when(release.commitId()).thenReturn("commit-id"); + when(release.publishWorkflowId()).thenReturn("publish-workflow"); + when(release.manifestHash()).thenReturn("sha256:" + "b".repeat(64)); + when(release.versionStateEpoch()).thenReturn(7L); + when(release.publishedReleaseBundleRef()).thenReturn("bundle:exact"); + + when(routeReader.readCurrentTarget(route)).thenReturn(route); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPublishedPlayerRouteReadService( + NAMESPACE, routeReader, catalogRepository, launchRepository, policyClient); + return new Fixture( + routeReader, + catalogRepository, + launchRepository, + policyClient, + route, + source, + launch, + descriptor, + release, + service); + } + + private static CanonicalGameplayRosterOwnerReadEvidence.Request exactRequest( + long pointerDelta, long catalogDelta, long epochDelta) { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + NAMESPACE, + TENANT, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L + catalogDelta, + 1L + pointerDelta, + 1L + epochDelta); + } + + private static WorldCanonicalInitialAdmissionHold.Request currentHoldRequest() { + return new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L, + "first-open-operation-17", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + } + + private static PreseededActorAssignmentOwnerReadEvidence.Request assignmentRequest( + UUID realmUuid) { + return new PreseededActorAssignmentOwnerReadEvidence.Request( + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + NAMESPACE, + TENANT, + "earth", + realmUuid, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L, + "b".repeat(64), + "bundle:exact"); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + CanonicalPlayerRouteReadService routeReader, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameDesignPublishedRealmPolicyClient policyClient, + CanonicalPlayableTarget route, + AuthoredWorldSourceEvidence source, + CanonicalInitialAdmissionLaunchTarget launch, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release, + CanonicalPublishedPlayerRouteReadService service) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java new file mode 100644 index 0000000000..d43281401e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java @@ -0,0 +1,302 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayRosterOwnerReadGrpcAdapterTest { + private static final String NAMESPACE = "test"; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + + @AfterEach + void tearDown() { + SessionContext.clear(); + } + + @Test + void exactEntityPeerReceivesExactProofAndEchoedAccountBinding() { + var provider = provider(); + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + var request = request(); + var typedRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid(request.getRequestUuid()), + ACCOUNT, + NAMESPACE, + TENANT, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 71L, + 73L, + 82L); + var proof = ownerProof(); + byte[] proofBytes = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof); + var policySet = + PublishedRealmPolicyEvidenceFixture.fixture( + TENANT, + VERSION, + 73L, + 42L, + "source-game-key-42", + "RETAINED_GAME_V29", + 3, + PublishedRealmPolicyEvidenceFixture.policy("main", true, true, "SHARED")) + .set(); + byte[] policyBytes = policySet.canonicalBytes(); + var evidence = + new CanonicalGameplayRosterOwnerReadEvidence( + typedRequest, "a".repeat(64), proof, policySet); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrent(typedRequest)).thenReturn(evidence); + + var observer = responseObserver(); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request, observer)); + + var responseCaptor = + org.mockito.ArgumentCaptor.forClass(GetCanonicalGameplayRosterOwnerReadResponse.class); + verify(observer).onNext(responseCaptor.capture()); + verify(observer).onCompleted(); + verify(source).readCurrent(typedRequest); + assertThat(responseCaptor.getValue().getRequest()).isEqualTo(request); + assertThat(responseCaptor.getValue().getRequest().getCanonicalAccountUuid()) + .isEqualTo(ACCOUNT.toString()); + assertThat(responseCaptor.getValue().getGameSessionOwnerProof().toByteArray()) + .isEqualTo(proofBytes); + assertThat(responseCaptor.getValue().getPublishedPolicySetEvidence().toByteArray()) + .isEqualTo(policyBytes); + } + + @Test + void rejectsWrongPeerNamespaceCallerContextAndTargetNamespaceBeforeSourceRead() { + var provider = provider(); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + var observer = responseObserver(); + + runAsPeer( + "world-management-service", + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), observer)); + assertStatus(observer, Status.Code.PERMISSION_DENIED); + verify(provider, never()).getIfAvailable(); + + var wrongNamespaceObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + "other", + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), wrongNamespaceObserver)); + assertStatus(wrongNamespaceObserver, Status.Code.PERMISSION_DENIED); + verify(provider, never()).getIfAvailable(); + + SessionContext.setContext(ACCOUNT.toString(), List.of("player"), Map.of()); + var callerContextObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), callerContextObserver)); + assertStatus(callerContextObserver, Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + var targetObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> + adapter.getCanonicalGameplayRosterOwnerRead( + request().toBuilder().setTargetNamespace("other").build(), targetObserver)); + assertStatus(targetObserver, Status.Code.PERMISSION_DENIED); + verify(provider, never()).getIfAvailable(); + } + + @Test + void rejectsUnknownAndPartialRequestsAndUnavailableOwnerTransport() { + var provider = provider(); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + var unknownObserver = responseObserver(); + var unknown = + request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(unknown, unknownObserver)); + assertStatus(unknownObserver, Status.Code.INVALID_ARGUMENT); + verify(provider, never()).getIfAvailable(); + + when(provider.getIfAvailable()).thenReturn(null); + var unavailableObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), unavailableObserver)); + assertStatus(unavailableObserver, Status.Code.UNAVAILABLE); + + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class))) + .thenThrow( + new CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException( + "private backend detail", new IllegalStateException("transport"))); + var transportObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), transportObserver)); + assertStatus(transportObserver, Status.Code.UNAVAILABLE); + } + + @Test + void staleOrInvalidCurrentSelectorsFailClosed() { + var provider = provider(); + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class))) + .thenThrow(new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException("stale")); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + var staleObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), staleObserver)); + assertStatus(staleObserver, Status.Code.FAILED_PRECONDITION); + + doThrow( + new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( + "changed policy or source")) + .when(source) + .readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class)); + var invalidObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), invalidObserver)); + assertStatus(invalidObserver, Status.Code.FAILED_PRECONDITION); + } + + private static void assertStatus(StreamObserver observer, Status.Code expected) { + var errorCaptor = org.mockito.ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(errorCaptor.capture()); + assertThat(Status.fromThrowable(errorCaptor.getValue()).getCode()).isEqualTo(expected); + assertThat(errorCaptor.getValue()).isInstanceOf(StatusRuntimeException.class); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static StreamObserver responseObserver() { + return mock(StreamObserver.class); + } + + private static GetCanonicalGameplayRosterOwnerReadRequest request() { + return GetCanonicalGameplayRosterOwnerReadRequest.newBuilder() + .setSchemaVersion(1) + .setRequestUuid("66666666-6666-4666-8666-666666666666") + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantUuid(TENANT.toString()) + .setWorldSlug("earth") + .setRealmUuid(REALM.toString()) + .setRealmSlug("main") + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceUuid(INSTANCE.toString()) + .setCanonicalVersionUuid(VERSION.toString()) + .setExpectedCatalogRevision(71L) + .setExpectedPointerVersion(73L) + .setExpectedActiveWorldEpoch(82L) + .build(); + } + + private static ObjectProvider provider() { + @SuppressWarnings("unchecked") + ObjectProvider provider = mock(ObjectProvider.class); + return provider; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof ownerProof() { + var request = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + "initial-admission-owner-request", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888")); + return new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-08T03:04:05Z")); + } + + private static void runAsPeer(String service, String namespace, Runnable action) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + service; + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, service)) + .run(action); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 14413fd81d..81fc275ae3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -182,6 +182,46 @@ void legacyNumericLaunchFailsClosedBeforeMutation() { assertNumericLaunchDeniedWithoutMutation(request); } + @ParameterizedTest + @ValueSource(strings = {"", "123e4567-e89b-12d3-a456-426614174000"}) + void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority(String legacyTenantId) { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-canonical-tenant", 42L); + doReturn( + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId("ld-cp-canonical-tenant") + .setCanonicalTenantId("123e4567-e89b-12d3-a456-426614174000") + .setTenantId(legacyTenantId) + .setGameTemplateId(request.gameTemplateId()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setVersionId(11L) + .setScriptPatchVersion("") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setVersionStateEpoch(77L) + .setReleaseBundleId(77L) + .setPublishedReleaseBundleRef("prb:1:11:77") + .build()) + .build()) + .when(gameDesignClient) + .resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + + Map before = new HashMap<>(); + store.forEach((id, instance) -> before.put(id, copyOf(instance))); + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); + + assertEquals("tenantId must be numeric", error.getMessage()); + org.assertj.core.api.Assertions.assertThat(store).usingRecursiveComparison().isEqualTo(before); + verify(gameDesignClient) + .resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + verifyNoMoreInteractions(gameDesignClient); + verifyNoInteractions(repository, worldManagementClient, stateService); + } + @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { StartSessionRequest request = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java index b14fe5c6d6..be0d8f8d68 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java @@ -12,14 +12,13 @@ import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotResponse; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.junit.jupiter.api.Test; -import org.springframework.test.util.TestSocketUtils; class WorldManagementStubServerTest { @Test void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { + int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); try { @@ -60,8 +59,8 @@ void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { @Test void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { + int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); try { @@ -92,8 +91,8 @@ void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { @Test void unknownRoomInstanceIdReturnsNotFound() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { + int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); try { diff --git a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java new file mode 100644 index 0000000000..0e887b49f4 --- /dev/null +++ b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java @@ -0,0 +1,765 @@ +package support.net.firedevops.firemud.gamesession; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.Request; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Complete canonical policy-set evidence for Game Session receiving-boundary tests. */ +public final class PublishedRealmPolicyEvidenceFixture { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID VERSION_IDENTITY_OPERATION_ID = + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaac"); + private static final UUID DRAFT_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID DRAFT_FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID INTAKE_REQUEST_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_OPERATION_ID = uuid("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final ObjectMapper JSON = new ObjectMapper(); + + private PublishedRealmPolicyEvidenceFixture() {} + + public static Fixture fixture(PolicySpec... requestedPolicies) { + return fixture( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("55555555-5555-4555-8555-555555555551"), + 19L, + 42L, + "tenant-key", + "NEW_GAME_ROW", + 3, + requestedPolicies); + } + + public static Fixture fixture( + UUID canonicalTenantId, + UUID canonicalVersionId, + long versionRowId, + long sourceGameRowId, + String tenantKey, + String provenanceKind, + int versionNumber, + PolicySpec... requestedPolicies) { + TargetProof target = + new TargetProof( + canonicalTenantId, + canonicalVersionId, + versionRowId, + tenantKey, + sourceGameRowId, + tenantKey, + provenanceKind); + DraftCommitBinding draft = freshGraphBinding(target); + byte[] accountBytes = accountBinding(draft); + var selection = selection(target, draft); + var workflow = + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + "publication-request") + .derivedWorkflowIdentity(); + var terminalReadRequest = + new WorldDraftTerminalReadEvidence.Request(1, "test", INTAKE_REQUEST_ID, accountBytes); + var committed = committedFreshGraphReadback(terminalReadRequest); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var worldRequest = + new Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + INTAKE_REQUEST_ID, + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + "publication-request", + selection.digest().substring(7), + 5L, + workflow, + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + JsonNode applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + var world = + new WorldPublishedStartLocationEvidence( + worldRequest, receipt, committed.fullBinding(), committed.result()); + var operation = new GameDesignPublicationOperationBinding(selectionAccount(selection), world); + var release = release(operation, versionNumber); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + 6L); + + List specs = + java.util.Arrays.stream(requestedPolicies) + .sorted( + java.util.Comparator.comparing(PolicySpec::worldSlug) + .thenComparing(PolicySpec::realmSlug)) + .toList(); + if (specs.isEmpty()) { + throw new IllegalArgumentException("At least one complete published policy is required"); + } + List policies = + specs.stream() + .map( + spec -> { + RealmEntryPolicy policy = policy(spec); + UUID policyId = + stableUuid("policy/" + canonicalVersionId + "/" + spec.realmSlug()); + UUID revisionId = + stableUuid("revision/" + canonicalVersionId + "/" + spec.realmSlug()); + String logicalRevisionId = + "realm-policy/" + spec.worldSlug() + "/" + spec.realmSlug(); + String policyDigest = + PublishedRealmEntryPolicySetEvidence.policyDigest( + policyId, + target, + versionNumber, + release.publishedReleaseBundleRef(), + release.contentDigest(), + workflow, + DIGEST, + draft.commitId(), + revisionId, + logicalRevisionId, + policy); + return new PublishedRealmEntryPolicyEvidence( + policyId, + draft.commitId(), + revisionId, + logicalRevisionId, + policy, + policyDigest); + }) + .toList(); + byte[] capture = capture(operation, draft, "43", specs, policies); + String setDigest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + versionNumber, + draft.commitId(), + "43", + release.publishedReleaseBundleRef(), + release.contentDigest(), + workflow, + DIGEST, + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies); + PublishedRealmEntryPolicySetEvidence evidence = + new PublishedRealmEntryPolicySetEvidence( + target, + versionNumber, + draft.commitId(), + "43", + release.publishedReleaseBundleRef(), + release.contentDigest(), + workflow, + DIGEST, + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies.size(), + setDigest, + policies); + if (!evidence.hasValidDigest()) { + throw new IllegalStateException("Canonical Game Design policy evidence fixture is invalid"); + } + return new Fixture(target, evidence, operation, terminal, capture); + } + + public static CanonicalPublishedPlayerRoute canonicalPublishedRoute() { + var fixture = fixture(policy("main", true, true, "SHARED")); + var route = + new CanonicalPlayableTarget( + "test", + "tenant-key", + uuid("11111111-1111-4111-8111-111111111111"), + "earth", + "Earth", + uuid("22222222-2222-4222-8222-222222222222"), + "main", + "main", + 101L, + 202L, + uuid("33333333-3333-4333-8333-333333333333"), + "SHARED", + uuid("44444444-4444-4444-8444-444444444444"), + fixture.target().canonicalVersionId(), + 303L, + 1L, + 7L, + "d".repeat(64), + 82L, + "first-open-operation-17", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + uuid("99999999-9999-4999-8999-999999999999"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "sha256:" + "c".repeat(64), + 27L, + "sha256:" + "f".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.parse("2026-10-07T00:00:00Z"), + "PRESEEDED_ONLY"); + return new CanonicalPublishedPlayerRoute( + route, fixture.set(), fixture.set().policies().getFirst()); + } + + public static CanonicalGameplayRosterClient.PreseededRosterSnapshot rosterSnapshot( + CanonicalPublishedPlayerRoute route, + UUID accountUuid, + List actors) { + var target = route.route(); + var publishedTarget = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(target.canonicalTenantId().toString()) + .setRealmUuid(target.realmId().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(target.canonicalGameInstanceId().toString()) + .setCatalogRevision(target.catalogRevision()) + .setPointerVersion(target.pointerVersion()) + .setActiveWorldEpoch(target.activeWorldEpoch()) + .setCanonicalVersionUuid(target.canonicalVersionId().toString()) + .setPublishedPolicyDigest( + route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())) + .setPublishedReleaseBundleRef(route.policySetEvidence().publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest(target.admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest(target.ownerProofDigest().substring("sha256:".length())) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + return new CanonicalGameplayRosterClient.PreseededRosterSnapshot( + accountUuid, + uuid("88888888-8888-4888-8888-888888888888"), + "b".repeat(64), + publishedTarget, + actors); + } + + public static PolicySpec policy( + String realmSlug, boolean visible, boolean publicProduction, String scope) { + return new PolicySpec("earth", "Earth", realmSlug, realmSlug, visible, publicProduction, scope); + } + + private static AccountPublicationAuthorizationBinding selectionAccount( + AuthoredDraftPublishSelectionBinding selection) { + return new AccountPublicationAuthorizationBinding( + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR_ID, selection), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + ACTOR_ID.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}))); + } + + private static AuthoredDraftPublishSelectionBinding selection( + TargetProof target, DraftCommitBinding draft) { + String request = "publication-request"; + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + request, + "5", + "test publication", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + java.time.OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + } + + private static DraftCommitBinding freshGraphBinding(TargetProof target) { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", target.canonicalTenantId().toString(), + "versionId", target.canonicalVersionId().toString(), + "startLocation", + Map.of( + "tenantId", target.canonicalTenantId().toString(), + "versionId", target.canonicalVersionId().toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + target, + DRAFT_REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) { + var payload = new LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) { + try { + payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + DRAFT_REQUEST_ID, + COMMIT_ID, + DRAFT_FENCE_ID, + ACTOR_ID, + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + draft.baseCommitId(), + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + ACTOR_ID.toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedFreshGraphReadback( + WorldDraftTerminalReadEvidence.Request request) { + try { + var account = request.accountBinding(); + DraftCommitBinding draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), + account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + VERSION_IDENTITY_OPERATION_ID.toString(), + Long.toString(draft.target().gameDesignVersionRowId()), + INTAKE_REQUEST_ID.toString(), + INTAKE_OPERATION_ID.toString(), + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + + byte[] graph = graphBytes(request, draft); + String graphDigest = sha256(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + sha256(account.canonicalBytes()), + draft.digest(), + new RoomTemplateRef( + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + ROOM_TEMPLATE_ID), + graphDigest); + byte[] receiptBytes = receipt.canonicalBytes(); + var result = new LinkedHashMap(); + result.put("schema", "world-draft-graph-applied/v2"); + result.put("status", "APPLIED"); + result.put( + "operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.receiptDigest()); + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", unit.aggregateType(), + "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), + "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), + "resultingEpoch", + Long.toString(Long.parseLong(unit.expectedEpoch()) + 1))) + .toList()); + byte[] resultBytes = canonical(JSON.valueToTree(result)); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + resultBytes); + } catch (Exception invalid) { + throw new IllegalStateException("Fresh World evidence fixture could not be created", invalid); + } + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + JsonNode mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", draft.target().gameDesignVersionRowId()); + mapping.put("version_identity_operation_id", VERSION_IDENTITY_OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static byte[] capture( + GameDesignPublicationOperationBinding operation, + DraftCommitBinding binding, + String sourceEpoch, + List specs, + List policies) { + try { + List> entries = + java.util.stream.IntStream.range(0, specs.size()) + .mapToObj( + index -> { + Map source = new LinkedHashMap<>(); + source.put("commitId", policies.get(index).sourceCommitId().toString()); + source.put("revisionId", policies.get(index).sourceRevisionId().toString()); + source.put("logicalRevisionId", policies.get(index).logicalRevisionId()); + try { + source.put( + "policy", JSON.readTree(policies.get(index).policy().canonicalJson())); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + return source; + }) + .toList(); + var snapshot = new LinkedHashMap(); + snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", sourceEpoch); + snapshot.put("policies", entries); + byte[] snapshotBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + return capture.toByteArray(); + } catch (Exception invalid) { + throw new IllegalStateException( + "Policy source capture fixture could not be created", invalid); + } + } + + private static ReleaseContent release( + GameDesignPublicationOperationBinding operation, int versionNumber) { + var request = operation.world().request(); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + versionNumber, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of(), + List.of(), + participants, + List.of("LOOK"), + "generation-1", + operation.world()); + } + + private static RealmEntryPolicy policy(PolicySpec spec) { + String json = + "{\"schemaVersion\":1,\"worldSlug\":\"" + + spec.worldSlug() + + "\",\"worldDisplayName\":\"" + + spec.worldDisplayName() + + "\",\"realmSlug\":\"" + + spec.realmSlug() + + "\",\"realmDisplayName\":\"" + + spec.realmDisplayName() + + "\",\"visible\":" + + spec.visible() + + ",\"publicProduction\":" + + spec.publicProduction() + + ",\"stateScope\":\"" + + spec.stateScope() + + "\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + return RealmEntryPolicy.parse(json, JSON); + } + + private static byte[] canonical(JsonNode node) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(node)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID stableUuid(String text) { + return UUID.nameUUIDFromBytes(text.getBytes(StandardCharsets.UTF_8)); + } + + public static UUID uuid(String value) { + return UUID.fromString(value); + } + + public record PolicySpec( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope) {} + + public record Fixture( + TargetProof target, + PublishedRealmEntryPolicySetEvidence set, + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal, + byte[] captureBytes) { + public Fixture { + captureBytes = captureBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + } +}