From 22ab2314b988be609d693a3befe73e490454df17 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:54:50 +1300 Subject: [PATCH 001/105] Complete direct-text JOIN player stage --- .../game-session-service/protocols.md | 18 +- .../system-architecture-authz-route-matrix.md | 4 +- ...ystem-architecture-authz-route-matrix.yaml | 11 +- .../player-access-and-session.md | 6 +- .../gamesession/client/AccountClient.java | 131 ++++ .../client/DirectTextConnectScopeTarget.java | 32 + .../BuiltInTextCommandDefinitionProvider.java | 9 + .../command/text/GameplayWorldCatalog.java | 172 ++++- .../command/text/HelpCommandHandler.java | 12 + .../command/text/LogoutCommandHandler.java | 31 +- .../command/text/PlayCommandHandler.java | 20 + .../gamesession/command/text/TextCommand.java | 6 + .../command/text/TextCommandParser.java | 10 + .../command/text/TextCommandPayload.java | 17 + .../command/text/TextCommandType.java | 2 + .../command/text/WorldsCommandHandler.java | 574 ++++++++++++++- .../WorldsTextCommandDispatchHandler.java | 119 ++- .../entity/GameplayAdmissionPointer.java | 4 + .../GameplayAdmissionPointerRepository.java | 52 ++ .../DirectTextConnectScopeSessionStore.java | 299 ++++++++ .../GameplayAdmissionPointerSnapshot.java | 70 +- ...eplayAdmissionPointerAuthorityService.java | 40 +- .../service/impl/GameSessionGrpcService.java | 60 +- ...V5__separate_gameplay_catalog_revision.sql | 4 + .../V6__persist_gameplay_realm_identity.sql | 74 ++ .../gamesession/client/AccountClientTest.java | 101 +++ .../text/GameplayWorldCatalogTest.java | 102 +++ .../command/text/HelpCommandHandlerTest.java | 14 + .../command/text/PlayCommandHandlerTest.java | 51 ++ .../text/TextCommandInterpreterTest.java | 8 +- .../command/text/TextCommandParserTest.java | 33 + .../text/WorldsCommandHandlerTest.java | 679 +++++++++++++++++- .../WorldsTextCommandDispatchHandlerTest.java | 284 +++++++- ...ameplayAdmissionPointerRepositoryTest.java | 137 ++++ ...irectTextConnectScopeSessionStoreTest.java | 142 ++++ ...yAdmissionPointerAuthorityServiceTest.java | 1 + .../impl/GameSessionGrpcServiceTest.java | 402 ++++++++++- 37 files changed, 3626 insertions(+), 105 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index be24a5b9c6..f36e80348c 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` may return `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the current `PLAY` consumer does not classify the latter specifically as `INACTIVE`, and direct-text clients can then issue `JOIN` without creating or restoring membership implicitly. Current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration` in the runtime membership response, but the current text `PLAY` consumer still decides from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; it does not yet consume the lifecycle or authority-generation fields, so an `ACTIVE` or `INACTIVE` classification remains target-only in `PLAY`. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). @@ -39,7 +39,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, `JOIN` is unavailable and `PLAY` applies only the Account-exposed `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` fields plus existing grant checks; it cannot classify `ACTIVE` or `INACTIVE` until Account exposes lifecycle state. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification, and explicit `JOIN` remains unavailable; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, direct-text `JOIN` is available through Account's explicit membership writer, while first-party `Join & Play` remains unavailable; Account exposes lifecycle and authority-generation fields, but `PLAY` still applies only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus existing grant checks and does not yet consume those new fields to classify `ACTIVE` or `INACTIVE`. An eligible public-production denial may return `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification, and direct-text clients can complete `JOIN`; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -64,7 +64,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Target-only; not currently implemented.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | +| `JOIN ` | **Implemented for direct text; proof incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | @@ -82,14 +82,14 @@ Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable ` The canonical JOIN and membership-admission contract is defined in [Authentication & Authorization](../../system-architecture-authentication.md#normative-target-contract); this section keeps only Game Session's protocol translation and local handling. -The target Account membership operation is `JoinPublicProductionMembership`; it remains target-only and unimplemented, so there is no current implicit membership writer. When the explicit text action is implemented, Game Session translates `JOIN ` to the sole target operation `JoinPublicProductionMembership`; it does not create membership locally or use another join writer. +The Account membership operation is `JoinPublicProductionMembership`; the direct-text implementation is current and remains the sole membership writer, with Account-owned membership and audit/outbox consequences. Game Session translates `JOIN ` to that operation; it does not create membership locally or use another join writer. The first-party `Join & Play` action remains target-only. - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. - Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the pending transport-local scope and passes the same identity to Account for retries. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. - An ambiguous or stale world/realm selector is a lobby-selection error: Game Session does not guess, does not invoke Account, and directs the client to refresh `WORLDS`/`REALMS`. A discovered scope that is stale or no longer matches the resolved `worldSlug`/`realmSlug` fails closed with the applicable scope or admission error rather than being translated to a newer target. - JOIN idempotency uses the canonical preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session generates and retains the server-side `requestId`, passes the verified local digest inputs and retained scope to Account, and reuses that identity through retries and scope-expiry cleanup. Account replays an exact `{requestId, digest}` outcome and rejects a different digest as `IDEMPOTENCY_CONFLICT`; a new `requestId` is a distinct attempt after a new scope. -Current `JOIN` availability and the membership-authority-generation gap are recorded in [Implementation Status](#implementation-status); this section defines only the target translation and must not be read as evidence that the explicit-join action is live. +Direct-text `JOIN` availability and the membership-authority-generation gap are recorded in [Implementation Status](#implementation-status); this section defines the target translation and current local handling, while the remaining runtime and end-to-end proof gaps do not establish full path completion. ## Login and Play Flow @@ -114,13 +114,13 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. It also does not expose `membershipLifecycleState`, so it uses the four-field Account adapter response (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because the adapter does not expose lifecycle state. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current `PLAY` consumer still validates the four fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and does not consume the lifecycle or authority-generation fields to classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; direct-text clients can then use the implemented `JOIN`, while the latter case remains unclassified by `PLAY`. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. ### Login and world-selection examples -Target-state/unimplemented world-selection transcript showing public browsing plus slug and index equivalence: +World-selection transcript showing public browsing plus slug and index equivalence; direct-text `JOIN` is implemented locally, while full end-to-end proof remains open: ```text WORLDS @@ -164,7 +164,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – bootstrap-backed `LOGIN` resolved to an account different from the validated connect-context subject. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. In the current runtime this is a fail-closed, non-actionable result because explicit `JOIN` is unavailable, and the existing non-admitting case cannot be classified as `INACTIVE` because Account does not expose lifecycle state. +- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. Direct-text clients can issue the implemented `JOIN`; first-party `Join & Play` remains unavailable. Account exposes lifecycle state, but current `PLAY` does not consume it, so the existing non-admitting case is not classified as `INACTIVE` there. - `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. @@ -204,7 +204,7 @@ OK PLAY Entered world: Demo World / Live Realm The transcript above shows the intended multi-line prompt flow. In the current implementation, the client sends `LOGIN ` to request a code and then submits `LOGIN `, or sends `LOGIN ` directly; bare non-bootstrap login returns `ERROR PROMPT_LOGIN_UNSUPPORTED ...`. -Planned target Telnet first-join success transcript; explicit `JOIN` is not current behavior: +Planned target Telnet first-join success transcript; direct-text `JOIN` is implemented locally, while full end-to-end proof remains open: ```text WORLDS diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index b8c0552065..3c65ac600f 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -25,7 +25,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status -- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the Account runtime response reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current Game Session `PLAY` consumer does not yet consume those fields, so the latter response is not classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Account's explicit JOIN writer is implemented locally, but Game Session text dispatch and direct text-client end-to-end proof remain unavailable in this stage; first-party `Join & Play` and durable unknown-outcome recovery remain incomplete. +- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the Account runtime response reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current Game Session `PLAY` consumer does not yet consume those fields, so the latter response is not classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Direct-text `JOIN` is implemented locally through Account's explicit writer; first-party `Join & Play`, durable unknown-outcome recovery, and end-to-end proof remain incomplete. - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. @@ -215,7 +215,7 @@ For every first public-production text entry, the target command sequence is `LO | Game Session Service | `WORLDS` anonymous browse | `public` | Public-production catalog only; no account-specific membership, grant, or character information | | Game Session Service | `WORLDS` authenticated discovery | `pre_tenant_discovery` | No pre-existing tenant role is required. Tenant visibility is derived server-side from membership or public-production visibility plus entitlement state; global roles do not widen gameplay discovery | | Game Session Service | `REALMS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive branch from the authoritative realm mode: public production permits pre-membership discovery; private/playtest requires caller-bound `membershipLifecycleState=ACTIVE`, current membership authority generation/version, and the current Account-owned grant for the exact target. Private/playtest is never classified as public onboarding, never falls back to public discovery, and never uses a grant to repair membership. Hidden/unauthorized targets are omitted; explicit branch failures use `NON_PUBLIC_ENROLLMENT_REQUIRED`, `REALM_ACCESS_DENIED`, `WORLD_ACCESS_DENIED`, `ADMISSION_POINTER_UNAVAILABLE`, `REALM_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE`, or `AUTH_UNAVAILABLE` as applicable. | -| Game Session Service | `JOIN` | `public_production_onboarding` | **Target-only; not currently implemented.** Explicit caller-bound open-enrollment action for the current public production realm; Account commits durable membership plus audit/outbox idempotently | +| Game Session Service | `JOIN` | `public_production_onboarding` | **Implemented locally; proof incomplete.** Game Session retains the Account-issued scope and submits explicit JOIN to Account, which commits caller-bound membership plus audit/outbox evidence locally. Membership-generation, unknown-outcome recovery/reconciliation, receipt/retention, PostgreSQL runtime, and direct-text end-to-end proof remain open; see [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Game Session Service | `CHARS` | `public_production_onboarding` (public branch); `caller_membership_scoped` (private/playtest branch) | Selects exactly one mutually exclusive public-production or grant-backed private/playtest branch. Public discovery may lead to `JOIN_REQUIRED` for missing or `INACTIVE` membership; private/playtest requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. It applies the current `admission_pointer` check to the selected catalog realm, but does not apply `PLAY`'s exact-binding admission lease, binding fence, or binding-ownership gate; character discovery and creation do not require a selected character. Policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and unavailable or invalid authority uses the applicable unavailable/invalid-authority outcome. Missing or non-`ACTIVE` private/playtest membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, and character discovery is not membership repair. | | Game Session Service | `PLAY` | `gameplay_admission` | **Target:** requires an existing caller-bound membership plus any non-public realm grant, current entitlements, and the current admissible realm pointer; `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when the selected target is confirmed as public production and its joining policy denies entry, and only an admissible, publicly visible public-production target whose joining policy permits entry and whose membership is missing or `INACTIVE` returns `JOIN_REQUIRED`; `ACTIVE` membership does not require `JOIN`, and `PLAY` never creates or restores membership. `PLAY` alone performs the final gameplay-binding CAS. First-party `/ws/game/**` also enforces connect-context scope. Unavailable, ambiguous, stale, or otherwise invalid routing returns `ADMISSION_POINTER_UNAVAILABLE`; a deliberately closed realm returns `REALM_UNAVAILABLE`; entitlement authority outage returns `ENTITLEMENT_UNAVAILABLE`. | | Spring Cloud Gateway | `/ws/game/**` (connect-token bootstrap) | `gameplay_admission` | **Implemented but non-promotable until the named Gateway readiness evidence is complete:** carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. This is one canonical WebSocket entry point with mutually exclusive variants. The current `first_party_web` variant accepts exactly the protected cookie for first-party protected-cookie clients, including native or other nonbrowser clients using a cookie jar. The live `GameplayHandshakeFilter` rejects `X-Firemud-Connect-Token` on this public route with `CONNECT_TOKEN_REJECTED` and reason `unsupported_carrier_or_route`, without falling back to the cookie. A future explicitly classified `non_first_party_public` variant may use the header only after its dedicated matrix entry and issuance, replay, signed-context, response, and carrier proof exist; it cannot select or fall back to `first_party_web`. Gateway consumes exactly one supported carrier, strips it, atomically enforces single use using the dedicated replay record/fence, matches the signed connect scope to the request, and emits the signed connect context for Game Session. Non-`101` outcomes use the bounded `CONNECT_TOKEN_MISSING`, `CONNECT_TOKEN_EXPIRED`, `CONNECT_TOKEN_REPLAYED`, `CONNECT_SCOPE_MISMATCH`, `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, `CONNECT_TOKEN_REJECTED`, `POLICY_DENY`, `POLICY_PRESSURE`, `BACKEND_UNAVAILABLE`, `PROTOCOL_MISMATCH`, or `INTERNAL_ERROR` handshake classes. | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 388b2834a0..a4ba1e7e20 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -393,7 +393,7 @@ required_live_check_vocabulary: - security_lock_export_action_family implementation_status: known_drift: - - Account_explicit_public_production_JOIN_writer_is_implemented_locally_but_Game_Session_text_dispatch_and_direct_text_end_to_end_proof_remain_unavailable; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_but_current_PLAY_consumer_still_uses_membershipExists_gameplayAdmissionAllowed_membershipVersion_and_evaluatedAt_without_consuming_the_new_fields; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented + - direct_text_explicit_public_production_JOIN_is_implemented_locally; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_but_current_PLAY_consumer_still_uses_membershipExists_gameplayAdmissionAllowed_membershipVersion_and_evaluatedAt_without_consuming_the_new_fields; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented - protected_cookie_ws_game_and_bootstrap_bare_LOGIN_are_implemented_but_non_promotable_until_Gateway_carrier_requirements_replay_marker_durability_replay_quarantine_continuity_and_Account_planned_rotation_compromise_cutover_evidence_are_complete - privileged_control_is_target_only_and_unavailable_in_current_runtime; platformAdmin_and_cross_tenant_billingAdmin_branches_requiring_it_fail_closed_while_the_support_branch_does_not_require_it - operator_mutation_rows_are_normative_target_contracts_not_current_availability; action_schema_mutationDigest_v1_vectors_and_account_issued_authorization_reference_flow_are_required_before_external_support @@ -1160,7 +1160,6 @@ routes: any_of: [JOIN_REQUIRED, PUBLIC_PRODUCTION_ADMISSION_DENIED, NON_PUBLIC_ENROLLMENT_REQUIRED, REALM_ACCESS_DENIED, WORLD_ACCESS_DENIED, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] - service: game-session-service route: JOIN - route_status: target_not_currently_routable scope: tenant classification: public_production_onboarding auth_path: game_session_authenticated_context @@ -1173,9 +1172,15 @@ routes: membership_authority_generation_applies: false required_live_checks: [public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, TENANT_BILLING_BLOCKED] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation + implementation_status: + known_drift: + - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only + - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only + - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable - service: game-session-service route: PLAY scope: tenant 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 b70063cb42..4e6acf3328 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Game Session text dispatch for JOIN and direct text-client end-to-end proof remain unavailable in this stage. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision; PostgreSQL runtime proof and direct text-client end-to-end proof are not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -34,7 +34,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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. Generic payment scaffolds still retain provider-mutating drift. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. Account's explicit public-production JOIN writer exists locally, but Game Session text dispatch and direct text-client end-to-end proof remain unavailable in this stage; first-party `Join & Play`, membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. Explicit JOIN exists locally through Account's public-production writer, but this does not prove the direct text-client path; the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025. | | `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. | | `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. | @@ -61,7 +61,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Current connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target but does not revalidate the applicable non-public grant. Target issuance grant validation and its focused proof remain gaps. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. The canonical `JoinPublicProductionMembership` Account writer is implemented locally, including a policy-bound v1 digest and membership/audit outbox transaction. Game Session text `JOIN` dispatch and first-party `Join & Play` remain unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam and direct text-client proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit `JOIN`/`Join & Play` is implemented locally through the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. Its `PENDING`/unknown-database-outcome recovery seam and direct text-client proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index bd417a98ea..10bb5ebc71 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -3,6 +3,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; +import java.util.Objects; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -14,6 +15,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; @@ -25,6 +30,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; import org.springframework.stereotype.Component; @@ -159,6 +165,131 @@ public PingResponse ping() { return callStub().ping(PingRequest.getDefaultInstance()); } + /** Requests one Account-owned direct-text scope for a server-resolved REALMS target. */ + public IssueDirectTextConnectScopeResponse issueDirectTextConnectScope( + PlayerExecutionContext playerContext, DirectTextConnectScopeTarget target) { + Objects.requireNonNull(playerContext, "playerContext must not be null"); + Objects.requireNonNull(target, "target must not be null"); + if (!hasDirectTextCallerIdentity(playerContext) + || !playerContext.getTenantId().equals(target.tenantId()) + || !playerContext.getRealmId().equals(target.realmId()) + || !playerContext.getPlayableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !playerContext.getPlayableStateScope().equals(target.playableStateScope()) + || !playerContext.getGameInstanceId().equals(target.gameInstanceId())) { + return scopeIssueError("INVALID_ARGUMENT", "Direct-text scope context did not match target"); + } + if (stub() == null) { + return scopeIssueError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + IssueDirectTextConnectScopeRequest request = + IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(playerContext) + .setTenantId(target.tenantId()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setRealmId(target.realmId()) + .setPlayableStateNamespaceId(target.playableStateNamespaceId()) + .setPlayableStateScope(target.playableStateScope()) + .setGameInstanceId(target.gameInstanceId()) + .setCatalogRevision(target.catalogRevision()) + .setPointerVersion(target.pointerVersion()) + .build(); + try { + return callStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .issueDirectTextConnectScope(request); + } catch (StatusRuntimeException ex) { + logger.warn("Account direct-text scope issuance failed", ex); + return scopeIssueError(accountAuthorityErrorCode(ex), "Account authority unavailable"); + } catch (Exception ex) { + logger.warn("Account direct-text scope issuance did not complete", ex); + return scopeIssueError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + } + + /** Applies explicit direct-text JOIN with a caller-bound, immutable request identity. */ + public JoinPublicProductionMembershipResponse joinPublicProductionMembership( + PlayerExecutionContext playerContext, String connectScopeId, String requestId) { + Objects.requireNonNull(playerContext, "playerContext must not be null"); + if (!hasDirectTextCallerIdentity(playerContext) + || connectScopeId == null + || connectScopeId.isBlank() + || requestId == null + || requestId.isBlank() + || !playerContext.getRequestId().equals(requestId)) { + return joinError("INVALID_ARGUMENT", "Direct-text JOIN request was incomplete"); + } + if (stub() == null) { + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + JoinPublicProductionMembershipRequest request = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(playerContext) + .setConnectScopeId(connectScopeId) + .setRequestId(requestId) + .build(); + try { + return callStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .joinPublicProductionMembership(request); + } catch (StatusRuntimeException ex) { + if (ex.getStatus().getCode() == Status.Code.UNAVAILABLE + || ex.getStatus().getCode() == Status.Code.DEADLINE_EXCEEDED) { + logger.warn( + "Account direct-text JOIN response was unavailable; retrying same request id", ex); + try { + initClient(); + return callStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .joinPublicProductionMembership(request); + } catch (Exception retryEx) { + logger.warn("Account direct-text JOIN retry did not complete", retryEx); + } + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + logger.warn("Account direct-text JOIN returned a terminal transport status", ex); + return joinError(ex.getStatus().getCode().name(), "Account JOIN request failed"); + } catch (Exception ex) { + logger.warn("Account direct-text JOIN did not complete", ex); + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + } + + private boolean hasDirectTextCallerIdentity(PlayerExecutionContext context) { + return isPositiveLong(context.getAccountId()) && isPositiveLong(context.getSessionId()); + } + + private boolean isPositiveLong(String value) { + if (value == null || value.isBlank()) { + return false; + } + try { + return Long.parseLong(value) > 0; + } catch (NumberFormatException ignored) { + return false; + } + } + + private String accountAuthorityErrorCode(StatusRuntimeException exception) { + Status.Code statusCode = exception.getStatus().getCode(); + return statusCode == Status.Code.UNAVAILABLE || statusCode == Status.Code.DEADLINE_EXCEEDED + ? "AUTH_UNAVAILABLE" + : statusCode.name(); + } + + private IssueDirectTextConnectScopeResponse scopeIssueError(String code, String message) { + return IssueDirectTextConnectScopeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(code).setMessage(message)) + .build(); + } + + private JoinPublicProductionMembershipResponse joinError(String code, String message) { + return JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode(code) + .setError(ErrorDetail.newBuilder().setCode(code).setMessage(message)) + .build(); + } + public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( String accountId, String tenantId, String requestId) { if (stub() == null) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java new file mode 100644 index 0000000000..dfeca7a8e8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.gamesession.client; + +/** Server-resolved realm routing evidence sent to Account before a direct-text scope is issued. */ +public record DirectTextConnectScopeTarget( + String tenantId, + String worldSlug, + String realmSlug, + String realmId, + String playableStateNamespaceId, + String playableStateScope, + String gameInstanceId, + long catalogRevision, + long pointerVersion) { + public DirectTextConnectScopeTarget { + requireText(tenantId, "tenantId"); + requireText(worldSlug, "worldSlug"); + requireText(realmSlug, "realmSlug"); + requireText(realmId, "realmId"); + requireText(playableStateNamespaceId, "playableStateNamespaceId"); + requireText(playableStateScope, "playableStateScope"); + requireText(gameInstanceId, "gameInstanceId"); + if (catalogRevision < 1 || pointerVersion < 1) { + throw new IllegalArgumentException("routing revisions must be positive"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(name + " must not be blank"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java index 8e6d594561..1f3eee1a37 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/BuiltInTextCommandDefinitionProvider.java @@ -30,6 +30,15 @@ final class BuiltInTextCommandDefinitionProvider implements TextCommandDefinitio TextCommandPromptPolicy.NEVER, TextCommandActionCategory.META, List.of(TextCommandActionTag.WORLD_BROWSE, TextCommandActionTag.UI)); + register( + definitions, + TextCommandType.JOIN, + List.of("join"), + TextCommandDispatchGroup.WORLDS, + TextCommandStageRequirement.LOGIN, + TextCommandPromptPolicy.NEVER, + TextCommandActionCategory.META, + List.of(TextCommandActionTag.WORLD_BROWSE, TextCommandActionTag.UI)); register( definitions, TextCommandType.CHARS, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index b24f5862c0..132011e453 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -55,17 +56,18 @@ public Optional resolveWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List worlds = visibleWorlds(); + List visibleWorlds = visibleWorlds(); + List indexedWorlds = discoverableWorlds(); try { int index = Integer.parseInt(selector); - if (index >= 1 && index <= worlds.size()) { - return Optional.of(worlds.get(index - 1)); + if (index >= 1 && index <= indexedWorlds.size()) { + return Optional.of(indexedWorlds.get(index - 1)); } } catch (NumberFormatException ignored) { // Fall back to slug matching. } String normalized = selector.trim().toLowerCase(Locale.ROOT); - return worlds.stream() + return visibleWorlds.stream() .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) .findFirst(); } @@ -105,10 +107,62 @@ public Optional resolveDefaultRealm(WorldView world) { if (visibleRealms.isEmpty()) { return Optional.empty(); } + List publicProductionRealms = + visibleRealms.stream().filter(RealmView::publicProductionRealm).toList(); + if (publicProductionRealms.size() > 1) { + return Optional.empty(); + } + if (publicProductionRealms.size() == 1) { + RealmView publicRealm = publicProductionRealms.getFirst(); + return hasValidPublicProductionRealm(publicRealm.tenantId()) + ? Optional.of(publicRealm) + : Optional.empty(); + } + // Preserve explicit non-public presentation when the selected tenant has a valid public + // production realm elsewhere in the catalogue. A tenant with zero public realms is invalid + // authority, so it must not become a default by falling back to the first visible row. return visibleRealms.stream() - .filter(RealmView::publicProductionRealm) - .findFirst() - .or(() -> Optional.of(visibleRealms.get(0))); + .allMatch(realm -> hasValidPublicProductionRealm(realm.tenantId())) + ? Optional.of(visibleRealms.getFirst()) + : Optional.empty(); + } + + /** + * Returns the tenant-wide cardinality of visible, player-addressable public-production realms. + * The scan intentionally spans every authored world because a tenant may have candidates in + * more than one world selector. + */ + public PublicProductionRealmCardinality publicProductionRealmCardinality(long tenantId) { + if (tenantId <= 0L) { + return PublicProductionRealmCardinality.ZERO; + } + long count = + normalizeWorlds(worldSupplier.get()).stream() + .flatMap(world -> world.realms().stream()) + .filter(realm -> realm.tenantId() == tenantId) + .filter(this::isPlayerAddressable) + .filter(RealmView::publicProductionRealm) + .count(); + return switch (Long.compare(count, 1L)) { + case -1 -> PublicProductionRealmCardinality.ZERO; + case 0 -> PublicProductionRealmCardinality.EXACTLY_ONE; + default -> PublicProductionRealmCardinality.MULTIPLE; + }; + } + + public boolean hasValidPublicProductionRealm(long tenantId) { + return publicProductionRealmCardinality(tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE; + } + + /** Returns whether every tenant represented by this selected world has unambiguous authority. */ + public boolean hasValidPublicProductionRealm(WorldView world) { + List visibleRealms = visibleRealms(world); + return !visibleRealms.isEmpty() + && visibleRealms.stream() + .map(RealmView::tenantId) + .distinct() + .allMatch(this::hasValidPublicProductionRealm); } public boolean requiresExplicitRealmSelection(WorldView world) { @@ -180,14 +234,13 @@ public List visibleWorlds() { } private List worldEntries() { - List worlds = visibleWorlds(); + List worlds = discoverableWorlds(); ArrayList entries = new ArrayList<>(worlds.size()); - for (int i = 0; i < worlds.size(); i++) { - WorldView world = worlds.get(i); - RealmView defaultRealm = defaultRealm(world); + for (WorldView world : worlds) { + RealmView defaultRealm = resolveDefaultRealm(world).orElseThrow(); entries.add( new WorldsViewOutput.WorldEntry( - i + 1, + entries.size() + 1, world.slug(), world.displayName(), defaultRealm.gameInstanceId(), @@ -196,6 +249,12 @@ private List worldEntries() { return List.copyOf(entries); } + private List discoverableWorlds() { + return visibleWorlds().stream() + .filter(world -> resolveDefaultRealm(world).isPresent()) + .toList(); + } + private List realmEntries(WorldView world) { List realms = visibleRealms(world); ArrayList entries = new ArrayList<>(realms.size()); @@ -218,13 +277,12 @@ private boolean hasVisibleRealmEntries(WorldView world) { return world != null && !visibleRealms(world).isEmpty(); } - private RealmView defaultRealm(WorldView world) { - return resolveDefaultRealm(world) - .orElseGet( - () -> { - return new RealmView( - "production", "Live Realm", 0L, 0L, 1L, true, true, false, "SHARED", "ALLOW_NEW"); - }); + private boolean isPlayerAddressable(RealmView realm) { + return realm != null + && realm.visible() + && realm.slug() != null + && !realm.slug().isBlank() + && realm.tenantId() > 0L; } private static List normalizeWorlds(List worlds) { @@ -285,7 +343,10 @@ private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { pointer.publicProductionRealm(), pointer.requiresCharacterSelection(), pointer.stateScope(), - pointer.characterCreationPolicy()); + pointer.characterCreationPolicy(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId()); } private static WorldView copyWorldView(WorldView input) { @@ -312,7 +373,10 @@ private static RealmView copyRealmView(RealmView input) { input.publicProductionRealm(), input.requiresCharacterSelection(), input.stateScope(), - input.characterCreationPolicy()); + input.characterCreationPolicy(), + input.catalogRevision(), + input.realmId(), + input.playableStateNamespaceId()); } public record WorldView(String slug, String displayName, List realms) { @@ -331,11 +395,75 @@ public record RealmView( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic realm view without authoritative identity evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic realm view without authoritative catalog revision evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } + } public record RuntimeRealmTarget( String worldSlug, String worldDisplayName, String realmSlug, String realmDisplayName) {} + public enum PublicProductionRealmCardinality { + ZERO, + EXACTLY_ONE, + MULTIPLE + } + private static final class MutableWorldAccumulator { private final String slug; private final String displayName; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index 747ef90542..ee8e3b095e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -83,6 +83,11 @@ public TextCommandInterpretationResult handle( success( "PLAY [realm] [character]\n" + "Select the world to enter, optionally name a visible realm, and optionally choose a character."); + case "JOIN" -> + success( + "JOIN \n" + + "Join the public-production membership for a world after LOGIN.\n" + + "Use REALMS first, then JOIN before CHARS and PLAY."); case "REALMS" -> success( "REALMS \n" @@ -226,6 +231,9 @@ private ResolvedHelpTopic canonicalTopic(String topic, Optional case "HELP" -> "HELP"; case "LOGIN", "LOGON" -> "LOGIN"; case "PLAY" -> "PLAY"; + case "JOIN" -> "JOIN"; + case "REALMS" -> "REALMS"; + case "CHARS" -> "CHARS"; case "WHO" -> "WHO"; case "STATUS", "STAT" -> "STATUS"; case "FRIENDS" -> "FRIENDS"; @@ -271,6 +279,9 @@ private String topicIndex(Optional maybeContext) { "Help topics:", "- HELP LOGIN", "- HELP PLAY", + "- HELP REALMS", + "- HELP JOIN", + "- HELP CHARS", "- HELP WHO", "- HELP STATUS", "- HELP FRIENDS", @@ -336,6 +347,7 @@ private boolean isEnabled( private PlayerCommandCapability capabilityForTopic(String topic) { return switch (topic) { + case "JOIN", "REALMS", "CHARS" -> PlayerCommandCapability.MANDATORY; case "SAY", "WHISPER", "TELL", "FRIENDS" -> PlayerCommandCapability.SOCIAL; case "WHO" -> PlayerCommandCapability.PRESENCE; case "INVENTORY", "EQUIPMENT", "CONTAINER", "PUT", "TAKE", "WEAR", "REMOVE", "GET", "DROP" -> diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java index 1aeafbe85a..6c425dd50a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -17,6 +18,7 @@ import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** Handles deliberate player logout distinct from reconnect-loss recovery. */ @@ -29,7 +31,9 @@ public final class LogoutCommandHandler { private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry; private final ScriptEventPublisher scriptEventPublisher; + private final DirectTextConnectScopeSessionStore directTextConnectScopeSessionStore; + @Autowired public LogoutCommandHandler( SessionAuthenticationService sessionAuthenticationService, SessionContextService sessionContextService, @@ -37,7 +41,8 @@ public LogoutCommandHandler( GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, GameplayPresenceLifecycleService gameplayPresenceLifecycleService, FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, - ScriptEventPublisher scriptEventPublisher) { + ScriptEventPublisher scriptEventPublisher, + DirectTextConnectScopeSessionStore directTextConnectScopeSessionStore) { this.sessionAuthenticationService = Objects.requireNonNull( sessionAuthenticationService, "sessionAuthenticationService must not be null"); @@ -57,6 +62,29 @@ public LogoutCommandHandler( firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); this.scriptEventPublisher = Objects.requireNonNull(scriptEventPublisher, "scriptEventPublisher must not be null"); + this.directTextConnectScopeSessionStore = + Objects.requireNonNull( + directTextConnectScopeSessionStore, + "directTextConnectScopeSessionStore must not be null"); + } + + public LogoutCommandHandler( + SessionAuthenticationService sessionAuthenticationService, + SessionContextService sessionContextService, + GameInstanceService gameInstanceService, + GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, + GameplayPresenceLifecycleService gameplayPresenceLifecycleService, + FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, + ScriptEventPublisher scriptEventPublisher) { + this( + sessionAuthenticationService, + sessionContextService, + gameInstanceService, + gameplayAdmissionPointerAuthorityService, + gameplayPresenceLifecycleService, + firstPartyConnectContextRegistry, + scriptEventPublisher, + new DirectTextConnectScopeSessionStore()); } public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) { @@ -83,6 +111,7 @@ public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) context.sessionId(), AccountRecentPresenceDisposition.LOGOUT); firstPartyConnectContextRegistry.unregister(context.sessionId()); sessionContextService.deleteBySessionId(context.tenantId(), context.sessionId()); + directTextConnectScopeSessionStore.clearSession(context.sessionId()); return new LogoutCommandHandlingResult( CommandEnqueueResult.success(), List.of(PlayerOutput.notice("Logged out.", "notice.logout.success", Map.of()))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 392ac0acf3..42bad054e1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -182,6 +182,9 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } GameplayWorldCatalog.WorldView selectedWorld = maybeWorld.get(); + if (!gameplayWorldCatalog.hasValidPublicProductionRealm(selectedWorld)) { + return admissionPointerUnavailableFailure(tenantTag, null); + } FirstPartyConnectContextResolution connectContextResolution = FirstPartyConnectContextResolution.resolve( context.sessionId(), context, firstPartyConnectContextRegistry); @@ -211,6 +214,10 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); String selectedTenantTag = Long.toString(selectedRealm.tenantId()); + if (!gameplayWorldCatalog.hasValidPublicProductionRealm(selectedRealm.tenantId())) { + return admissionPointerUnavailableFailure( + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); + } try (GameplayLoggingContext worldContext = GameplayLoggingContext.open( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), null, null)) { @@ -847,6 +854,19 @@ private PlayCommandHandlingResult authorityUnavailableFailure( null); } + private PlayCommandHandlingResult admissionPointerUnavailableFailure( + String tenantTag, String gameInstanceTag) { + return failure( + "ADMISSION_POINTER_UNAVAILABLE", + "Gameplay admission pointer is unavailable", + "error.play.authority-unavailable", + Map.of(), + tenantTag, + gameInstanceTag, + null, + null); + } + private PlayCommandHandlingResult entitlementUnavailableFailure( String tenantTag, String gameInstanceTag, long requestedCharacterId) { return failure( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java index 20181dc6b7..4cd2cfcc84 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommand.java @@ -59,6 +59,12 @@ public Optional realmBrowsePayload() { : Optional.empty(); } + public Optional joinRequestPayload() { + return payload instanceof TextCommandPayload.JoinRequest joinRequest + ? Optional.of(joinRequest) + : Optional.empty(); + } + public Optional characterBrowsePayload() { return payload instanceof TextCommandPayload.CharacterBrowseRequest browseRequest ? Optional.of(browseRequest) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java index 466d2e05c4..d0968ecf41 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java @@ -71,6 +71,7 @@ public TextCommand parse(String rawLine, TextCommandRegistry registry) { case WORLDS -> new ParsedCommandData(List.of(), new TextCommandPayload.ViewRequest("WORLDS", true)); case REALMS -> parseRealms(tokens); + case JOIN -> parseJoin(tokens); case CHARS -> parseChars(tokens); case LOGOUT -> new ParsedCommandData(List.of(), new TextCommandPayload.None()); case AFK -> parseAfk(tokens); @@ -151,6 +152,15 @@ private ParsedCommandData parseRealms(String[] tokens) { return new ParsedCommandData(args, new TextCommandPayload.Tokens(args)); } + private ParsedCommandData parseJoin(String[] tokens) { + List args = parseRemainingTokens(tokens); + if (TextCommandPayload.fromLegacy(TextCommandType.JOIN, args) + instanceof TextCommandPayload.JoinRequest joinRequest) { + return new ParsedCommandData(args, joinRequest); + } + return new ParsedCommandData(args, new TextCommandPayload.Tokens(args)); + } + private ParsedCommandData parseChars(String[] tokens) { List args = parseRemainingTokens(tokens); if (!args.isEmpty() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java index df8e5cfd65..023c4504f7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandPayload.java @@ -10,6 +10,7 @@ public sealed interface TextCommandPayload TextCommandPayload.Credentials, TextCommandPayload.EmailLoginChallengeRequest, TextCommandPayload.RealmBrowseRequest, + TextCommandPayload.JoinRequest, TextCommandPayload.CharacterBrowseRequest, TextCommandPayload.PlayRequest, TextCommandPayload.AfkRequest, @@ -37,6 +38,8 @@ record EmailLoginChallengeRequest(String email) implements TextCommandPayload {} record RealmBrowseRequest(String worldSelector) implements TextCommandPayload {} + record JoinRequest(String worldSelector) implements TextCommandPayload {} + record CharacterBrowseRequest(String worldSelector, String realmSelector) implements TextCommandPayload {} @@ -83,6 +86,10 @@ static TextCommandPayload fromLegacy(TextCommandType type, List args) { parseRealmBrowseRequest(safeArgs) .map(request -> request) .orElseGet(() -> safeArgs.isEmpty() ? new None() : new Tokens(safeArgs)); + case JOIN -> + parseJoinRequest(safeArgs) + .map(request -> request) + .orElseGet(() -> safeArgs.isEmpty() ? new None() : new Tokens(safeArgs)); case CHARS -> parseCharacterBrowseRequest(safeArgs) .map(request -> request) @@ -246,6 +253,16 @@ private static java.util.Optional parseRealmBrowseRequest(Li return java.util.Optional.of(new RealmBrowseRequest(worldSelector)); } + private static java.util.Optional parseJoinRequest(List args) { + if (args == null || args.size() != 1) { + return java.util.Optional.empty(); + } + String worldSelector = normalizeSelectorToken(args.getFirst()); + return StringUtils.hasText(worldSelector) + ? java.util.Optional.of(new JoinRequest(worldSelector)) + : java.util.Optional.empty(); + } + private static java.util.Optional parseCharacterBrowseRequest( List args) { if (args == null || args.isEmpty()) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java index b447c1966a..86abd56458 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandType.java @@ -6,6 +6,7 @@ public enum TextCommandType { WORLDS, REALMS, + JOIN, CHARS, LOGIN, LOGOUT, @@ -45,6 +46,7 @@ public static TextCommandType fromToken(String token) { return switch (normalized) { case "WORLDS" -> WORLDS; case "REALMS" -> REALMS; + case "JOIN" -> JOIN; case "CHARS" -> CHARS; case "LOGIN", "LOGON" -> LOGIN; case "LOGOUT", "LOGOFF", "QUIT" -> LOGOUT; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 680d7852c2..96dc4e22ee 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -1,14 +1,30 @@ package net.firedevops.firemud.gamesession.command.text; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @@ -21,12 +37,31 @@ public class WorldsCommandHandler { private final GameplayWorldCatalog worldCatalog; private final EntityManagementClient entityManagementClient; + private final AccountClient accountClient; + private final DirectTextConnectScopeSessionStore connectScopeSessionStore; + @Autowired public WorldsCommandHandler( + GameplayWorldCatalog worldCatalog, + EntityManagementClient entityManagementClient, + AccountClient accountClient, + DirectTextConnectScopeSessionStore connectScopeSessionStore) { + this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); + this.entityManagementClient = + Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); + this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); + this.connectScopeSessionStore = + Objects.requireNonNull( + connectScopeSessionStore, "connectScopeSessionStore must not be null"); + } + + WorldsCommandHandler( GameplayWorldCatalog worldCatalog, EntityManagementClient entityManagementClient) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); this.entityManagementClient = Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); + this.accountClient = null; + this.connectScopeSessionStore = new DirectTextConnectScopeSessionStore(); } public WorldsViewOutput browseView() { @@ -37,9 +72,375 @@ public java.util.Optional browseRealms(String worldSelect return worldCatalog.browseRealms(worldSelector); } + public RealmBrowseResult browseRealms(SessionContext sessionContext, String worldSelector) { + Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + return RealmBrowseResult.failure("LOGIN_REQUIRED"); + } + if (connectScopeSessionStore != null) { + connectScopeSessionStore.clearWorldScopes(sessionContext, worldSelector); + } + Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); + if (maybeWorld.isEmpty()) { + return RealmBrowseResult.invalidSelector(); + } + + GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); + if (!worldCatalog.hasValidPublicProductionRealm(world)) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + List visibleEntries = new ArrayList<>(); + List issuedScopes = new ArrayList<>(); + String requestId = sessionContext.sessionId() + ":" + UUID.randomUUID(); + for (GameplayWorldCatalog.RealmView realm : worldCatalog.visibleRealms(world)) { + if (!realm.publicProductionRealm()) { + NonPublicRealmAuthorization authorization = + authorizeNonPublicRealm(sessionContext, world, realm, requestId); + if (authorization == NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + if (authorization == NonPublicRealmAuthorization.ENTITLEMENT_UNAVAILABLE) { + return RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE"); + } + if (authorization != NonPublicRealmAuthorization.AUTHORIZED) { + continue; + } + } + if (realm.publicProductionRealm()) { + if (accountClient == null || connectScopeSessionStore == null) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + DirectTextConnectScopeTarget target = connectScopeTarget(world, realm); + if (target == null) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + PlayerExecutionContext playerContext = playerContext(sessionContext, realm); + IssueDirectTextConnectScopeResponse scopeResponse = + accountClient.issueDirectTextConnectScope(playerContext, target); + if (scopeResponse.hasError()) { + String errorCode = scopeResponse.getError().getCode(); + if ("REALM_UNAVAILABLE".equals(errorCode)) { + continue; + } + return RealmBrowseResult.failure(errorCode.isBlank() ? "AUTH_UNAVAILABLE" : errorCode); + } + if (scopeResponse.getConnectScopeId().isBlank()) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + Instant expiresAt; + try { + expiresAt = Instant.parse(scopeResponse.getConnectScopeExpiresAt()); + } catch (DateTimeParseException ex) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + if (!expiresAt.isAfter(Instant.now())) { + return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + } + issuedScopes.add( + new DirectTextConnectScopeSessionStore.ScopedRealm( + realm.slug(), true, scopeResponse.getConnectScopeId(), expiresAt, playerContext)); + } + visibleEntries.add(realmEntry(visibleEntries.size() + 1, realm)); + } + + connectScopeSessionStore.replaceWorldScopes( + sessionContext, worldSelector, world.slug(), issuedScopes); + return RealmBrowseResult.success(new RealmBrowseViewOutput(world.slug(), visibleEntries)); + } + + private NonPublicRealmAuthorization authorizeNonPublicRealm( + SessionContext sessionContext, + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmView realm, + String requestId) { + if (accountClient == null) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + GetTenantMembershipForRuntimeResponse membershipResponse = + accountClient.getTenantMembershipForRuntime( + Long.toString(sessionContext.accountId()), Long.toString(realm.tenantId()), requestId); + if (membershipResponse == null) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + if (membershipResponse.hasError()) { + if (!StringUtils.hasText(membershipResponse.getError().getCode())) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + return isAuthorityUnavailable(membershipResponse.getError().getCode()) + ? NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE + : NonPublicRealmAuthorization.DENIED; + } + if (!membershipResponse.getMembershipExists() + || !membershipResponse.getGameplayAdmissionAllowed() + || "INACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { + return NonPublicRealmAuthorization.ENROLLMENT_REQUIRED; + } + if (!isValidActiveMembership(membershipResponse, sessionContext, realm)) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + + GetRealmAccessGrantForRuntimeResponse grantResponse = + accountClient.getRealmAccessGrantForRuntime( + Long.toString(sessionContext.accountId()), + Long.toString(realm.tenantId()), + world.slug(), + realm.slug(), + requestId); + if (grantResponse == null) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + if (grantResponse.hasError()) { + if (!StringUtils.hasText(grantResponse.getError().getCode())) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + return isAuthorityUnavailable(grantResponse.getError().getCode()) + ? NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE + : NonPublicRealmAuthorization.DENIED; + } + if (!grantResponse.getGranted()) { + return NonPublicRealmAuthorization.DENIED; + } + if (!isValidGrant(grantResponse, sessionContext, world, realm)) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + + GetTenantEntitlementsForRuntimeResponse entitlementResponse = + accountClient.getTenantEntitlementsForRuntime( + Long.toString(realm.tenantId()), requestId); + if (entitlementResponse == null) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + if (entitlementResponse.hasError()) { + String errorCode = entitlementResponse.getError().getCode(); + if (!StringUtils.hasText(errorCode)) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + if (GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE.equalsIgnoreCase(errorCode)) { + return NonPublicRealmAuthorization.ENTITLEMENT_UNAVAILABLE; + } + return isAuthorityUnavailable(errorCode) + ? NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE + : NonPublicRealmAuthorization.DENIED; + } + if (!isValidEntitlement(entitlementResponse, realm)) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } + return entitlementResponse.getGameplayAvailable() + ? NonPublicRealmAuthorization.AUTHORIZED + : NonPublicRealmAuthorization.DENIED; + } + + private boolean isValidEntitlement( + GetTenantEntitlementsForRuntimeResponse response, + GameplayWorldCatalog.RealmView realm) { + return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) + && isInstant(response.getEvaluatedAt()); + } + + private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { + try { + return Long.parseLong(tenantId) == expectedTenantId; + } catch (NumberFormatException ex) { + return false; + } + } + + private boolean isValidActiveMembership( + GetTenantMembershipForRuntimeResponse response, + SessionContext sessionContext, + GameplayWorldCatalog.RealmView realm) { + return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) + && response.getMembershipVersion() > 0L + && response.getMembershipAuthorityGeneration() > 0L + && hasMatchingAuthorityIdentity( + response.getAccountId(), + response.getTenantId(), + sessionContext.accountId(), + realm.tenantId()) + && isInstant(response.getEvaluatedAt()); + } + + private boolean isValidGrant( + GetRealmAccessGrantForRuntimeResponse response, + SessionContext sessionContext, + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmView realm) { + return response.getGrantVersion() > 0L + && hasMatchingAuthorityIdentity( + response.getAccountId(), + response.getTenantId(), + sessionContext.accountId(), + realm.tenantId()) + && world.slug().equals(response.getWorldSlug()) + && realm.slug().equals(response.getRealmSlug()) + && isInstant(response.getEvaluatedAt()); + } + + private boolean hasMatchingAuthorityIdentity( + String accountId, String tenantId, long expectedAccountId, long expectedTenantId) { + try { + return Long.parseLong(accountId) == expectedAccountId + && Long.parseLong(tenantId) == expectedTenantId; + } catch (NumberFormatException ex) { + return false; + } + } + + private boolean isInstant(String value) { + if (!StringUtils.hasText(value)) { + return false; + } + try { + Instant.parse(value); + return true; + } catch (DateTimeParseException ex) { + return false; + } + } + + private boolean isAuthorityUnavailable(String code) { + return AuthenticationErrorCodes.UNAVAILABLE.equalsIgnoreCase(code) + || "UNAVAILABLE".equalsIgnoreCase(code); + } + + private enum NonPublicRealmAuthorization { + AUTHORIZED, + DENIED, + ENROLLMENT_REQUIRED, + AUTHORITY_UNAVAILABLE, + ENTITLEMENT_UNAVAILABLE + } + + public JoinMembershipResult joinPublicProductionMembership( + SessionContext sessionContext, String worldSelector) { + Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + return JoinMembershipResult.failure("LOGIN_REQUIRED"); + } + if (accountClient == null || connectScopeSessionStore == null) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); + if (maybeWorld.isEmpty()) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + if (!worldCatalog.hasValidPublicProductionRealm(maybeWorld.orElseThrow())) { + return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + Optional maybeJoinScope = + connectScopeSessionStore.publicProductionScopeForJoin( + sessionContext, worldSelector, Instant.now()); + if (maybeJoinScope.isEmpty()) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + DirectTextConnectScopeSessionStore.JoinScope joinScope = maybeJoinScope.orElseThrow(); + DirectTextConnectScopeSessionStore.ScopedRealm scope = joinScope.scope(); + String requestId = joinScope.requestId(); + PlayerExecutionContext playerContext = + scope.playerContext().toBuilder().setRequestId(requestId).build(); + return JoinMembershipResult.response( + accountClient.joinPublicProductionMembership( + playerContext, scope.connectScopeId(), requestId)); + } + + private DirectTextConnectScopeTarget connectScopeTarget( + GameplayWorldCatalog.WorldView world, GameplayWorldCatalog.RealmView realm) { + if (realm.tenantId() <= 0 + || realm.gameInstanceId() <= 0 + || realm.realmId() == null + || realm.playableStateNamespaceId() == null + || realm.catalogRevision() <= 0 + || realm.pointerVersion() <= 0 + || !"SHARED".equals(realm.stateScope()) && !"ISOLATED".equals(realm.stateScope())) { + return null; + } + return new DirectTextConnectScopeTarget( + Long.toString(realm.tenantId()), + world.slug(), + realm.slug(), + realm.realmId().toString(), + realm.playableStateNamespaceId().toString(), + realm.stateScope(), + Long.toString(realm.gameInstanceId()), + realm.catalogRevision(), + realm.pointerVersion()); + } + + private PlayerExecutionContext playerContext( + SessionContext caller, GameplayWorldCatalog.RealmView realm) { + return PlayerExecutionContext.newBuilder() + .setAccountId(Long.toString(caller.accountId())) + .setSessionId(Long.toString(caller.sessionId())) + .setTenantId(Long.toString(realm.tenantId())) + .setRealmId(realm.realmId().toString()) + .setPlayableStateNamespaceId(realm.playableStateNamespaceId().toString()) + .setPlayableStateScope(realm.stateScope()) + .setGameInstanceId(Long.toString(realm.gameInstanceId())) + .build(); + } + + private RealmBrowseViewOutput.RealmEntry realmEntry( + int ordinal, GameplayWorldCatalog.RealmView realm) { + return new RealmBrowseViewOutput.RealmEntry( + ordinal, + realm.slug(), + realm.displayName(), + realm.gameInstanceId(), + realm.requiresCharacterSelection(), + realm.stateScope(), + realm.characterCreationPolicy()); + } + + public sealed interface RealmBrowseResult + permits RealmBrowseResult.Success, + RealmBrowseResult.InvalidSelector, + RealmBrowseResult.Failure { + static RealmBrowseResult success(RealmBrowseViewOutput output) { + return new Success(output); + } + + static RealmBrowseResult invalidSelector() { + return new InvalidSelector(); + } + + static RealmBrowseResult failure(String code) { + return new Failure(code); + } + + record Success(RealmBrowseViewOutput output) implements RealmBrowseResult {} + + record InvalidSelector() implements RealmBrowseResult {} + + record Failure(String code) implements RealmBrowseResult {} + } + + public sealed interface JoinMembershipResult + permits JoinMembershipResult.Response, JoinMembershipResult.Failure { + static JoinMembershipResult response( + net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse response) { + return new Response(response); + } + + static JoinMembershipResult failure(String code) { + return new Failure(code); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf responses are immutable value messages.") + record Response( + net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse response) + implements JoinMembershipResult {} + + record Failure(String code) implements JoinMembershipResult {} + } + public CharacterBrowseResult browseCharacters( SessionContext sessionContext, String worldSelector, String realmSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + return CharacterBrowseResult.failure("LOGIN_REQUIRED"); + } java.util.Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); if (maybeWorld.isEmpty()) { @@ -60,6 +461,21 @@ public CharacterBrowseResult browseCharacters( } GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); + if (!worldCatalog.hasValidPublicProductionRealm(realm.tenantId()) + || !hasCompleteSelectedRealmPointerEvidence(realm)) { + return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + + String requestId = sessionContext.sessionId() + ":" + UUID.randomUUID(); + CharacterBrowseAuthorization authorization = + realm.publicProductionRealm() + ? authorizePublicCharacterBrowse(sessionContext, realm, requestId) + : mapNonPublicCharacterAuthorization( + authorizeNonPublicRealm(sessionContext, world, realm, requestId)); + if (authorization != CharacterBrowseAuthorization.AUTHORIZED) { + return CharacterBrowseResult.failure(authorization.code()); + } + ListCharactersByAccountResponse response = entityManagementClient.listCharactersByAccount( Long.toString(realm.tenantId()), @@ -86,12 +502,162 @@ public CharacterBrowseResult browseCharacters( entries)); } + private CharacterBrowseAuthorization authorizePublicCharacterBrowse( + SessionContext sessionContext, + GameplayWorldCatalog.RealmView realm, + String requestId) { + if (accountClient == null) { + return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; + } + GetTenantMembershipForRuntimeResponse membershipResponse = + accountClient.getTenantMembershipForRuntime( + Long.toString(sessionContext.accountId()), Long.toString(realm.tenantId()), requestId); + if (membershipResponse == null) { + return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; + } + if (membershipResponse.hasError()) { + String errorCode = membershipResponse.getError().getCode(); + if (!StringUtils.hasText(errorCode)) { + return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; + } + return isAuthorityUnavailable(errorCode) + ? CharacterBrowseAuthorization.AUTH_UNAVAILABLE + : CharacterBrowseAuthorization.DENIED; + } + if (!isValidMembershipAuthoritySnapshot(membershipResponse, sessionContext, realm)) { + return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; + } + + PublicEntitlementAuthorization entitlementAuthorization = + authorizePublicCharacterEntitlement(realm, requestId); + if (entitlementAuthorization.authorization() != CharacterBrowseAuthorization.AUTHORIZED) { + return entitlementAuthorization.authorization(); + } + if (!membershipResponse.getMembershipExists() + || !membershipResponse.getGameplayAdmissionAllowed() + || !"ACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { + return entitlementAuthorization.allowPublicJoin() + ? CharacterBrowseAuthorization.JOIN_REQUIRED + : CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; + } + if (!isValidActiveMembership(membershipResponse, sessionContext, realm)) { + return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; + } + return CharacterBrowseAuthorization.AUTHORIZED; + } + + private PublicEntitlementAuthorization authorizePublicCharacterEntitlement( + GameplayWorldCatalog.RealmView realm, String requestId) { + if (accountClient == null) { + return new PublicEntitlementAuthorization( + CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); + } + GetTenantEntitlementsForRuntimeResponse entitlementResponse = + accountClient.getTenantEntitlementsForRuntime(Long.toString(realm.tenantId()), requestId); + if (entitlementResponse == null) { + return new PublicEntitlementAuthorization( + CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); + } + if (entitlementResponse.hasError()) { + String errorCode = entitlementResponse.getError().getCode(); + if (!StringUtils.hasText(errorCode)) { + return new PublicEntitlementAuthorization( + CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); + } + if (GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE.equalsIgnoreCase(errorCode)) { + return new PublicEntitlementAuthorization( + CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE, false); + } + return new PublicEntitlementAuthorization( + isAuthorityUnavailable(errorCode) + ? CharacterBrowseAuthorization.AUTH_UNAVAILABLE + : CharacterBrowseAuthorization.DENIED, + false); + } + if (!isValidEntitlement(entitlementResponse, realm)) { + return new PublicEntitlementAuthorization( + CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); + } + if (!entitlementResponse.getGameplayAvailable()) { + return new PublicEntitlementAuthorization( + CharacterBrowseAuthorization.TENANT_BILLING_BLOCKED, false); + } + return new PublicEntitlementAuthorization( + CharacterBrowseAuthorization.AUTHORIZED, entitlementResponse.getAllowPublicJoin()); + } + + private CharacterBrowseAuthorization mapNonPublicCharacterAuthorization( + NonPublicRealmAuthorization authorization) { + return switch (authorization) { + case AUTHORIZED -> CharacterBrowseAuthorization.AUTHORIZED; + case DENIED -> CharacterBrowseAuthorization.DENIED; + case ENROLLMENT_REQUIRED -> CharacterBrowseAuthorization.NON_PUBLIC_ENROLLMENT_REQUIRED; + case AUTHORITY_UNAVAILABLE -> CharacterBrowseAuthorization.AUTH_UNAVAILABLE; + case ENTITLEMENT_UNAVAILABLE -> CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE; + }; + } + + private boolean isValidMembershipAuthoritySnapshot( + GetTenantMembershipForRuntimeResponse response, + SessionContext sessionContext, + GameplayWorldCatalog.RealmView realm) { + if (!hasMatchingAuthorityIdentity( + response.getAccountId(), + response.getTenantId(), + sessionContext.accountId(), + realm.tenantId()) + || !isInstant(response.getEvaluatedAt())) { + return false; + } + if (!response.getMembershipExists()) { + return response.getMembershipVersion() == 0L + && response.getMembershipAuthorityGeneration() == 0L; + } + return response.getMembershipVersion() > 0L + && response.getMembershipAuthorityGeneration() > 0L + && StringUtils.hasText(response.getMembershipLifecycleState()); + } + + private boolean hasCompleteSelectedRealmPointerEvidence( + GameplayWorldCatalog.RealmView realm) { + return realm.visible() + && realm.tenantId() > 0L + && realm.gameInstanceId() > 0L + && realm.pointerVersion() > 0L + && StringUtils.hasText(realm.slug()); + } + + private enum CharacterBrowseAuthorization { + AUTHORIZED(null), + JOIN_REQUIRED("JOIN_REQUIRED"), + DENIED("WORLD_ACCESS_DENIED"), + PUBLIC_PRODUCTION_ADMISSION_DENIED("PUBLIC_PRODUCTION_ADMISSION_DENIED"), + NON_PUBLIC_ENROLLMENT_REQUIRED("NON_PUBLIC_ENROLLMENT_REQUIRED"), + TENANT_BILLING_BLOCKED("TENANT_BILLING_BLOCKED"), + AUTH_UNAVAILABLE("AUTH_UNAVAILABLE"), + ENTITLEMENT_UNAVAILABLE("ENTITLEMENT_UNAVAILABLE"); + + private final String code; + + CharacterBrowseAuthorization(String code) { + this.code = code; + } + + private String code() { + return code; + } + } + + private record PublicEntitlementAuthorization( + CharacterBrowseAuthorization authorization, boolean allowPublicJoin) {} + public sealed interface CharacterBrowseResult permits CharacterBrowseResult.Success, CharacterBrowseResult.InvalidWorld, CharacterBrowseResult.InvalidRealm, CharacterBrowseResult.RealmSelectionRequired, - CharacterBrowseResult.Unavailable { + CharacterBrowseResult.Unavailable, + CharacterBrowseResult.Failure { static CharacterBrowseResult success(CharacterBrowseViewOutput output) { return new Success(output); } @@ -112,6 +678,10 @@ static CharacterBrowseResult unavailable() { return new Unavailable(); } + static CharacterBrowseResult failure(String code) { + return new Failure(code); + } + record Success(CharacterBrowseViewOutput output) implements CharacterBrowseResult {} record InvalidWorld() implements CharacterBrowseResult {} @@ -121,6 +691,8 @@ record InvalidRealm(String worldSlug) implements CharacterBrowseResult {} record RealmSelectionRequired(String worldSlug) implements CharacterBrowseResult {} record Unavailable() implements CharacterBrowseResult {} + + record Failure(String code) implements CharacterBrowseResult {} } private PlayableStateScope toPlayableStateScope(GameplayWorldCatalog.RealmView realm) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index d2433f654d..6d8631b370 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -34,7 +34,8 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( worldsHandler.browseView()))); - case REALMS -> handleRealms(request.command()); + case REALMS -> handleRealms(request); + case JOIN -> handleJoin(request); case CHARS -> handleChars(request); default -> new TextCommandInterpretationResult( @@ -44,7 +45,7 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request net.firedevops.firemud.gamesession.presentation.PlayerOutput.error( "INVALID_ARGUMENT", "Unsupported discovery command"))); }; - if (result.commandResult().accepted()) { + if (result.commandResult().accepted() && request.command().type() != TextCommandType.JOIN) { request .sessionContext() .ifPresent(context -> publishCommandEvent(context, request.command())); @@ -52,21 +53,82 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request return result; } - private TextCommandInterpretationResult handleRealms(TextCommand command) { - return command - .realmBrowsePayload() - .flatMap(payload -> worldsHandler.browseRealms(payload.worldSelector())) - .map( - view -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view(view)))) - .orElseGet( - () -> - errorResult( - "INVALID_ARGUMENT", - "REALMS requires a valid world selector. Use WORLDS first.")); + private TextCommandInterpretationResult handleRealms(TextCommandDispatchRequest request) { + if (request.command().realmBrowsePayload().isEmpty() || request.sessionContext().isEmpty()) { + return errorResult("INVALID_ARGUMENT", "REALMS requires a world selector after LOGIN."); + } + TextCommandPayload.RealmBrowseRequest payload = + request.command().realmBrowsePayload().orElseThrow(); + return switch (worldsHandler.browseRealms( + request.sessionContext().orElseThrow(), payload.worldSelector())) { + case WorldsCommandHandler.RealmBrowseResult.Success success -> + new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( + success.output()))); + case WorldsCommandHandler.RealmBrowseResult.InvalidSelector ignored -> + errorResult( + "INVALID_ARGUMENT", "REALMS requires a valid world selector. Use WORLDS first."); + case WorldsCommandHandler.RealmBrowseResult.Failure failure -> + errorResult(failure.code(), realmBrowseFailureMessage(failure.code())); + }; + } + + private TextCommandInterpretationResult handleJoin(TextCommandDispatchRequest request) { + if (request.command().joinRequestPayload().isEmpty() || request.sessionContext().isEmpty()) { + return errorResult("INVALID_ARGUMENT", "JOIN requires a world selector after LOGIN."); + } + TextCommandPayload.JoinRequest payload = request.command().joinRequestPayload().orElseThrow(); + return switch (worldsHandler.joinPublicProductionMembership( + request.sessionContext().orElseThrow(), payload.worldSelector())) { + case WorldsCommandHandler.JoinMembershipResult.Failure failure -> + errorResult(failure.code(), joinFailureMessage(failure.code())); + case WorldsCommandHandler.JoinMembershipResult.Response response -> + handleJoinResponse(response.response()); + }; + } + + private TextCommandInterpretationResult handleJoinResponse( + net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse response) { + if (response.hasError()) { + String code = response.getError().getCode(); + if (code.isBlank()) { + code = "JOIN_FAILED"; + } + return errorResult(code, joinFailureMessage(code)); + } + if (!response.getSuccess()) { + String code = response.getOutcomeCode().isBlank() ? "JOIN_FAILED" : response.getOutcomeCode(); + return errorResult(code, joinFailureMessage(code)); + } + return new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.notice( + "Membership is ready. Continue with CHARS and PLAY."))); + } + + private String realmBrowseFailureMessage(String code) { + return switch (code) { + case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> + "Realm authority unavailable. Retry REALMS shortly."; + case "CONNECT_SCOPE_MISMATCH", "ADMISSION_POINTER_UNAVAILABLE" -> + "Realm routing changed or is unavailable. Retry REALMS."; + default -> "Realm selection is unavailable."; + }; + } + + private String joinFailureMessage(String code) { + return switch (code) { + case "CONNECT_SCOPE_MISMATCH" -> "Join scope expired or changed. Run REALMS again."; + case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> + "Account authority unavailable. Retry JOIN shortly."; + case "ENTITLEMENT_UNAVAILABLE" -> + "Join policy could not be checked. Use REALMS and JOIN to start a new attempt later."; + case "LOGIN_REQUIRED" -> "Log in before joining a world."; + default -> "The selected world could not be joined."; + }; } private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest request) { @@ -98,12 +160,35 @@ private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest r "Selection required. Use REALMS " + realmSelectionRequired.worldSlug() + " before CHARS."); + case WorldsCommandHandler.CharacterBrowseResult.Failure failure -> + errorResult(failure.code(), characterBrowseFailureMessage(failure.code())); case WorldsCommandHandler.CharacterBrowseResult.Unavailable ignored -> errorResult( "CHARACTER_LIST_UNAVAILABLE", "Character list unavailable. Retry CHARS shortly."); }; } + private String characterBrowseFailureMessage(String code) { + return switch (code) { + case "LOGIN_REQUIRED" -> "Log in before browsing characters."; + case "JOIN_REQUIRED" -> "Membership is required before CHARS. Use JOIN first."; + case "WORLD_ACCESS_DENIED" -> "You are not allowed to browse characters in that realm."; + case "NON_PUBLIC_ENROLLMENT_REQUIRED" -> + "Existing membership is required before browsing characters in that realm."; + case "PUBLIC_PRODUCTION_ADMISSION_DENIED" -> + "Public joining is not available for this world."; + case "TENANT_BILLING_BLOCKED" -> + "That world is temporarily unavailable for gameplay."; + case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> + "Character authority unavailable. Retry CHARS shortly."; + case "ENTITLEMENT_UNAVAILABLE" -> + "Gameplay entitlement is temporarily unavailable. Retry CHARS shortly."; + case "ADMISSION_POINTER_UNAVAILABLE" -> + "Realm routing changed or is unavailable. Retry REALMS, then CHARS."; + default -> "Character selection is unavailable."; + }; + } + private TextCommandInterpretationResult errorResult(String code, String message) { return new TextCommandInterpretationResult( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.failure(code, message), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java index 235349c833..27163a0068 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -13,6 +14,9 @@ public class GameplayAdmissionPointer { private Long tenantId; private Long gameInstanceId; private Long pointerVersion; + private Long catalogRevision; + private UUID realmId; + private UUID playableStateNamespaceId; private boolean visible; private boolean publicProductionRealm; private boolean requiresCharacterSelection; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index a01611bf45..e67eefd155 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -3,10 +3,13 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointer.GAMEPLAY_ADMISSION_POINTER; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayTenantSharedPlayableStateNamespace.GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerRecord; @@ -73,11 +76,19 @@ public List findAllByOrderByWorldSlugAscRealmSlugAsc() public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { if (entity.getId() == null) { + if (!"SHARED".equals(entity.getStateScope()) && !"ISOLATED".equals(entity.getStateScope())) { + throw new IllegalArgumentException("state_scope must be SHARED or ISOLATED"); + } lockRuntimeTargetForCreation(entity); if (countByRuntimeTarget(entity.getTenantId(), entity.getGameInstanceId()) != 0) { throw new IllegalStateException( "Admission pointer creation conflicted with another route for the runtime target"); } + entity.setRealmId(UUID.randomUUID()); + entity.setPlayableStateNamespaceId( + "SHARED".equals(entity.getStateScope()) + ? getOrCreateTenantSharedNamespace(entity.getTenantId()) + : UUID.randomUUID()); GameplayAdmissionPointerRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER); populate(record, entity); try { @@ -109,6 +120,12 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { "Admission pointer changed before the requested version could be committed: id=" + entity.getId()); } + if (!Objects.equals(entity.getRealmId(), current.getRealmId()) + || !Objects.equals( + entity.getPlayableStateNamespaceId(), current.getPlayableStateNamespaceId())) { + throw new IllegalStateException( + "Admission pointer update cannot replace durable realm or playable-state identity"); + } long destinationCount = countByRuntimeTargetExcludingId( entity.getTenantId(), entity.getGameInstanceId(), entity.getId()); @@ -127,6 +144,7 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { .set(GAMEPLAY_ADMISSION_POINTER.TENANT_ID, entity.getTenantId()) .set(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION, entity.getPointerVersion()) + .set(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION, entity.getCatalogRevision()) .set(GAMEPLAY_ADMISSION_POINTER.VISIBLE, entity.isVisible()) .set( GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM, @@ -228,6 +246,33 @@ private void lockRuntimeTargetForCreation(GameplayAdmissionPointer entity) { lockRuntimeTarget(runtimeTargetLockKey(entity.getTenantId(), entity.getGameInstanceId())); } + private UUID getOrCreateTenantSharedNamespace(Long tenantId) { + lockRuntimeTarget("tenant-shared-playable-state:" + tenantId); + var table = GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; + UUID namespace = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (namespace != null) { + return namespace; + } + dsl.insertInto(table) + .set(table.TENANT_ID, tenantId) + .set(table.PLAYABLE_STATE_NAMESPACE_ID, UUID.randomUUID()) + .onDuplicateKeyIgnore() + .execute(); + UUID allocated = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (allocated == null) { + throw new IllegalStateException("Tenant shared playable-state namespace allocation failed"); + } + return allocated; + } + private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPointer entity) { record.setWorldSlug(entity.getWorldSlug()); record.setWorldDisplayName(entity.getWorldDisplayName()); @@ -236,6 +281,9 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setPointerVersion(entity.getPointerVersion()); + record.setCatalogRevision(entity.getCatalogRevision()); + record.setRealmId(entity.getRealmId()); + record.setPlayableStateNamespaceId(entity.getPlayableStateNamespaceId()); record.setVisible(entity.isVisible()); record.setPublicProductionRealm(entity.isPublicProductionRealm()); record.setRequiresCharacterSelection(entity.isRequiresCharacterSelection()); @@ -257,6 +305,10 @@ private GameplayAdmissionPointer toEntity(Record record) { entity.setTenantId(record.get(GAMEPLAY_ADMISSION_POINTER.TENANT_ID)); entity.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID)); entity.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION)); + entity.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION)); + entity.setRealmId(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_ID)); + entity.setPlayableStateNamespaceId( + record.get(GAMEPLAY_ADMISSION_POINTER.PLAYABLE_STATE_NAMESPACE_ID)); entity.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.VISIBLE))); entity.setPublicProductionRealm( Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java new file mode 100644 index 0000000000..e362bbc763 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Holds Account-issued direct-text scopes only for the transport session that resolved them. */ +@Component +public final class DirectTextConnectScopeSessionStore { + private final ConcurrentMap scopesBySessionId = new ConcurrentHashMap<>(); + + public void replaceWorldScopes( + SessionContext caller, + String requestedWorldSelector, + String canonicalWorldSlug, + List scopes) { + Objects.requireNonNull(caller, "caller must not be null"); + requireCallerIdentity(caller); + String requestedSelector = normalizeSelector(requestedWorldSelector); + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (requestedSelector == null || worldSlug == null) { + throw new IllegalArgumentException("world selectors must not be blank"); + } + List safeScopes = + List.copyOf(Objects.requireNonNull(scopes, "scopes must not be null")); + if (safeScopes.stream().anyMatch(scope -> scope.playerContext().getAccountId().isBlank())) { + throw new IllegalArgumentException("scope caller identity must not be blank"); + } + safeScopes.forEach( + scope -> { + if (!scope.playerContext().getAccountId().equals(Long.toString(caller.accountId())) + || !scope.playerContext().getSessionId().equals(Long.toString(caller.sessionId()))) { + throw new IllegalArgumentException("scope caller identity did not match session"); + } + }); + + scopesBySessionId.compute( + caller.sessionId(), + (sessionId, existing) -> { + Map> byWorld = new HashMap<>(); + Map worldBySelector = new HashMap<>(); + if (existing != null && existing.accountId() == caller.accountId()) { + byWorld.putAll(existing.scopesByWorld()); + worldBySelector.putAll(existing.worldBySelector()); + } + byWorld.put(worldSlug, safeScopes); + worldBySelector.put(worldSlug, worldSlug); + worldBySelector.put(requestedSelector, worldSlug); + return new SessionScopes( + caller.accountId(), Map.copyOf(byWorld), Map.copyOf(worldBySelector)); + }); + } + + public void clearWorldScopes(SessionContext caller, String worldSelector) { + Objects.requireNonNull(caller, "caller must not be null"); + String selector = normalizeSelector(worldSelector); + if (selector == null) { + return; + } + scopesBySessionId.computeIfPresent( + caller.sessionId(), + (sessionId, existing) -> { + if (existing.accountId() != caller.accountId()) { + return null; + } + String worldSlug = existing.worldBySelector().get(selector); + if (worldSlug == null) { + return existing; + } + Map> byWorld = new HashMap<>(existing.scopesByWorld()); + byWorld.remove(worldSlug); + Map worldBySelector = new HashMap<>(existing.worldBySelector()); + worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); + if (byWorld.isEmpty()) { + return null; + } + return new SessionScopes( + existing.accountId(), Map.copyOf(byWorld), Map.copyOf(worldBySelector)); + }); + } + + public Optional publicProductionScope( + SessionContext caller, String worldSelector, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); + requireCallerIdentity(caller); + String selector = normalizeSelector(worldSelector); + if (selector == null) { + return Optional.empty(); + } + SessionScopes sessionScopes = scopesBySessionId.get(caller.sessionId()); + if (sessionScopes == null || sessionScopes.accountId() != caller.accountId()) { + if (sessionScopes != null) { + scopesBySessionId.remove(caller.sessionId(), sessionScopes); + } + return Optional.empty(); + } + String canonicalWorldSlug = sessionScopes.worldBySelector().get(selector); + if (canonicalWorldSlug == null) { + return Optional.empty(); + } + List validScopes = + sessionScopes.scopesByWorld().getOrDefault(canonicalWorldSlug, List.of()).stream() + .filter(scope -> scope.expiresAt().isAfter(now)) + .toList(); + List publicScopes = + validScopes.stream().filter(ScopedRealm::publicProductionRealm).toList(); + return publicScopes.size() == 1 ? Optional.of(publicScopes.getFirst()) : Optional.empty(); + } + + /** + * Resolves a public scope and atomically binds one stable JOIN request ID to that scope. Repeated + * JOIN commands reuse the ID; a fresh REALMS response replaces the scope and starts a new logical + * attempt. + */ + public Optional publicProductionScopeForJoin( + SessionContext caller, String worldSelector, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); + requireCallerIdentity(caller); + String selector = normalizeSelector(worldSelector); + if (selector == null) { + return Optional.empty(); + } + AtomicReference selected = new AtomicReference<>(); + scopesBySessionId.computeIfPresent( + caller.sessionId(), + (sessionId, sessionScopes) -> { + if (sessionScopes.accountId() != caller.accountId()) { + return sessionScopes; + } + String worldSlug = sessionScopes.worldBySelector().get(selector); + if (worldSlug == null) { + return sessionScopes; + } + List scopes = + sessionScopes.scopesByWorld().getOrDefault(worldSlug, List.of()); + List validPublicScopes = + scopes.stream() + .filter(scope -> scope.expiresAt().isAfter(now)) + .filter(ScopedRealm::publicProductionRealm) + .toList(); + if (validPublicScopes.size() != 1) { + return sessionScopes; + } + + ScopedRealm scope = validPublicScopes.getFirst(); + String requestId = scope.joinRequestId(); + ScopedRealm boundScope = scope; + if (requestId.isBlank()) { + requestId = UUID.randomUUID().toString(); + boundScope = scope.withJoinRequestId(requestId); + } + + if (boundScope != scope) { + ScopedRealm updatedScope = boundScope; + List updatedScopes = + scopes.stream() + .map( + candidate -> + candidate.connectScopeId().equals(scope.connectScopeId()) + ? updatedScope + : candidate) + .toList(); + Map> byWorld = new HashMap<>(sessionScopes.scopesByWorld()); + byWorld.put(worldSlug, updatedScopes); + sessionScopes = + new SessionScopes( + sessionScopes.accountId(), byWorld, sessionScopes.worldBySelector()); + } + selected.set(new JoinScope(boundScope, requestId)); + return sessionScopes; + }); + return Optional.ofNullable(selected.get()); + } + + public void clearSession(long sessionId) { + scopesBySessionId.remove(sessionId); + } + + @Scheduled(fixedDelay = 60_000L) + void removeExpiredScopes() { + Instant now = Instant.now(); + scopesBySessionId.forEach( + (sessionId, current) -> { + Map> remainingByWorld = new HashMap<>(); + current + .scopesByWorld() + .forEach( + (worldSlug, worldScopes) -> { + List remaining = + worldScopes.stream() + .filter(scope -> scope.expiresAt().isAfter(now)) + .toList(); + if (!remaining.isEmpty()) { + remainingByWorld.put(worldSlug, remaining); + } + }); + if (remainingByWorld.isEmpty()) { + scopesBySessionId.remove(sessionId, current); + return; + } + Map remainingSelectors = new HashMap<>(current.worldBySelector()); + remainingSelectors + .entrySet() + .removeIf(entry -> !remainingByWorld.containsKey(entry.getValue())); + SessionScopes updated = + new SessionScopes( + current.accountId(), + Map.copyOf(remainingByWorld), + Map.copyOf(remainingSelectors)); + scopesBySessionId.replace(sessionId, current, updated); + }); + } + + private void requireCallerIdentity(SessionContext caller) { + if (caller.accountId() <= 0 || caller.sessionId() <= 0) { + throw new IllegalArgumentException( + "authenticated account and transport session are required"); + } + } + + private String normalizeSelector(String selector) { + if (selector == null || selector.isBlank()) { + return null; + } + return selector.trim().toLowerCase(Locale.ROOT); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf execution contexts are immutable value messages.") + public record ScopedRealm( + String realmSlug, + boolean publicProductionRealm, + String connectScopeId, + Instant expiresAt, + PlayerExecutionContext playerContext, + String joinRequestId) { + public ScopedRealm( + String realmSlug, + boolean publicProductionRealm, + String connectScopeId, + Instant expiresAt, + PlayerExecutionContext playerContext) { + this(realmSlug, publicProductionRealm, connectScopeId, expiresAt, playerContext, ""); + } + + public ScopedRealm { + if (realmSlug == null || realmSlug.isBlank()) { + throw new IllegalArgumentException("realmSlug must not be blank"); + } + if (connectScopeId == null || connectScopeId.isBlank()) { + throw new IllegalArgumentException("connectScopeId must not be blank"); + } + Objects.requireNonNull(expiresAt, "expiresAt must not be null"); + Objects.requireNonNull(playerContext, "playerContext must not be null"); + joinRequestId = joinRequestId == null ? "" : joinRequestId; + } + + private ScopedRealm withJoinRequestId(String requestId) { + return new ScopedRealm( + realmSlug, publicProductionRealm, connectScopeId, expiresAt, playerContext, requestId); + } + } + + public record JoinScope(ScopedRealm scope, String requestId) { + public JoinScope { + Objects.requireNonNull(scope, "scope must not be null"); + if (requestId == null || requestId.isBlank()) { + throw new IllegalArgumentException("requestId must not be blank"); + } + } + } + + private record SessionScopes( + long accountId, + Map> scopesByWorld, + Map worldBySelector) { + private SessionScopes { + Map> safeWorlds = new HashMap<>(); + scopesByWorld.forEach((slug, scopes) -> safeWorlds.put(slug, List.copyOf(scopes))); + scopesByWorld = Map.copyOf(safeWorlds); + worldBySelector = Map.copyOf(worldBySelector); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java index 91fa8e464f..5b0a879615 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.service; +import java.util.UUID; + public record GameplayAdmissionPointerSnapshot( String worldSlug, String worldDisplayName, @@ -12,4 +14,70 @@ public record GameplayAdmissionPointerSnapshot( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic snapshot without catalog identity/revision authority. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic snapshot without catalog authority for legacy test fixtures. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index baa71c65e1..c1c216b5cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -78,9 +78,15 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu && pointer.getTenantId() != mutation.tenantId()) { throw new IllegalArgumentException("tenant_id does not own admission pointer"); } + if (pointer.getId() != null + && !Objects.equals(pointer.getStateScope(), mutation.stateScope())) { + throw new IllegalArgumentException( + "state_scope changes require a new playable-state lifecycle"); + } enforceExpectedPointerVersion(pointer, mutation.expectedPointerVersion()); long nextPointerVersion = pointer.getId() == null ? 1L : Math.max(pointer.getPointerVersion() + 1L, 1L); + long nextCatalogRevision = nextCatalogRevision(pointer, mutation); pointer.setWorldSlug(mutation.worldSlug()); pointer.setWorldDisplayName(mutation.worldDisplayName()); pointer.setRealmSlug(mutation.realmSlug()); @@ -88,6 +94,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu pointer.setTenantId(mutation.tenantId()); pointer.setGameInstanceId(mutation.gameInstanceId()); pointer.setPointerVersion(nextPointerVersion); + pointer.setCatalogRevision(nextCatalogRevision); pointer.setVisible(mutation.visible()); pointer.setPublicProductionRealm(mutation.publicProductionRealm()); pointer.setRequiresCharacterSelection(mutation.requiresCharacterSelection()); @@ -167,7 +174,38 @@ private GameplayAdmissionPointerSnapshot toSnapshot(GameplayAdmissionPointer poi pointer.isPublicProductionRealm(), pointer.isRequiresCharacterSelection(), pointer.getStateScope(), - pointer.getCharacterCreationPolicy()); + pointer.getCharacterCreationPolicy(), + pointer.getCatalogRevision() == null ? 0L : pointer.getCatalogRevision(), + pointer.getRealmId(), + pointer.getPlayableStateNamespaceId()); + } + + private long nextCatalogRevision( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + if (pointer.getId() == null) { + return 1L; + } + Long currentRevision = pointer.getCatalogRevision(); + if (currentRevision == null || currentRevision <= 0L) { + throw new IllegalStateException("Admission pointer catalog revision is missing or invalid"); + } + if (!catalogPolicyMatches(pointer, mutation)) { + return Math.addExact(currentRevision, 1L); + } + return currentRevision; + } + + private boolean catalogPolicyMatches( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + return Objects.equals(pointer.getWorldSlug(), mutation.worldSlug()) + && Objects.equals(pointer.getWorldDisplayName(), mutation.worldDisplayName()) + && Objects.equals(pointer.getRealmSlug(), mutation.realmSlug()) + && Objects.equals(pointer.getRealmDisplayName(), mutation.realmDisplayName()) + && pointer.isVisible() == mutation.visible() + && pointer.isPublicProductionRealm() == mutation.publicProductionRealm() + && pointer.isRequiresCharacterSelection() == mutation.requiresCharacterSelection() + && Objects.equals(pointer.getStateScope(), mutation.stateScope()) + && Objects.equals(pointer.getCharacterCreationPolicy(), mutation.characterCreationPolicy()); } private void validateMutation(GameplayAdmissionPointerMutation mutation) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index f39849a79b..6ff329d7c1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -545,12 +545,24 @@ public void listGameplayRealms( gameplayWorldCatalog .resolveWorld(request.getWorldSlug()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); + if (!gameplayWorldCatalog.hasValidPublicProductionRealm(world)) { + throw new CatalogRevisionUnavailableException( + "Authoritative public-production realm cardinality is invalid"); + } + List realms = + gameplayWorldCatalog.visibleRealms(world).stream() + .map(realm -> toGameplayRealm(world.slug(), realm)) + .toList(); + ListGameplayRealmsResponse response = + ListGameplayRealmsResponse.newBuilder().addAllRealms(realms).build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (CatalogRevisionUnavailableException ex) { ListGameplayRealmsResponse response = ListGameplayRealmsResponse.newBuilder() - .addAllRealms( - gameplayWorldCatalog.visibleRealms(world).stream() - .map(realm -> toGameplayRealm(world.slug(), realm)) - .toList()) + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -592,10 +604,24 @@ public void getAdmissionPointer( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity( + realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (CatalogRevisionUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() @@ -778,9 +804,35 @@ private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity(realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build(); } + private static String requireIdentity(java.util.UUID identity, String fieldName) { + if (identity == null) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay " + fieldName + " is missing"); + } + return identity.toString(); + } + + private static long requireCatalogRevision(long catalogRevision) { + if (catalogRevision <= 0L) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay catalog revision is missing or invalid"); + } + return catalogRevision; + } + + private static final class CatalogRevisionUnavailableException extends RuntimeException { + private CatalogRevisionUnavailableException(String message) { + super(message); + } + } + private static final class AuthorizationException extends RuntimeException { private AuthorizationException(String message) { super(message); diff --git a/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql new file mode 100644 index 0000000000..63e5cd1ce1 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql @@ -0,0 +1,4 @@ +ALTER TABLE gameplay_admission_pointer + ADD COLUMN catalog_revision bigint NOT NULL DEFAULT 1, + ADD CONSTRAINT gameplay_admission_pointer_catalog_revision_positive + CHECK (catalog_revision > 0); diff --git a/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql b/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql new file mode 100644 index 0000000000..41effca0d0 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql @@ -0,0 +1,74 @@ +-- A tenant's shared playable-state namespace is allocated once and reused by every +-- SHARED realm. Isolated realms receive independent namespace UUIDs. +CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id bigint PRIMARY KEY, + playable_state_namespace_id uuid NOT NULL UNIQUE, + allocated_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_tenant_shared_playable_state_namespace ( + tenant_id, + playable_state_namespace_id +) +SELECT shared_tenants.tenant_id, gen_random_uuid() +FROM ( + SELECT DISTINCT pointer.tenant_id + FROM gameplay_admission_pointer pointer + WHERE pointer.state_scope = 'SHARED' +) shared_tenants; + +ALTER TABLE gameplay_admission_pointer + ADD COLUMN realm_id uuid, + ADD COLUMN playable_state_namespace_id uuid; + +-- Retained rows with an exact known state scope can be classified without using +-- the replaceable game_instance_id as identity. Unknown legacy values remain +-- explicitly unresolved below. +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = ( + SELECT shared_namespace.playable_state_namespace_id + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.tenant_id = gameplay_admission_pointer.tenant_id + ) +WHERE state_scope = 'SHARED'; + +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = gen_random_uuid() +WHERE state_scope = 'ISOLATED'; + +CREATE TABLE gameplay_admission_pointer_identity_backfill_issue ( + pointer_id bigint PRIMARY KEY, + tenant_id bigint NOT NULL, + world_slug character varying(120) NOT NULL, + realm_slug character varying(120) NOT NULL, + prior_state_scope character varying(32), + issue_code character varying(64) NOT NULL, + recorded_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_admission_pointer_identity_backfill_issue ( + pointer_id, + tenant_id, + world_slug, + realm_slug, + prior_state_scope, + issue_code +) +SELECT id, + tenant_id, + world_slug, + realm_slug, + state_scope, + 'UNKNOWN_PLAYABLE_STATE_SCOPE' +FROM gameplay_admission_pointer +WHERE state_scope IS NULL OR state_scope NOT IN ('SHARED', 'ISOLATED'); + +ALTER TABLE gameplay_admission_pointer + ADD CONSTRAINT gameplay_admission_pointer_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); + +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_realm_id + ON gameplay_admission_pointer (realm_id) + WHERE realm_id IS NOT NULL; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 155d484a7b..5d84ceca3b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -27,6 +27,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -34,6 +38,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -41,6 +46,102 @@ class AccountClientTest { + @Test + void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + IssueDirectTextConnectScopeResponse expected = + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("account-issued-scope") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build(); + when(stub.issueDirectTextConnectScope(any(IssueDirectTextConnectScopeRequest.class))) + .thenReturn(expected); + AccountClient client = newClient(stub); + PlayerExecutionContext context = directTextContext("request-unused"); + DirectTextConnectScopeTarget target = + new DirectTextConnectScopeTarget( + "22", + "demo-world", + "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "42d234a2-7487-4dda-a7e5-a3831214328e", + "SHARED", + "9", + 7L, + 4L); + + IssueDirectTextConnectScopeResponse actual = + client.issueDirectTextConnectScope(context, target); + + assertThat(actual).isEqualTo(expected); + ArgumentCaptor captor = + ArgumentCaptor.forClass(IssueDirectTextConnectScopeRequest.class); + verify(stub).issueDirectTextConnectScope(captor.capture()); + assertThat(captor.getValue().getPlayerContext().getAccountId()).isEqualTo("41"); + assertThat(captor.getValue().getPlayerContext().getSessionId()).isEqualTo("7"); + assertThat(captor.getValue().getTenantId()).isEqualTo("22"); + assertThat(captor.getValue().getWorldSlug()).isEqualTo("demo-world"); + assertThat(captor.getValue().getRealmId()).isEqualTo(target.realmId()); + assertThat(captor.getValue().getPlayableStateNamespaceId()) + .isEqualTo(target.playableStateNamespaceId()); + assertThat(captor.getValue().getPlayableStateScope()).isEqualTo("SHARED"); + assertThat(captor.getValue().getGameInstanceId()).isEqualTo("9"); + assertThat(captor.getValue().getCatalogRevision()).isEqualTo(7L); + assertThat(captor.getValue().getPointerVersion()).isEqualTo(4L); + } + + @Test + void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { + RetryFixture fixture = newRetryFixture(); + when(fixture + .initialStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + JoinPublicProductionMembershipResponse expected = + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("CREATED") + .build(); + when(fixture + .retryStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenReturn(expected); + AccountClient client = fixture.client(); + PlayerExecutionContext context = directTextContext("join-request-1"); + + JoinPublicProductionMembershipResponse actual = + client.joinPublicProductionMembership(context, "account-issued-scope", "join-request-1"); + + assertThat(actual).isEqualTo(expected); + ArgumentCaptor firstCaptor = + ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + ArgumentCaptor retryCaptor = + ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + verify(fixture.initialStub()).joinPublicProductionMembership(firstCaptor.capture()); + verify(fixture.retryStub()).joinPublicProductionMembership(retryCaptor.capture()); + assertThat(firstCaptor.getValue()).isEqualTo(retryCaptor.getValue()); + assertThat(retryCaptor.getValue().getConnectScopeId()).isEqualTo("account-issued-scope"); + assertThat(retryCaptor.getValue().getRequestId()).isEqualTo("join-request-1"); + assertThat(retryCaptor.getValue().getPlayerContext().getRequestId()) + .isEqualTo("join-request-1"); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + private static PlayerExecutionContext directTextContext(String requestId) { + return PlayerExecutionContext.newBuilder() + .setAccountId("41") + .setSessionId("7") + .setTenantId("22") + .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") + .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") + .setPlayableStateScope("SHARED") + .setGameInstanceId("9") + .setRequestId(requestId) + .build(); + } + @Test void authenticateReturnsUnavailableWhenStubIsNotInitialized() throws Exception { AuthenticateResponse response = newClient(null).authenticate("demo@example.com", "swordfish"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index f14c14301c..a54d8aea9a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -167,6 +167,89 @@ void normalizeWorldsDropsRealmViewsWithoutSlugsBeforeAdmissionLookup() { assertThat(catalog.resolveRealmForAdmission(normalizedWorld, "invalid")).isEmpty(); } + @Test + void publicProductionCardinalityCountsExactlyOneAcrossTheTenantCatalogue() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("demo", "production", 7L, true), + worldWithRealm("preview", "preview", 7L, false))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())) + .isPresent(); + } + + @Test + void publicProductionCardinalityFailsClosedWhenTenantHasNoPublicRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of(worldWithRealm("preview", "preview", 7L, false))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.ZERO); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("preview").orElseThrow())) + .isEmpty(); + } + + @Test + void publicProductionCardinalityCountsSameTenantCandidatesAcrossWorlds() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("demo", "production", 7L, true), + worldWithRealm("alternate", "production", 7L, true))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())) + .isEmpty(); + } + + @Test + void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 0L, + 0L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"))))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())) + .isPresent(); + } + + @Test + void numericWorldSelectionUsesTheSameFilteredSetAsWorldBrowsePresentation() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("invalid", "preview", 7L, false), + worldWithRealm("demo", "production", 8L, true))); + + assertThat(catalog.browseView().worlds()) + .extracting( + net.firedevops.firemud.gamesession.presentation.WorldsViewOutput.WorldEntry::slug) + .containsExactly("demo"); + assertThat(catalog.resolveWorld("1").orElseThrow().slug()).isEqualTo("demo"); + assertThat(catalog.resolveWorld("invalid")).isPresent(); + } + private static GameplayWorldCatalog.WorldView worldWithTargetRealm( String realmSlug, boolean visible) { return new GameplayWorldCatalog.WorldView( @@ -188,6 +271,25 @@ private static GameplayWorldCatalog.WorldView worldWithTargetRealm( "ALLOW_NEW"))); } + private static GameplayWorldCatalog.WorldView worldWithRealm( + String worldSlug, String realmSlug, long tenantId, boolean publicProduction) { + return new GameplayWorldCatalog.WorldView( + worldSlug, + worldSlug, + List.of( + new GameplayWorldCatalog.RealmView( + realmSlug, + realmSlug, + tenantId, + 11L, + 1L, + true, + publicProduction, + false, + "SHARED", + "ALLOW_NEW"))); + } + private static GameplayAdmissionPointerSnapshot pointer( String worldSlug, String worldDisplayName, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 9b38159a98..feeccfb89c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -26,6 +26,9 @@ void helpWithoutTopicShowsTopicIndex() { assertTrue(result.outputs().get(0).text().contains("HELP MOVEMENT")); assertTrue(result.outputs().get(0).text().contains("HELP SAY")); assertTrue(result.outputs().get(0).text().contains("HELP WHO")); + assertTrue(result.outputs().get(0).text().contains("HELP REALMS")); + assertTrue(result.outputs().get(0).text().contains("HELP JOIN")); + assertTrue(result.outputs().get(0).text().contains("HELP CHARS")); assertTrue(result.outputs().get(0).text().contains("HELP INVENTORY")); assertTrue(result.outputs().get(0).text().contains("HELP EQUIPMENT")); } @@ -47,6 +50,17 @@ void helpWhoTopicExplainsGameplayOnlyScope() { assertTrue(result.outputs().get(0).text().contains("You must already be in-world with PLAY.")); } + @Test + void helpJoinExplainsTheExplicitPublicMembershipStep() { + TextCommandInterpretationResult result = + handler.handle(new TextCommand(TextCommandType.HELP, List.of("join"), "HELP join")); + + assertTrue(result.commandResult().accepted()); + assertTrue(result.outputs().get(0).text().contains("JOIN ")); + assertTrue(result.outputs().get(0).text().contains("public-production membership")); + assertTrue(result.outputs().get(0).text().contains("Use REALMS first")); + } + @Test void helpFriendsTopicExplainsVisibilityReadAndWriteSurface() { TextCommandInterpretationResult result = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 6f9274fad8..1ba3bea2ac 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -78,6 +78,14 @@ void setUp() { List.of( realm("production", "Live Realm", 22L, 2L, true, true), realm("preview", "Preview Realm", 22L, 41L, true, true))))); + // The catalogue contract permits one public-production realm per tenant. Keep the sandbox + // production realm non-public so these tests can exercise its explicit non-public path. + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(false); handler = new PlayCommandHandler( sessionAuthenticationService, @@ -228,6 +236,49 @@ void playPromotesSessionIntoGameplay() { "play-spawn:1:1:7001:1"); } + @Test + void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(true); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); + } + + @Test + void playFailsClosedWhenTenantHasNoPublicProductionRealm() { + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(false); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); + } + @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 43b755f2cb..237e6571a1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -518,15 +518,15 @@ void worldsAreVisibleBeforeLogin() { } @Test - void realmsAreVisibleAfterLogin() { + void privateRealmsAreNotDisclosedWithoutAuthority() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "REALMS demo", false); - assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("REALMS demo", interpretation).contains("Live Realm")); - assertTrue(renderedResponse("REALMS demo", interpretation).contains("[shared, allow_new]")); + assertFalse(interpretation.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", interpretation.commandResult().errorCode()); + assertFalse(renderedResponse("REALMS demo", interpretation).contains("Live Realm")); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java index 5dc7755cb2..7c2a88a113 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java @@ -46,6 +46,39 @@ void parsesOneArgumentLoginAsEmailChallengeRequest() { assertEquals("demo@example.com", payload.email()); } + @Test + void parsesJoinAsOneAdapterLocalWorldSelector() { + TextCommand command = parser.parse("JOIN tenant-a/world-a"); + + assertEquals(TextCommandType.JOIN, command.type()); + assertEquals(List.of("tenant-a/world-a"), command.args()); + assertEquals(new TextCommandPayload.JoinRequest("tenant-a/world-a"), command.payload()); + } + + @Test + void rejectsJoinWithoutExactlyOneWorldSelector() { + TextCommand missingSelector = parser.parse("JOIN"); + TextCommand extraArguments = parser.parse("JOIN world-a realm-b"); + + assertEquals(TextCommandType.JOIN, missingSelector.type()); + assertFalse(missingSelector.joinRequestPayload().isPresent()); + assertEquals(TextCommandType.JOIN, extraArguments.type()); + assertFalse(extraArguments.joinRequestPayload().isPresent()); + } + + @Test + void resolvesJoinThroughTheBuiltInAuthenticatedWorldDispatchDefinition() { + TextCommandDefinition definition = + new BuiltInTextCommandDefinitionProvider() + .definitions().stream() + .filter(candidate -> candidate.type() == TextCommandType.JOIN) + .findFirst() + .orElseThrow(); + + assertEquals(TextCommandDispatchGroup.WORLDS, definition.dispatchGroup()); + assertEquals(TextCommandStageRequirement.LOGIN, definition.stageRequirement()); + } + @Test void rejectsLegacyThreeArgumentLoginShape() { TextCommand command = parser.parse("LOGIN demo@example.com swordfish 123456"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 223d2a85d2..01aaeb611d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2,14 +2,23 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.time.Instant; +import java.util.ArrayList; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.Test; @@ -27,6 +36,12 @@ class WorldsCommandHandlerTest { @Test void browseViewReturnsStructuredWorldList() { + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(false); WorldsViewOutput response = handler.browseView(); assertThat(response.worlds()).hasSize(2); @@ -71,6 +86,15 @@ void browseRealmsToleratesNullRealmEnums() { void browseCharactersReturnsStructuredCharacterList() { gameplayCatalogProperties.setWorlds( List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(false); + addPublicProductionAuthority(gameplayCatalogProperties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubActivePrivateAuthorization(accountClient, "demo"); Mockito.when( entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -83,9 +107,10 @@ void browseCharactersReturnsStructuredCharacterList() { .setLevel(12) .build()) .build()); + WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = - handler.browseCharacters( + localHandler.browseCharacters( new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), "demo", null); @@ -117,6 +142,9 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .getFirst() .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); + addPublicProductionAuthority(gameplayCatalogProperties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubActivePrivateAuthorization(accountClient, "demo"); Mockito.when( entityManagementClient.listCharactersByAccount( "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) @@ -129,9 +157,10 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .setLevel(5) .build()) .build()); + WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = - handler.browseCharacters( + localHandler.browseCharacters( new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), "demo", null); @@ -150,14 +179,15 @@ void browseCharactersUsesIsolatedStateRealmRoster() { void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); + addPublicProductionAuthority(gameplayCatalogProperties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubActivePrivateAuthorization(accountClient, "demo"); Mockito.when( entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED)) .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); WorldsCommandHandler localHandler = - new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); + authenticatedHandler(gameplayCatalogProperties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( @@ -168,6 +198,645 @@ void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); } + @Test + void browseCharactersReturnsJoinRequiredForPublicNonMemberWithoutReadingEntityRoster() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("demo", 22L, 1L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("JOIN_REQUIRED")); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEntityRoster() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("demo", 22L, 1L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo( + new WorldsCommandHandler.CharacterBrowseResult.Failure( + "PUBLIC_PRODUCTION_ADMISSION_DENIED")); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void browseCharactersReturnsUnavailableEntitlementBeforeReadingPublicEntityRoster() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("demo", 22L, 1L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("ENTITLEMENT_UNAVAILABLE") + .setMessage("Entitlement authority unavailable") + .build()) + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo( + new WorldsCommandHandler.CharacterBrowseResult.Failure( + "ENTITLEMENT_UNAVAILABLE")); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void browseCharactersDeniesRevokedPrivateMembershipBeforeReadingEntityRoster() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + activeMembership().toBuilder() + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("INACTIVE") + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "preview", "production"); + + assertThat(result) + .isEqualTo( + new WorldsCommandHandler.CharacterBrowseResult.Failure( + "NON_PUBLIC_ENROLLMENT_REQUIRED")); + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + @Test + void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoster() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(false)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "preview", "production"); + + assertThat(result) + .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("WORLD_ACCESS_DENIED")); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "preview", "production"); + + assertThat(result) + .isEqualTo( + new WorldsCommandHandler.CharacterBrowseResult.Failure( + "ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + + @Test + void browseCharactersRejectsMultiplePublicProductionCardinalityWithExplicitRealm() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds( + List.of(world("demo", 22L, 1L, false), world("alternate", 22L, 2L, false))); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo( + new WorldsCommandHandler.CharacterBrowseResult.Failure( + "ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + + @Test + void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRoster() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("demo", 22L, 1L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(false) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + Mockito.verify(entityManagementClient) + .listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + @Test + void authenticatedBrowseOmitsPrivateRealmForNonMember() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder().setMembershipExists(false).build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) + .isEmpty(); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + @Test + void authenticatedBrowseOmitsPrivateRealmWithoutExactGrant() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(false)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) + .isEmpty(); + } + + @Test + void authenticatedBrowseFailsClosedWhenMembershipAuthorityUnavailable() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE") + .build()) + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + } + + @Test + void authenticatedBrowseIncludesPrivateRealmForActiveMemberWithExactGrant() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(true)); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + } + + @Test + void authenticatedBrowseRejectsPrivateRealmWhenEntitlementTenantDoesNotMatch() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(true)); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("23") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + } + + @Test + void authenticatedBrowseOmitsPrivateRealmWhenGameplayEntitlementIsUnavailable() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(true)); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(false) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) + .isEmpty(); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + } + + @Test + void authenticatedBrowseFailsClosedWhenGameplayEntitlementIsUnavailable() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(true)); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("ENTITLEMENT_UNAVAILABLE") + .setMessage("Entitlement authority unavailable") + .build()) + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + } + + @Test + void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembership() { + UUID realmId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + GameplayWorldCatalog.RealmView realm = + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + realmId, + namespaceId); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-1") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews( + List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "demo"); + + assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void authenticatedBrowseFailsClosedWhenTenantHasNoPublicProductionRealm() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "preview"); + + assertThat(result) + .isEqualTo( + WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); + } + + @Test + void authenticatedBrowseFailsClosedWhenPublicProductionRealmIsDuplicatedAcrossWorlds() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds( + List.of(world("demo", 22L, 1L, false), world("alternate", 22L, 2L, false))); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "demo"); + + assertThat(result) + .isEqualTo( + WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); + } + + private WorldsCommandHandler authenticatedHandler( + GameplayCatalogProperties properties, AccountClient accountClient) { + return new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(properties), + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()); + } + + private void addPublicProductionAuthority(GameplayCatalogProperties properties) { + GameplayCatalogProperties.World authority = world("production-authority", 22L, 1L, false); + authority.getRealms().getFirst().setPublicProductionRealm(true); + List worlds = new ArrayList<>(properties.getWorlds()); + worlds.add(authority); + properties.setWorlds(worlds); + } + + private SessionContext authenticatedSession() { + return new SessionContext(7L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + } + + private GetTenantMembershipForRuntimeResponse activeMembership() { + return GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build(); + } + + private GetTenantEntitlementsForRuntimeResponse publicEntitlement(boolean allowPublicJoin) { + return GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(allowPublicJoin) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build(); + } + + private GetRealmAccessGrantForRuntimeResponse grant(boolean granted) { + return grant("preview", granted); + } + + private GetRealmAccessGrantForRuntimeResponse grant( + String worldSlug, boolean granted) { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setWorldSlug(worldSlug) + .setRealmSlug("production") + .setGranted(granted) + .setGrantVersion(granted ? 1L : 0L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build(); + } + + private void stubActivePrivateAuthorization(AccountClient accountClient, String worldSlug) { + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq(worldSlug), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(worldSlug, true)); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + } + private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 1b955207e9..7079fe626f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -5,13 +5,22 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; @@ -64,12 +73,66 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { @Test void publishesCommandEventForGameplayScopedRealmsBrowse() { + gameplayCatalogProperties.setWorlds( + List.of(world("sandbox", 1L, 2L, false), world("authority", 1L, 1L, false))); + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("41") + .setTenantId("1") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId("41") + .setTenantId("1") + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setGranted(true) + .setGrantVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("1") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()), + scriptEventPublisher); SessionContext context = new SessionContext( 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = - handler.handle( + scopedHandler.handle( new TextCommandDispatchRequest( "session-1", new TextCommand(TextCommandType.REALMS, List.of("sandbox"), "REALMS sandbox"), @@ -93,6 +156,34 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { @Test void publishesCommandEventForGameplayScopedCharsBrowse() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); when(entityManagementClient.listCharactersByAccount( "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( @@ -108,8 +199,16 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { new SessionContext( 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()), + scriptEventPublisher); TextCommandInterpretationResult result = - handler.handle( + scopedHandler.handle( new TextCommandDispatchRequest( "session-1", new TextCommand(TextCommandType.CHARS, List.of("demo"), "CHARS demo"), @@ -130,6 +229,64 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { && "CHARS demo".equals(gameplayCommand.getCommandText()))); } + @Test + void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity() { + gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()), + scriptEventPublisher); + SessionContext context = + new SessionContext( + 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + + TextCommandInterpretationResult result = + scopedHandler.handle( + new TextCommandDispatchRequest( + "session-1", + new TextCommand(TextCommandType.CHARS, List.of("demo", "production"), "CHARS demo production"), + false, + Optional.of(context))); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("JOIN_REQUIRED"); + assertThat(result.outputs()).singleElement().extracting(output -> output.payload()).isNotNull(); + Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + } + @Test void skipsCommandEventWithoutGameplayContext() { TextCommandInterpretationResult result = @@ -144,6 +301,129 @@ void skipsCommandEventWithoutGameplayContext() { Mockito.verifyNoInteractions(scriptEventPublisher); } + @Test + void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + DirectTextConnectScopeSessionStore scopeStore = new DirectTextConnectScopeSessionStore(); + UUID realmId = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + UUID namespaceId = UUID.fromString("42d234a2-7487-4dda-a7e5-a3831214328e"); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo-world", + "Demo World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 9L, + 4L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 7L, + realmId, + namespaceId))))); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore), + scriptEventPublisher); + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-account-scope") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build()); + when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("AUTH_UNAVAILABLE") + .build(), + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("CREATED") + .build()); + SessionContext context = + new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + + TextCommandInterpretationResult realmsResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.REALMS, List.of("demo-world"), "REALMS demo-world"), + false, + Optional.of(context))); + TextCommandInterpretationResult firstJoinResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); + TextCommandInterpretationResult retryJoinResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); + + assertThat(realmsResult.commandResult().accepted()).isTrue(); + assertThat(firstJoinResult.commandResult().accepted()).isFalse(); + assertThat(retryJoinResult.commandResult().accepted()).isTrue(); + assertThat(realmsResult.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isInstanceOf(RealmBrowseViewOutput.class); + org.mockito.ArgumentCaptor + callerCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + org.mockito.ArgumentCaptor targetCaptor = + org.mockito.ArgumentCaptor.forClass(DirectTextConnectScopeTarget.class); + Mockito.verify(accountClient) + .issueDirectTextConnectScope(callerCaptor.capture(), targetCaptor.capture()); + assertThat(callerCaptor.getValue().getAccountId()).isEqualTo("41"); + assertThat(callerCaptor.getValue().getSessionId()).isEqualTo("7"); + assertThat(targetCaptor.getValue().realmId()).isEqualTo(realmId.toString()); + assertThat(targetCaptor.getValue().catalogRevision()).isEqualTo(7L); + assertThat(targetCaptor.getValue().pointerVersion()).isEqualTo(4L); + + org.mockito.ArgumentCaptor + joinContextCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + org.mockito.ArgumentCaptor scopeIdCaptor = + org.mockito.ArgumentCaptor.forClass(String.class); + org.mockito.ArgumentCaptor requestIdCaptor = + org.mockito.ArgumentCaptor.forClass(String.class); + Mockito.verify(accountClient, Mockito.times(2)) + .joinPublicProductionMembership( + joinContextCaptor.capture(), scopeIdCaptor.capture(), requestIdCaptor.capture()); + List joinContexts = + joinContextCaptor.getAllValues(); + List scopeIds = scopeIdCaptor.getAllValues(); + List requestIds = requestIdCaptor.getAllValues(); + assertThat(scopeIds.getFirst()).isEqualTo("opaque-account-scope"); + assertThat(requestIds.getFirst()).isNotBlank(); + assertThat(requestIds.getLast()).isEqualTo(requestIds.getFirst()); + assertThat(scopeIds.getLast()).isEqualTo(scopeIds.getFirst()); + assertThat(joinContexts.getFirst().getRequestId()).isEqualTo(requestIds.getFirst()); + assertThat(joinContexts.getFirst().getAccountId()).isEqualTo("41"); + assertThat(joinContexts.getFirst().getSessionId()).isEqualTo("7"); + assertThat(joinContexts.getFirst().getRealmId()).isEqualTo(realmId.toString()); + assertThat(joinContexts.getLast()).isEqualTo(joinContexts.getFirst()); + Mockito.verify(scriptEventPublisher) + .publishCommandEvent( + Mockito.eq(context), + Mockito.argThat(gameplayCommand -> "REALMS".equals(gameplayCommand.getCommandName()))); + } + private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..cce6340463 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameplayAdmissionPointerRepositoryTest { + @Test + void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + + GameplayAdmissionPointer shared = pointer(7L, 44L, "SHARED", "production"); + GameplayAdmissionPointer createdShared = repository.save(shared); + UUID sharedRealmId = createdShared.getRealmId(); + UUID sharedNamespaceId = createdShared.getPlayableStateNamespaceId(); + GameplayAdmissionPointer sharedReadback = + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); + + GameplayAdmissionPointer secondShared = + repository.save(pointer(7L, 45L, "SHARED", "seasonal")); + GameplayAdmissionPointer isolated = repository.save(pointer(7L, 46L, "ISOLATED", "playtest")); + + assertNotNull(sharedRealmId); + assertNotNull(sharedNamespaceId); + assertEquals(sharedRealmId, sharedReadback.getRealmId()); + assertEquals(sharedNamespaceId, sharedReadback.getPlayableStateNamespaceId()); + assertNotNull(secondShared.getRealmId()); + assertNotNull(isolated.getRealmId()); + assertEquals(sharedNamespaceId, secondShared.getPlayableStateNamespaceId()); + assertNotEquals(sharedRealmId, secondShared.getRealmId()); + assertNotEquals(sharedNamespaceId, isolated.getPlayableStateNamespaceId()); + + createdShared.setGameInstanceId(99L); + createdShared.setPointerVersion(2L); + createdShared.setCatalogRevision(1L); + GameplayAdmissionPointer replaced = repository.save(createdShared); + + assertEquals(99L, replaced.getGameInstanceId()); + assertEquals(sharedRealmId, replaced.getRealmId()); + assertEquals(sharedNamespaceId, replaced.getPlayableStateNamespaceId()); + } + } + + @Test + void repositoryRejectsAttemptToReplaceStableRealmIdentity() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity-immutable;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + GameplayAdmissionPointer created = repository.save(pointer(7L, 44L, "ISOLATED", "fork")); + + created.setPointerVersion(2L); + created.setRealmId(UUID.randomUUID()); + + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, () -> repository.save(created)); + } + } + + private static GameplayAdmissionPointer pointer( + long tenantId, long gameInstanceId, String stateScope, String realmSlug) { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setWorldSlug("demo"); + pointer.setWorldDisplayName("Demo World"); + pointer.setRealmSlug(realmSlug); + pointer.setRealmDisplayName(realmSlug); + pointer.setTenantId(tenantId); + pointer.setGameInstanceId(gameInstanceId); + pointer.setPointerVersion(1L); + pointer.setCatalogRevision(1L); + pointer.setVisible(true); + pointer.setPublicProductionRealm("production".equals(realmSlug)); + pointer.setRequiresCharacterSelection(false); + pointer.setStateScope(stateScope); + pointer.setCharacterCreationPolicy("ALLOW_NEW"); + pointer.setLastUpdatedBy("test"); + pointer.setLastUpdateReason("test"); + pointer.setCreatedAt(Instant.parse("2026-09-24T00:00:00Z")); + pointer.setUpdatedAt(Instant.parse("2026-09-24T00:00:00Z")); + return pointer; + } + + private static void createSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id BIGINT PRIMARY KEY, + playable_state_namespace_id UUID NOT NULL UNIQUE, + allocated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + """); + dsl.execute( + """ + CREATE TABLE gameplay_admission_pointer ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + realm_slug VARCHAR(120) NOT NULL, + realm_display_name VARCHAR(200) NOT NULL, + tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + realm_id UUID, + playable_state_namespace_id UUID, + visible BOOLEAN NOT NULL, + public_production_realm BOOLEAN NOT NULL, + requires_character_selection BOOLEAN NOT NULL, + state_scope VARCHAR(32) NOT NULL, + character_creation_policy VARCHAR(32) NOT NULL, + last_updated_by VARCHAR(200) NOT NULL, + last_update_reason VARCHAR(500) NOT NULL, + created_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP NOT NULL, + CONSTRAINT uq_pointer_tenant_world_realm UNIQUE (tenant_id, world_slug, realm_slug), + CONSTRAINT uq_pointer_tenant_runtime UNIQUE (tenant_id, game_instance_id) + ) + """); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java new file mode 100644 index 0000000000..1faab651a6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.List; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; + +class DirectTextConnectScopeSessionStoreTest { + private final DirectTextConnectScopeSessionStore store = new DirectTextConnectScopeSessionStore(); + + @Test + void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { + SessionContext caller = session(7L, 41L); + Instant expiry = Instant.parse("2030-01-01T00:00:00Z"); + store.replaceWorldScopes( + caller, + "1", + "demo-world", + List.of(scopedRealm(caller, "demo-world", "scope-secret", expiry))); + + assertThat(store.publicProductionScope(caller, "1", Instant.parse("2029-01-01T00:00:00Z"))) + .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("scope-secret")); + assertThat( + store.publicProductionScope( + session(8L, 41L), "1", Instant.parse("2029-01-01T00:00:00Z"))) + .isEmpty(); + assertThat( + store.publicProductionScope( + session(7L, 42L), "1", Instant.parse("2029-01-01T00:00:00Z"))) + .isEmpty(); + } + + @Test + void refusesExpiredAndAmbiguousPublicScopes() { + SessionContext caller = session(7L, 41L); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of( + scopedRealm( + caller, "production", "expired-scope", Instant.parse("2029-01-01T00:00:00Z")))); + + assertThat( + store.publicProductionScope( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z"))) + .isEmpty(); + + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of( + scopedRealm(caller, "production-a", "scope-a", Instant.parse("2031-01-01T00:00:00Z")), + scopedRealm(caller, "production-b", "scope-b", Instant.parse("2031-01-01T00:00:00Z")))); + + assertThat( + store.publicProductionScope( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z"))) + .isEmpty(); + } + + @Test + void clearsPriorScopeBeforeReplacingTheWorldBinding() { + SessionContext caller = session(7L, 41L); + store.replaceWorldScopes( + caller, + "1", + "demo-world", + List.of( + scopedRealm( + caller, "production", "scope-secret", Instant.parse("2031-01-01T00:00:00Z")))); + + store.clearWorldScopes(caller, "1"); + + assertThat(store.publicProductionScope(caller, "1", Instant.parse("2030-01-01T00:00:00Z"))) + .isEmpty(); + } + + @Test + void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { + SessionContext caller = session(7L, 41L); + Instant expiry = Instant.parse("2031-01-01T00:00:00Z"); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of(scopedRealm(caller, "production", "scope-first", expiry))); + + DirectTextConnectScopeSessionStore.JoinScope firstAttempt = + store + .publicProductionScopeForJoin( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) + .orElseThrow(); + DirectTextConnectScopeSessionStore.JoinScope retryAttempt = + store + .publicProductionScopeForJoin( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) + .orElseThrow(); + + assertThat(firstAttempt.requestId()).isEqualTo(retryAttempt.requestId()); + assertThat(firstAttempt.scope().connectScopeId()) + .isEqualTo(retryAttempt.scope().connectScopeId()); + + store.clearWorldScopes(caller, "demo-world"); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of(scopedRealm(caller, "production", "scope-second", expiry))); + DirectTextConnectScopeSessionStore.JoinScope newAttempt = + store + .publicProductionScopeForJoin( + caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) + .orElseThrow(); + + assertThat(newAttempt.scope().connectScopeId()).isEqualTo("scope-second"); + assertThat(newAttempt.requestId()).isNotEqualTo(firstAttempt.requestId()); + } + + private static SessionContext session(long sessionId, long accountId) { + return new SessionContext(sessionId, 22L, accountId, 7001L, 9L, "jwt"); + } + + private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( + SessionContext caller, String realmSlug, String scopeId, Instant expiry) { + PlayerExecutionContext playerContext = + PlayerExecutionContext.newBuilder() + .setAccountId(Long.toString(caller.accountId())) + .setSessionId(Long.toString(caller.sessionId())) + .setTenantId("22") + .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") + .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") + .setPlayableStateScope("SHARED") + .setGameInstanceId("9") + .build(); + return new DirectTextConnectScopeSessionStore.ScopedRealm( + realmSlug, true, scopeId, expiry, playerContext); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index ae5d5933b0..f84933a724 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -38,6 +38,7 @@ void upsertPointerRejectsMismatchedExpectedVersion() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); existing.setId(11L); existing.setPointerVersion(3L); + existing.setStateScope("SHARED"); when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) .thenReturn(Optional.of(existing)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 27318cf7ba..98c270825e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -18,13 +18,18 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; @@ -440,36 +445,26 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); - world.setSlug("demo"); - world.setDisplayName("Demo World"); - GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); - realm.setSlug("production"); - realm.setDisplayName("Live Realm"); - realm.setTenantId(7L); - realm.setGameInstanceId(999L); - realm.setPointerVersion(999L); - realm.setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - world.setRealms(List.of(realm)); - properties.setWorlds(List.of(world)); + GameplayAdmissionPointerSnapshot authoritativeSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "ISOLATED", + "COPIED_ONLY", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn( - java.util.Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 7L, - 44L, - 17L, - true, - false, - false, - "ISOLATED", - "COPIED_ONLY"))); + .thenReturn(java.util.Optional.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -478,7 +473,7 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { textCommandInterpreter, gameInstanceRepository, pointerAuthorityService, - TestGameplayWorldCatalogs.fromProperties(properties), + new GameplayWorldCatalog(pointerAuthorityService), tickService, meterRegistry, ipLimiter); @@ -504,6 +499,12 @@ public void onCompleted() {} assertEquals(1, realmsRef.get().getRealmsCount()); assertEquals("production", realmsRef.get().getRealms(0).getRealmSlug()); assertEquals("ISOLATED", realmsRef.get().getRealms(0).getStateScope()); + assertEquals(17L, realmsRef.get().getRealms(0).getPointerVersion()); + assertEquals(29L, realmsRef.get().getRealms(0).getCatalogRevision()); + assertEquals("8a1df0f1-1b57-465e-9c4b-bb34f8153d31", realmsRef.get().getRealms(0).getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + realmsRef.get().getRealms(0).getPlayableStateNamespaceId()); AtomicReference pointerRef = new AtomicReference<>(); service.getAdmissionPointer( @@ -529,9 +530,350 @@ public void onCompleted() {} assertEquals("44", pointerRef.get().getAdmissionPointer().getGameInstanceId()); assertEquals(17L, pointerRef.get().getAdmissionPointer().getPointerVersion()); + assertEquals(29L, pointerRef.get().getAdmissionPointer().getCatalogRevision()); + assertEquals( + "8a1df0f1-1b57-465e-9c4b-bb34f8153d31", + pointerRef.get().getAdmissionPointer().getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); Mockito.verify(pointerAuthorityService).findPointer(7L, "demo", "production"); } + @Test + void gameplayCatalogRpcFailsClosedWhenTenantHasNoPublicProductionRealm() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot privateRealm = + catalogPointer("demo", "production", 7L, 44L, 17L, false); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(privateRealm)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "demo"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + } + + @Test + void gameplayCatalogRpcFailsClosedWhenTenantHasPublicRealmsAcrossWorlds() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot firstRealm = + catalogPointer("demo", "production", 7L, 44L, 17L, true); + GameplayAdmissionPointerSnapshot secondRealm = + catalogPointer("alternate", "production", 7L, 45L, 18L, true); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(firstRealm, secondRealm)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "demo"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + } + + @Test + void missingCatalogRevisionFailsClosedForCatalogAndAdmissionPointerReads() { + PingService pingService = Mockito.mock(PingService.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); + TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + TickService tickService = Mockito.mock(TickService.class); + IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + GameplayAdmissionPointerSnapshot missingRevision = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingRevision)); + GameSessionGrpcService service = + newService( + pingService, + gameInstanceService, + featureFlagService, + textCommandInterpreter, + gameInstanceRepository, + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + tickService, + meterRegistry, + ipLimiter); + + AtomicReference realmsRef = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + realmsRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realmsRef.get().getError().getCode()); + assertEquals(0, realmsRef.get().getRealmsCount()); + + AtomicReference pointerRef = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerRef.get().getError().getCode()); + assertFalse(pointerRef.get().hasAdmissionPointer()); + } + + private static ListGameplayRealmsResponse listGameplayRealms( + GameSessionGrpcService service, String worldSlug) { + AtomicReference response = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug(worldSlug).build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + + private static GameplayAdmissionPointerSnapshot catalogPointer( + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean publicProductionRealm) { + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldSlug, + realmSlug, + realmSlug, + tenantId, + gameInstanceId, + pointerVersion, + true, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + 29L, + java.util.UUID.randomUUID(), + java.util.UUID.randomUUID()); + } + + @Test + void missingStableRealmIdentityFailsClosedForCatalogReads() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot missingIdentity = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingIdentity)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertEquals(0, response.get().getRealmsCount()); + + AtomicReference pointerResponse = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerResponse.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.get().getError().getCode()); + assertFalse(pointerResponse.get().hasAdmissionPointer()); + } + + @Test + void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { + GameplayAdmissionPointerRepository pointerRepository = + Mockito.mock(GameplayAdmissionPointerRepository.class); + GameplayAdmissionPointerEventRepository eventRepository = + Mockito.mock(GameplayAdmissionPointerEventRepository.class); + AtomicReference currentPointer = new AtomicReference<>(); + Mockito.when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + .thenAnswer(invocation -> java.util.Optional.ofNullable(currentPointer.get())); + Mockito.when(pointerRepository.save(Mockito.any(GameplayAdmissionPointer.class))) + .thenAnswer( + invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + if (pointer.getId() == null) { + pointer.setId(11L); + } + currentPointer.set(pointer); + return pointer; + }); + Mockito.when(eventRepository.save(Mockito.any(GameplayAdmissionPointerEvent.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + DatabaseGameplayAdmissionPointerAuthorityService authorityService = + new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); + + GameplayAdmissionPointerSnapshot created = + authorityService.upsertPointer(pointerMutation(44L, true, 0L)); + GameplayAdmissionPointerSnapshot policyChanged = + authorityService.upsertPointer(pointerMutation(44L, false, 1L)); + GameplayAdmissionPointerSnapshot routeChanged = + authorityService.upsertPointer(pointerMutation(45L, false, 2L)); + + assertEquals(1L, created.catalogRevision()); + assertEquals(1L, created.pointerVersion()); + assertEquals(2L, policyChanged.catalogRevision()); + assertEquals(2L, policyChanged.pointerVersion()); + assertEquals(2L, routeChanged.catalogRevision()); + assertEquals(3L, routeChanged.pointerVersion()); + } + + private static GameplayAdmissionPointerMutation pointerMutation( + long gameInstanceId, boolean publicProductionRealm, Long expectedPointerVersion) { + return new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + gameInstanceId, + true, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + "test", + "catalog revision test", + "catalog-revision-test-" + expectedPointerVersion, + expectedPointerVersion, + null); + } + @Test void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { PingService pingService = Mockito.mock(PingService.class); From d7a47f801492f6964126b9ac547b2a8579f5c9c0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 06:07:29 +1300 Subject: [PATCH 002/105] Align text fixtures with exact realm authority --- .../player-access-and-session.md | 2 +- .../text/SessionResumptionFlowTest.java | 23 ++++-- .../text/TextCommandInterpreterTest.java | 79 ++++++++++++------- 3 files changed, 70 insertions(+), 34 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4e6acf3328..d435a6f762 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -61,7 +61,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Current connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target but does not revalidate the applicable non-public grant. Target issuance grant validation and its focused proof remain gaps. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit `JOIN`/`Join & Play` is implemented locally through the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. Its `PENDING`/unknown-database-outcome recovery seam and direct text-client proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit text `JOIN` is implemented locally through Game Session dispatch and the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. First-party `Join & Play`, the writer's `PENDING`/unknown-database-outcome recovery seam, and direct text-client end-to-end proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index e6f5ef4316..33ed582b54 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -49,6 +49,7 @@ import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; import net.firedevops.firemud.gamesession.service.CommandService; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -143,11 +144,11 @@ void setUp() { sessionContextService.save(bootstrapShell(1L, 1L)); sessionContextService.save(bootstrapShell(2L, 1L)); gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + List.of(world("demo", 22L, 1L, false), world("sandbox", 23L, 2L, true))); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); - when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) - .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L))); + when(pointerAuthorityService.listByRuntimeTarget(23L, 2L)) + .thenReturn(List.of(pointer("sandbox", "production", 23L, 2L, 1L))); when(instanceRepository.findById(Mockito.anyLong())) .thenAnswer( invocation -> { @@ -172,6 +173,8 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); when(accountClient.getRealmAccessGrantForRuntime( @@ -191,6 +194,7 @@ void setUp() { GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") .setGameplayAvailable(true) + .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") @@ -279,7 +283,12 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - worldsHandler = new WorldsCommandHandler(worldCatalog, entityManagementClient); + worldsHandler = + new WorldsCommandHandler( + worldCatalog, + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); interpreter = @@ -471,7 +480,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { assertTrue(secondLogin.commandResult().accepted()); TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertFalse(deniedPlay.commandResult().accepted()); - assertEquals("WORLD_ACCESS_DENIED", deniedPlay.commandResult().errorCode()); + assertEquals("JOIN_REQUIRED", deniedPlay.commandResult().errorCode()); TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); @@ -572,8 +581,12 @@ private static GameplayCatalogProperties.World world( realm.setDisplayName("Live Realm"); realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); + realm.setPointerVersion(1L); realm.setVisible(true); + realm.setPublicProductionRealm(true); realm.setRequiresCharacterSelection(requiresCharacterSelection); + realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); + realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); world.setRealms(List.of(realm)); return world; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 237e6571a1..e2fa06024e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -12,18 +12,20 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; -import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomResponse; @@ -64,6 +66,7 @@ import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; import net.firedevops.firemud.gamesession.service.CommandService; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -79,7 +82,6 @@ import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.gamesession.service.impl.DefaultGameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.impl.FakeGameplayPresenceService; -import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.shared.v1.RoomInstanceRef; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -163,6 +165,15 @@ void setUp() { .setAuthToken("auth-token") .setAccountId("123") .build()); + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE") + .setMessage("scope authority unavailable") + .build()) + .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -172,6 +183,8 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); when(accountClient.getRealmAccessGrantForRuntime( @@ -191,6 +204,7 @@ void setUp() { GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") .setGameplayAvailable(true) + .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) .setEvaluatedAt("2026-03-30T00:00:00Z") @@ -329,8 +343,8 @@ void setUp() { .thenReturn(CommandEnqueueResult.success()); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); - when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) - .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L))); + when(pointerAuthorityService.listByRuntimeTarget(23L, 2L)) + .thenReturn(List.of(pointer("sandbox", "production", 23L, 2L, 1L))); when(gameInstanceRepository.findById(Mockito.anyLong())) .thenAnswer( invocation -> { @@ -348,11 +362,10 @@ void setUp() { gameSessionProperties, sessionRoutingNormalizationService(), gameplayPresenceLifecycleService); - GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); - gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); GameplayWorldCatalog worldCatalog = - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); + GameplayWorldCatalog.forWorldViews( + List.of(worldView("demo", "Demo World", 22L, 1L, false), + worldView("sandbox", "Builder Sandbox", 23L, 2L, true))); LoginCommandHandler loginHandler = new LoginCommandHandler( gameInstanceRepository, @@ -411,7 +424,11 @@ void setUp() { .build()) .build()); WorldsCommandHandler worldsHandler = - new WorldsCommandHandler(worldCatalog, entityManagementClient); + new WorldsCommandHandler( + worldCatalog, + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()); LookResult lookResult = LookResult.newBuilder() @@ -1028,25 +1045,31 @@ private String renderedResponse( interpretation.outputs()); } - private static GameplayCatalogProperties.World world( - String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { - GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); - world.setSlug(slug); - world.setDisplayName( - switch (slug) { - case "demo" -> "Demo World"; - case "sandbox" -> "Builder Sandbox"; - default -> slug; - }); - GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); - realm.setSlug("production"); - realm.setDisplayName("Live Realm"); - realm.setTenantId(tenantId); - realm.setGameInstanceId(gameInstanceId); - realm.setVisible(true); - realm.setRequiresCharacterSelection(requiresCharacterSelection); - world.setRealms(List.of(realm)); - return world; + private static GameplayWorldCatalog.WorldView worldView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + boolean requiresCharacterSelection) { + return new GameplayWorldCatalog.WorldView( + slug, + displayName, + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + tenantId, + gameInstanceId, + 1L, + true, + true, + requiresCharacterSelection, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.nameUUIDFromBytes((slug + ":realm").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (slug + ":namespace").getBytes(StandardCharsets.UTF_8))))); } private static GameplayAdmissionPointerSnapshot pointer( From 6e485d81ca7564851c9b003d034a3f76cc6a039a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 06:51:05 +1300 Subject: [PATCH 003/105] Fail closed on ambiguous world and lobby authority responses --- .../command/text/GameplayWorldCatalog.java | 7 +- .../command/text/WorldsCommandHandler.java | 36 ++- .../text/GameplayWorldCatalogTest.java | 29 +++ .../text/SessionResumptionFlowTest.java | 5 + .../text/TextCommandInterpreterTest.java | 3 + .../text/WorldsCommandHandlerTest.java | 217 ++++++++++++++++-- .../WorldsTextCommandDispatchHandlerTest.java | 3 + 7 files changed, 269 insertions(+), 31 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 132011e453..bdd0243a4d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -1,12 +1,14 @@ package net.firedevops.firemud.gamesession.command.text; import java.util.ArrayList; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; @@ -304,9 +306,10 @@ private static List toWorlds(List p } MutableWorldAccumulator world = worlds.computeIfAbsent( - pointer.worldSlug(), + pointer.worldSlug().toLowerCase(Locale.ROOT), ignored -> new MutableWorldAccumulator(pointer.worldSlug(), pointer.worldDisplayName())); + world.tenantIds.add(pointer.tenantId()); world .realmsBySlug .computeIfAbsent(pointer.realmSlug(), ignored -> new ArrayList<>()) @@ -314,6 +317,7 @@ private static List toWorlds(List p } return normalizeWorlds( worlds.values().stream() + .filter(world -> world.tenantIds.size() == 1) .map( world -> new WorldView( @@ -467,6 +471,7 @@ public enum PublicProductionRealmCardinality { private static final class MutableWorldAccumulator { private final String slug; private final String displayName; + private final Set tenantIds = new HashSet<>(); private final Map> realmsBySlug = new LinkedHashMap<>(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 96dc4e22ee..fd5d6c4476 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -4,9 +4,11 @@ import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -120,7 +122,7 @@ public RealmBrowseResult browseRealms(SessionContext sessionContext, String worl if (scopeResponse.hasError()) { String errorCode = scopeResponse.getError().getCode(); if ("REALM_UNAVAILABLE".equals(errorCode)) { - continue; + return RealmBrowseResult.failure("REALM_UNAVAILABLE"); } return RealmBrowseResult.failure(errorCode.isBlank() ? "AUTH_UNAVAILABLE" : errorCode); } @@ -320,13 +322,6 @@ public JoinMembershipResult joinPublicProductionMembership( if (accountClient == null || connectScopeSessionStore == null) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } - Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); - if (maybeWorld.isEmpty()) { - return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); - } - if (!worldCatalog.hasValidPublicProductionRealm(maybeWorld.orElseThrow())) { - return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); - } Optional maybeJoinScope = connectScopeSessionStore.publicProductionScopeForJoin( sessionContext, worldSelector, Instant.now()); @@ -487,8 +482,17 @@ public CharacterBrowseResult browseCharacters( } java.util.List entries = new java.util.ArrayList<>(response.getCharactersCount()); + Set characterIds = new HashSet<>(); for (int i = 0; i < response.getCharactersCount(); i++) { net.firedevops.firemud.entitymanagement.v1.Character character = response.getCharacters(i); + if (!Long.toString(realm.tenantId()).equals(character.getTenantId()) + || !Long.toString(sessionContext.accountId()).equals(character.getAccountId()) + || character.getPlayableStateScope() != toPlayableStateScope(realm) + || !StringUtils.hasText(character.getId()) + || !StringUtils.hasText(character.getName()) + || !characterIds.add(character.getId())) { + return CharacterBrowseResult.unavailable(); + } entries.add( new CharacterBrowseViewOutput.CharacterEntry( i + 1, character.getId(), character.getName(), character.getLevel())); @@ -610,12 +614,20 @@ private boolean isValidMembershipAuthoritySnapshot( return false; } if (!response.getMembershipExists()) { - return response.getMembershipVersion() == 0L + return "MISSING".equalsIgnoreCase(response.getMembershipLifecycleState()) + && !response.getGameplayAdmissionAllowed() + && response.getMembershipVersion() == 0L && response.getMembershipAuthorityGeneration() == 0L; } - return response.getMembershipVersion() > 0L - && response.getMembershipAuthorityGeneration() > 0L - && StringUtils.hasText(response.getMembershipLifecycleState()); + if (response.getMembershipVersion() <= 0L + || response.getMembershipAuthorityGeneration() <= 0L) { + return false; + } + if ("ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState())) { + return response.getGameplayAdmissionAllowed(); + } + return "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) + && !response.getGameplayAdmissionAllowed(); } private boolean hasCompleteSelectedRealmPointerEvidence( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index cce093ab92..5bbeaaba34 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -26,6 +26,35 @@ void visibleWorldsDropsAmbiguousRealmSelectorRows() { assertThat(catalog.resolveWorld("demo")).isEmpty(); } + @Test + void visibleWorldsDropsWorldSlugSharedAcrossTenants() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), + pointer("DEMO", "Other Demo", "preview", "Preview Realm", 2L, 21L, 8L), + pointer("other", "Other World", "production", "Other Live", 2L, 22L, 9L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("other"); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + } + + @Test + void visibleWorldsGroupsMultipleRealmsForTheSameTenantWorldSlug() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), + pointer("demo", "Demo World", "event", "Event Realm", 1L, 12L, 8L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("demo").orElseThrow(); + assertThat(world.realms()).extracting(GameplayWorldCatalog.RealmView::slug) + .containsExactly("production", "event"); + } + @Test void reverseRuntimeLookupFailsClosedWhenMultipleVisibleRealmsShareRuntimeTarget() { when(authorityService.listPointers()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 33ed582b54..91d6afab5e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -209,6 +209,11 @@ void setUp() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("77") + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) .setName("Emberline") .setLevel(12) .build()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index e2fa06024e..ccf886523a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -419,6 +419,9 @@ void setUp() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("123") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setName("Emberline") .setLevel(12) .build()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 01aaeb611d..425fa0b85e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -6,10 +6,12 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; @@ -21,6 +23,7 @@ import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -103,6 +106,9 @@ void browseCharactersReturnsStructuredCharacterList() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("123") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setName("Emberline") .setLevel(12) .build()) @@ -153,6 +159,9 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8001") + .setTenantId("22") + .setAccountId("123") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .setName("Forkline") .setLevel(5) .build()) @@ -175,6 +184,44 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .containsExactly("Forkline"); } + @Test + void browseCharactersRejectsMismatchedOrDuplicateEntityRows() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.getTenantMembershipForRuntime(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + WorldsCommandHandler localHandler = authenticatedHandler(publicProductionProperties(), accountClient); + net.firedevops.firemud.entitymanagement.v1.Character valid = + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("7001") + .setTenantId("22") + .setAccountId("123") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setName("Emberline") + .build(); + for (net.firedevops.firemud.entitymanagement.v1.Character invalid : + List.of( + valid.toBuilder().setTenantId("23").build(), + valid.toBuilder().setAccountId("456").build(), + valid.toBuilder().setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED).build(), + valid.toBuilder().clearId().build(), + valid.toBuilder().clearName().build())) { + Mockito.when(entityManagementClient.listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.newBuilder().addCharacters(invalid).build()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + } + + Mockito.when(entityManagementClient.listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.newBuilder() + .addCharacters(valid) + .addCharacters(valid) + .build()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + } + @Test void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); @@ -200,24 +247,34 @@ void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { @Test void browseCharactersReturnsJoinRequiredForPublicNonMemberWithoutReadingEntityRoster() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + GameplayCatalogProperties properties = publicProductionProperties(); AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + publicMembership(false, false, 0L, 0L, "MISSING")); + Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("JOIN_REQUIRED")); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void browseCharactersReturnsJoinRequiredForPublicInactiveMemberWithoutReadingEntityRoster() { + GameplayCatalogProperties properties = publicProductionProperties(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + publicMembership(true, false, 3L, 4L, "INACTIVE")); Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); @@ -230,6 +287,26 @@ void browseCharactersReturnsJoinRequiredForPublicNonMemberWithoutReadingEntityRo Mockito.verifyNoInteractions(entityManagementClient); } + @Test + void browseCharactersFailsClosedForUnknownPublicMembershipLifecycleWithoutReadingEntityRoster() { + assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "UNKNOWN")); + } + + @Test + void browseCharactersFailsClosedForActivePublicMembershipWithoutAdmissionWithoutReadingEntityRoster() { + assertPublicMembershipFailsClosed(publicMembership(true, false, 1L, 1L, "ACTIVE")); + } + + @Test + void browseCharactersFailsClosedForAbsentPublicMembershipWithActiveLifecycleWithoutReadingEntityRoster() { + assertPublicMembershipFailsClosed(publicMembership(false, false, 0L, 0L, "ACTIVE")); + } + + @Test + void browseCharactersFailsClosedForInactivePublicMembershipWithAdmissionWithoutReadingEntityRoster() { + assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "INACTIVE")); + } + @Test void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEntityRoster() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -719,6 +796,76 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); } + @Test + void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySuccess() { + GameplayWorldCatalog.RealmView realm = + new GameplayWorldCatalog.RealmView( + "production", "Live Realm", 22L, 1L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, + UUID.randomUUID(), UUID.randomUUID()); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn(IssueDirectTextConnectScopeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("REALM_UNAVAILABLE")) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews( + List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), + entityManagementClient, + accountClient, + new DirectTextConnectScopeSessionStore()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("REALM_UNAVAILABLE")); + } + + @Test + void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { + GameplayWorldCatalog.RealmView realmA = + new GameplayWorldCatalog.RealmView( + "production", "A", 22L, 1L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, + UUID.randomUUID(), UUID.randomUUID()); + GameplayWorldCatalog.RealmView realmB = + new GameplayWorldCatalog.RealmView( + "production", "B", 23L, 2L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, + UUID.randomUUID(), UUID.randomUUID()); + GameplayWorldCatalog.WorldView worldA = + new GameplayWorldCatalog.WorldView("a", "A", List.of(realmA)); + GameplayWorldCatalog.WorldView worldB = + new GameplayWorldCatalog.WorldView("b", "B", List.of(realmB)); + AtomicReference> worlds = + new AtomicReference<>(List.of(worldA, worldB)); + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(worlds::get); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn(IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-a") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + Mockito.when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false).setOutcomeCode("CONNECT_SCOPE_MISMATCH").build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler(catalog, entityManagementClient, accountClient, + new DirectTextConnectScopeSessionStore()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "1")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + worlds.set(List.of(worldB, worldA)); + assertThat(catalog.resolveWorld("1")).hasValue(worldB); + WorldsCommandHandler.JoinMembershipResult join = + localHandler.joinPublicProductionMembership(authenticatedSession(), "1"); + + assertThat(join).isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); + assertThat(((WorldsCommandHandler.JoinMembershipResult.Response) join).response().getOutcomeCode()) + .isEqualTo("CONNECT_SCOPE_MISMATCH"); + Mockito.verify(accountClient).joinPublicProductionMembership( + Mockito.argThat(context -> context.getTenantId().equals("22") + && context.getRealmId().equals(realmA.realmId().toString())), + Mockito.eq("scope-a"), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + } + @Test void authenticatedBrowseFailsClosedWhenTenantHasNoPublicProductionRealm() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -762,6 +909,31 @@ private WorldsCommandHandler authenticatedHandler( new DirectTextConnectScopeSessionStore()); } + private GameplayCatalogProperties publicProductionProperties() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("demo", 22L, 1L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + return properties; + } + + private void assertPublicMembershipFailsClosed( + GetTenantMembershipForRuntimeResponse membership) { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(membership); + WorldsCommandHandler localHandler = + authenticatedHandler(publicProductionProperties(), accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(entityManagementClient); + } + private void addPublicProductionAuthority(GameplayCatalogProperties properties) { GameplayCatalogProperties.World authority = world("production-authority", 22L, 1L, false); authority.getRealms().getFirst().setPublicProductionRealm(true); @@ -775,14 +947,23 @@ private SessionContext authenticatedSession() { } private GetTenantMembershipForRuntimeResponse activeMembership() { + return publicMembership(true, true, 1L, 1L, "ACTIVE"); + } + + private GetTenantMembershipForRuntimeResponse publicMembership( + boolean membershipExists, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String lifecycleState) { return GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId("123") .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setMembershipLifecycleState("ACTIVE") - .setMembershipAuthorityGeneration(1L) + .setMembershipExists(membershipExists) + .setGameplayAdmissionAllowed(gameplayAdmissionAllowed) + .setMembershipVersion(membershipVersion) + .setMembershipLifecycleState(lifecycleState) + .setMembershipAuthorityGeneration(membershipAuthorityGeneration) .setEvaluatedAt("2026-03-30T00:00:00Z") .build(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 7079fe626f..a3f0b42c4b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -191,6 +191,9 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("123") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setName("Emberline") .setLevel(12) .build()) From 8a1095d59f87e88b3bf3ddaa5ce5cf29c0410ec7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 07:29:32 +1300 Subject: [PATCH 004/105] Fail closed on direct-text admission evidence and JOIN outcomes --- ...ystem-architecture-authz-route-matrix.yaml | 2 +- .../test_check_authz_route_matrix.py | 8 ++ .../command/text/WorldsCommandHandler.java | 34 ++++- .../WorldsTextCommandDispatchHandler.java | 3 + .../text/SessionResumptionFlowTest.java | 3 +- .../text/TextCommandInterpreterTest.java | 3 +- .../text/WorldsCommandHandlerTest.java | 130 ++++++++++++++++-- .../WorldsTextCommandDispatchHandlerTest.java | 109 ++++++++++++++- .../support/TestGameplayWorldCatalogs.java | 11 +- 9 files changed, 279 insertions(+), 24 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index a4ba1e7e20..d258bbf6ef 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1172,7 +1172,7 @@ routes: membership_authority_generation_applies: false required_live_checks: [public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, MEMBERSHIP_RECONCILIATION_REQUIRED, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation implementation_status: diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index ae9d805c22..7dd8e8df5f 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -6146,6 +6146,14 @@ def test_missing_join_route_error_is_shared_once(self): ], ) + def test_direct_text_join_matrix_includes_account_terminal_outcomes(self): + document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) + route = route_for(document, "game-session-service", "JOIN") + outcomes = route["canonical_errors"]["any_of"] + + self.assertIn("CONNECT_SCOPE_INVALID", outcomes) + self.assertIn("MEMBERSHIP_RECONCILIATION_REQUIRED", outcomes) + def test_privileged_control_cardinality_error_uses_shared_set(self): document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) routes = [ diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index fd5d6c4476..edb65d2619 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -225,7 +225,7 @@ private NonPublicRealmAuthorization authorizeNonPublicRealm( : NonPublicRealmAuthorization.DENIED; } if (!isValidEntitlement(entitlementResponse, realm)) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + return NonPublicRealmAuthorization.ENTITLEMENT_UNAVAILABLE; } return entitlementResponse.getGameplayAvailable() ? NonPublicRealmAuthorization.AUTHORIZED @@ -236,7 +236,22 @@ private boolean isValidEntitlement( GetTenantEntitlementsForRuntimeResponse response, GameplayWorldCatalog.RealmView realm) { return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) - && isInstant(response.getEvaluatedAt()); + && response.getEntitlementVersion() > 0L + && response.getTenantBillingSequence() > 0L + && isFreshEntitlementEvaluation(response.getEvaluatedAt()); + } + + private boolean isFreshEntitlementEvaluation(String evaluatedAt) { + if (!StringUtils.hasText(evaluatedAt)) { + return false; + } + try { + Instant evaluated = Instant.parse(evaluatedAt); + Instant now = Instant.now(); + return !evaluated.isAfter(now) && !evaluated.isBefore(now.minusSeconds(15)); + } catch (DateTimeParseException ex) { + return false; + } } private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { @@ -330,6 +345,15 @@ public JoinMembershipResult joinPublicProductionMembership( } DirectTextConnectScopeSessionStore.JoinScope joinScope = maybeJoinScope.orElseThrow(); DirectTextConnectScopeSessionStore.ScopedRealm scope = joinScope.scope(); + long tenantId; + try { + tenantId = Long.parseLong(scope.playerContext().getTenantId()); + } catch (NumberFormatException ex) { + return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + if (!worldCatalog.hasValidPublicProductionRealm(tenantId)) { + return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } String requestId = joinScope.requestId(); PlayerExecutionContext playerContext = scope.playerContext().toBuilder().setRequestId(requestId).build(); @@ -580,7 +604,7 @@ private PublicEntitlementAuthorization authorizePublicCharacterEntitlement( } if (!isValidEntitlement(entitlementResponse, realm)) { return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); + CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE, false); } if (!entitlementResponse.getGameplayAvailable()) { return new PublicEntitlementAuthorization( @@ -635,7 +659,11 @@ private boolean hasCompleteSelectedRealmPointerEvidence( return realm.visible() && realm.tenantId() > 0L && realm.gameInstanceId() > 0L + && realm.catalogRevision() > 0L && realm.pointerVersion() > 0L + && realm.realmId() != null + && realm.playableStateNamespaceId() != null + && ("SHARED".equals(realm.stateScope()) || "ISOLATED".equals(realm.stateScope())) && StringUtils.hasText(realm.slug()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index 6d8631b370..fabffe5266 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -121,7 +121,10 @@ private String realmBrowseFailureMessage(String code) { private String joinFailureMessage(String code) { return switch (code) { + case "CONNECT_SCOPE_INVALID" -> "Join scope is invalid or expired. Run REALMS again."; case "CONNECT_SCOPE_MISMATCH" -> "Join scope expired or changed. Run REALMS again."; + case "MEMBERSHIP_RECONCILIATION_REQUIRED" -> + "Membership needs reconciliation. Contact support before retrying JOIN."; case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> "Account authority unavailable. Retry JOIN shortly."; case "ENTITLEMENT_UNAVAILABLE" -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 91d6afab5e..d6ea6b84cd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -197,7 +198,7 @@ void setUp() { .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(entityManagementClient.listCharactersByAccount( Mockito.anyString(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index ccf886523a..277d2773c5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -12,6 +12,7 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; @@ -207,7 +208,7 @@ void setUp() { .setAllowPublicJoin(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(gameLogicClient.queryInventory(Mockito.any(SessionContext.class))) .thenReturn( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 425fa0b85e..6dfc238152 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -223,16 +223,11 @@ void browseCharactersRejectsMismatchedOrDuplicateEntityRows() { } @Test - void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { + void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); addPublicProductionAuthority(gameplayCatalogProperties); AccountClient accountClient = Mockito.mock(AccountClient.class); - stubActivePrivateAuthorization(accountClient, "demo"); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); @@ -242,7 +237,9 @@ void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { "demo", null); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure( + "ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -480,6 +477,69 @@ void browseCharactersRejectsMultiplePublicProductionCardinalityWithExplicitRealm Mockito.verifyNoInteractions(accountClient, entityManagementClient); } + @Test + void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() { + UUID realmId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + GameplayWorldCatalog.RealmView complete = + new GameplayWorldCatalog.RealmView( + "production", "Live Realm", 22L, 1L, 1L, true, true, false, "SHARED", + "ALLOW_NEW", 1L, realmId, namespaceId); + AccountClient accountClient = Mockito.mock(AccountClient.class); + for (GameplayWorldCatalog.RealmView incomplete : List.of( + new GameplayWorldCatalog.RealmView( + complete.slug(), complete.displayName(), complete.tenantId(), + complete.gameInstanceId(), complete.pointerVersion(), complete.visible(), + complete.publicProductionRealm(), complete.requiresCharacterSelection(), + complete.stateScope(), complete.characterCreationPolicy(), 0L, realmId, namespaceId), + new GameplayWorldCatalog.RealmView( + complete.slug(), complete.displayName(), complete.tenantId(), + complete.gameInstanceId(), complete.pointerVersion(), complete.visible(), + complete.publicProductionRealm(), complete.requiresCharacterSelection(), + complete.stateScope(), complete.characterCreationPolicy(), 1L, null, namespaceId), + new GameplayWorldCatalog.RealmView( + complete.slug(), complete.displayName(), complete.tenantId(), + complete.gameInstanceId(), complete.pointerVersion(), complete.visible(), + complete.publicProductionRealm(), complete.requiresCharacterSelection(), + complete.stateScope(), complete.characterCreationPolicy(), 1L, realmId, null))) { + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews(List.of( + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(incomplete)))), + entityManagementClient, accountClient, new DirectTextConnectScopeSessionStore()); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure( + "ADMISSION_POINTER_UNAVAILABLE")); + } + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + + @Test + void browseCharactersRejectsIncompleteOrStaleEntitlementBeforeReadingRoster() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + WorldsCommandHandler localHandler = + authenticatedHandler(publicProductionProperties(), accountClient); + GetTenantEntitlementsForRuntimeResponse valid = publicEntitlement(true); + for (GetTenantEntitlementsForRuntimeResponse invalid : List.of( + valid.toBuilder().setEntitlementVersion(0L).build(), + valid.toBuilder().setTenantBillingSequence(0L).build(), + valid.toBuilder().setEvaluatedAt(Instant.now().minusSeconds(16).toString()).build(), + valid.toBuilder().setEvaluatedAt(Instant.now().plusSeconds(30).toString()).build())) { + Mockito.when(accountClient.getTenantEntitlementsForRuntime( + Mockito.anyString(), Mockito.anyString())) + .thenReturn(invalid); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure( + "ENTITLEMENT_UNAVAILABLE")); + } + Mockito.verifyNoInteractions(entityManagementClient); + } + @Test void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRoster() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -497,7 +557,8 @@ void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRo .setGameplayAvailable(true) .setAllowPublicJoin(false) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); Mockito.when( entityManagementClient.listCharactersByAccount( @@ -623,7 +684,8 @@ void authenticatedBrowseIncludesPrivateRealmForActiveMemberWithExactGrant() { .setTenantId("22") .setGameplayAvailable(true) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); @@ -661,14 +723,15 @@ void authenticatedBrowseRejectsPrivateRealmWhenEntitlementTenantDoesNotMatch() { .setTenantId("23") .setGameplayAvailable(true) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "preview"); - assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); } @Test @@ -696,7 +759,8 @@ void authenticatedBrowseOmitsPrivateRealmWhenGameplayEntitlementIsUnavailable() .setTenantId("22") .setGameplayAvailable(false) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); @@ -866,6 +930,42 @@ void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { Mockito.verifyNoInteractions(entityManagementClient); } + @Test + void joinRejectsRetainedScopeWhenTenantPublicRealmBecomesAmbiguous() { + GameplayWorldCatalog.RealmView originalRealm = + new GameplayWorldCatalog.RealmView( + "production", "A", 22L, 1L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, + UUID.randomUUID(), UUID.randomUUID()); + GameplayWorldCatalog.RealmView conflictingRealm = + new GameplayWorldCatalog.RealmView( + "production", "B", 22L, 2L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, + UUID.randomUUID(), UUID.randomUUID()); + GameplayWorldCatalog.WorldView originalWorld = + new GameplayWorldCatalog.WorldView("a", "A", List.of(originalRealm)); + AtomicReference> worlds = + new AtomicReference<>(List.of(originalWorld)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn(IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-a") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldSupplier(worlds::get), entityManagementClient, + accountClient, new DirectTextConnectScopeSessionStore()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "a")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + worlds.set(List.of(originalWorld, + new GameplayWorldCatalog.WorldView("b", "B", List.of(conflictingRealm)))); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "a")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verify(accountClient, Mockito.never()) + .joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + } + @Test void authenticatedBrowseFailsClosedWhenTenantHasNoPublicProductionRealm() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -974,7 +1074,8 @@ private GetTenantEntitlementsForRuntimeResponse publicEntitlement(boolean allowP .setGameplayAvailable(true) .setAllowPublicJoin(allowPublicJoin) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build(); } @@ -1014,7 +1115,8 @@ private void stubActivePrivateAuthorization(AccountClient accountClient, String .setTenantId("22") .setGameplayAvailable(true) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index a3f0b42c4b..6737652e77 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; +import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -117,7 +118,8 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { .setTenantId("1") .setGameplayAvailable(true) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( @@ -182,7 +184,8 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .setTenantId("22") .setGameplayAvailable(true) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); when(entityManagementClient.listCharactersByAccount( "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -262,7 +265,8 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) .build()); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( @@ -427,6 +431,105 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { Mockito.argThat(gameplayCommand -> "REALMS".equals(gameplayCommand.getCommandName()))); } + @Test + void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { + UUID realmId = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + UUID namespaceId = UUID.fromString("42d234a2-7487-4dda-a7e5-a3831214328e"); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo-world", + "Demo World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 9L, + 4L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 7L, + realmId, + namespaceId))))); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + catalog, entityManagementClient, accountClient, new DirectTextConnectScopeSessionStore()), + scriptEventPublisher); + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-account-scope-1") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build(), + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-account-scope-2") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build()); + when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("CONNECT_SCOPE_INVALID") + .build(), + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("MEMBERSHIP_RECONCILIATION_REQUIRED") + .build()); + SessionContext context = + new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.REALMS, List.of("demo-world"), "REALMS demo-world"), + false, + Optional.of(context))); + TextCommandInterpretationResult invalidScopeResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.REALMS, List.of("demo-world"), "REALMS demo-world"), + false, + Optional.of(context))); + TextCommandInterpretationResult reconciliationResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); + + assertThat(invalidScopeResult.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(invalidScopeResult.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isEqualTo( + new net.firedevops.firemud.gamesession.presentation.ErrorOutput( + "CONNECT_SCOPE_INVALID", "Join scope is invalid or expired. Run REALMS again.")); + assertThat(reconciliationResult.commandResult().errorCode()) + .isEqualTo("MEMBERSHIP_RECONCILIATION_REQUIRED"); + assertThat(reconciliationResult.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isEqualTo( + new net.firedevops.firemud.gamesession.presentation.ErrorOutput( + "MEMBERSHIP_RECONCILIATION_REQUIRED", + "Membership needs reconciliation. Contact support before retrying JOIN.")); + } + private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index d9dd2b3cf1..4a71ba45b8 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -3,6 +3,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.UUID; +import java.nio.charset.StandardCharsets; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; @@ -55,6 +57,13 @@ private static GameplayWorldCatalog.RealmView toRealmView(GameplayCatalogPropert input.isPublicProductionRealm(), input.isRequiresCharacterSelection(), stateScope, - characterCreationPolicy); + characterCreationPolicy, + 1L, + UUID.nameUUIDFromBytes( + ("test-realm:" + input.getTenantId() + ":" + input.getSlug()) + .getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + ("test-namespace:" + input.getTenantId() + ":" + input.getGameInstanceId()) + .getBytes(StandardCharsets.UTF_8))); } } From a94fad396b00d9098ddb006529f150af79b505f8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:24:03 +1300 Subject: [PATCH 005/105] Keep direct-text lobby authority across Game Session instances --- .../game-session-service/protocols.md | 6 +- .../realm-routing-and-playable-state.md | 6 +- .../gamesession/client/GameDesignClient.java | 3 +- .../command/text/GameplayWorldCatalog.java | 197 ++++- .../command/text/LogoutCommandHandler.java | 19 - .../command/text/WorldsCommandHandler.java | 225 ++++- .../WorldsTextCommandDispatchHandler.java | 36 +- .../DirectTextConnectScopeSessionStore.java | 802 ++++++++++++++---- ...irectTextConnectScopeSessionStoreTest.java | 169 ++++ .../text/GameplayWorldCatalogTest.java | 22 +- .../text/LogoutCommandHandlerTest.java | 4 +- .../text/SessionResumptionFlowTest.java | 5 +- .../text/TextCommandInterpreterTest.java | 13 +- .../text/WorldsCommandHandlerTest.java | 496 ++++++++--- .../WorldsTextCommandDispatchHandlerTest.java | 31 +- ...irectTextConnectScopeSessionStoreTest.java | 106 ++- ...sionWebSocketHandshakeInterceptorTest.java | 39 +- .../support/TestGameplayWorldCatalogs.java | 2 +- .../GameplayWebSocketBridgeHandler.java | 22 +- .../GatewayGameplayBridgeIntegrationTest.java | 44 +- .../GameplayWebSocketBridgeHandlerTest.java | 87 +- 21 files changed, 1881 insertions(+), 453 deletions(-) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index f36e80348c..77e44c073c 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -54,7 +54,7 @@ CHARS [realm] (only when a valid selected character is not already resol PLAY [realm] [character] ``` -For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous discovery step before `LOGIN`, and `REALMS` / `CHARS` are fresh authenticated discovery or selection steps as needed on that transport. The target text flow is `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. A direct text client must not reuse a first-party WebSocket discovery snapshot. The selected-character discovery shortcut is restricted to the first-party token-backed WebSocket path; direct text may omit a separate `CHARS` round-trip only when fresh transport-local resolution supplies one valid current character. The current proxy still bootstraps a hidden default route and does not enforce `WORLDS` as a prerequisite, so this target requirement remains an implementation and proof gap. +For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous discovery step before `LOGIN`, and `REALMS` / `CHARS` are fresh authenticated discovery or selection steps as needed on that transport. The target text flow is `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Direct text does not reuse a first-party WebSocket discovery snapshot: current Game Session captures each public WORLDS response and its exact ordinal targets from the same catalog read, then persists that bounded snapshot in the shared Redis lobby record keyed by the positive numeric transport session ID. On the trusted TCP Proxy path, Gateway forwards the mTLS-authenticated `X-Proxy-Connection-Id` unchanged and omits `X-Firemud-Transport-Session-Id`; Game Session derives the numeric transport ID from that stable proxy connection identity, and Gateway fails closed if it is missing. First-party transport IDs continue to use the Gateway-issued transport header; bootstrap game-instance identity is not a transport-session key. Numeric `REALMS ` selectors require the exact unexpired WORLDS snapshot and reject a changed catalog instead of reindexing; stable slugs re-resolve against current catalog authority. Account-issued scopes and sticky JOIN request IDs share that record with exact account/session binding and bounded expiry, so Game Session replacement does not lose the pending JOIN attempt. Local focused unit proof is present; the Redis integration test is Docker-gated and full direct-text/Telnet end-to-end proof remains open. The selected-character discovery shortcut is restricted to the first-party token-backed WebSocket path; direct text may omit a separate `CHARS` round-trip only when fresh transport-local resolution supplies one valid current character. The current proxy still bootstraps a hidden default route and does not enforce `WORLDS` as a prerequisite, so the full target sequence remains an implementation and proof gap. | Command | Purpose | Example | | ------- | ------- | ------- | @@ -85,11 +85,11 @@ The canonical JOIN and membership-admission contract is defined in [Authenticati The Account membership operation is `JoinPublicProductionMembership`; the direct-text implementation is current and remains the sole membership writer, with Account-owned membership and audit/outbox consequences. Game Session translates `JOIN ` to that operation; it does not create membership locally or use another join writer. The first-party `Join & Play` action remains target-only. - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. -- Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the pending transport-local scope and passes the same identity to Account for retries. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. +- Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the Account-issued scope in the shared Redis lobby record keyed by the stable numeric transport session ID. Atomic per-key compare-and-set preserves that request identity across retries and Game Session replacement. The record contains no raw JWT; the Account scope is bound to exact account/session identity and expires within its bounded lifetime. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. - An ambiguous or stale world/realm selector is a lobby-selection error: Game Session does not guess, does not invoke Account, and directs the client to refresh `WORLDS`/`REALMS`. A discovered scope that is stale or no longer matches the resolved `worldSlug`/`realmSlug` fails closed with the applicable scope or admission error rather than being translated to a newer target. - JOIN idempotency uses the canonical preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session generates and retains the server-side `requestId`, passes the verified local digest inputs and retained scope to Account, and reuses that identity through retries and scope-expiry cleanup. Account replays an exact `{requestId, digest}` outcome and rejects a different digest as `IDEMPOTENCY_CONFLICT`; a new `requestId` is a distinct attempt after a new scope. -Direct-text `JOIN` availability and the membership-authority-generation gap are recorded in [Implementation Status](#implementation-status); this section defines the target translation and current local handling, while the remaining runtime and end-to-end proof gaps do not establish full path completion. +Direct-text `JOIN` is implemented locally through Account, with focused Game Session coverage for the shared scope/request binding; a Docker-gated Redis integration test covers persistence across store instances and concurrent retry binding. The Game Session focused proof does not establish full direct-text/Telnet end-to-end completion. The membership-authority-generation reread and other admission gaps remain in [Implementation Status](#implementation-status); this section defines the target translation and current local handling. ## Login and Play Flow 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 a7bb6391dc..7be2a7c287 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target-only and unimplemented; Account issuance/validation and Game Session transport-local scope retention, retry, terminal-outcome, and expiry behavior still need implementation and proof. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, catalog and route revisions are combined, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and stable slugs re-resolve against current catalog authority. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Full direct-text/Telnet end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, catalog and route revisions are combined, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. ## Packet 4 Status and Proof Gaps @@ -19,7 +19,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered WORLDS/REALMS/CHARS discovery is live, but the baseline unique index is `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`; cross-tenant duplicate selectors are not schema-safe. | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The baseline unique index is still `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`, so cross-tenant duplicate selectors are not schema-safe. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Internal sequential expected-version and prepared-cutover seams exist but are nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, catalog revision separation, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | @@ -59,7 +59,7 @@ Account-to-tenant membership is an explicit runtime substrate rather than an `ac First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. -The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target/unimplemented because Account direct-text `JOIN` issuance/validation and Game Session transport-local scope retention through retry, terminal outcome, or expiry still lack implementation and focused proof. This is distinct from the browser/WebSocket bootstrap snapshot and remains a contract gap rather than current proof. +The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; stable slug selection re-resolves current authority. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path and terminal-outcome recovery remain unproved. This is distinct from the browser/WebSocket bootstrap snapshot. Gateway and Game Session preserve and validate `worldSlug`, `realmSlug`, `connectScopeId`, `connectRequestId`, `pointerVersion`, and resolved target in first-party connect context. The durable bootstrap shell stores the selector identity and is the reconnect/login/`PLAY` fallback when transient registry state is absent. Generic websocket bootstrap preserves an incoming complete bundle, repairs a runtime-only shell only from one complete current pointer, and collapses ambiguous or incomplete authority to no bundle. If a reused shell had a bundle and the repaired incoming shell does not, it is a real route change: the `BOOTSTRAP_ROUTE_CHANGED` path clears authenticated/gameplay state instead of preserving the older route. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index 1396cfbd90..ca97ef1158 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -104,7 +104,8 @@ public GetPublishedScriptPatchVersionResponse getPublishedScriptPatchVersion( .setError( ErrorDetail.newBuilder() .setCode("INVALID_ARGUMENT") - .setMessage("base_version_id must be positive for script-patch publication lookup") + .setMessage( + "base_version_id must be positive for script-patch publication lookup") .build()) .build(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index bdd0243a4d..86fdbd6387 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -1,5 +1,9 @@ package net.firedevops.firemud.gamesession.command.text; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; @@ -13,6 +17,7 @@ import java.util.function.Supplier; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.WorldOrdinalTarget; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; @@ -46,7 +51,89 @@ public static GameplayWorldCatalog forWorldSupplier(Supplier> wo } public WorldsViewOutput browseView() { - return new WorldsViewOutput(worldEntries()); + return readDiscoverySnapshot().output(); + } + + /** Reads the catalog once and builds the exact public WORLDS projection and ordinal authority. */ + public DiscoverySnapshot readDiscoverySnapshot() { + List catalogWorlds = normalizeWorlds(worldSupplier.get()); + List visibleWorlds = + catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); + List discoverableWorlds = + visibleWorlds.stream() + .filter(world -> resolveDefaultRealm(world, catalogWorlds).isPresent()) + .toList(); + ArrayList entries = new ArrayList<>(discoverableWorlds.size()); + ArrayList targets = new ArrayList<>(discoverableWorlds.size()); + for (WorldView world : discoverableWorlds) { + RealmView defaultRealm = resolveDefaultRealm(world, catalogWorlds).orElseThrow(); + int ordinal = entries.size() + 1; + entries.add( + new WorldsViewOutput.WorldEntry( + ordinal, + world.slug(), + world.displayName(), + defaultRealm.gameInstanceId(), + defaultRealm.requiresCharacterSelection())); + targets.add( + new WorldOrdinalTarget( + ordinal, + world.slug(), + defaultRealm.tenantId(), + defaultRealm.catalogRevision(), + worldTargetFingerprint(world, defaultRealm))); + } + List exactTargets = List.copyOf(targets); + return new DiscoverySnapshot( + new WorldsViewOutput(entries), + fingerprint( + exactTargets.stream().map(GameplayWorldCatalog::targetFingerprintInput).toList()), + exactTargets, + visibleWorlds); + } + + public Optional resolveStableWorld(DiscoverySnapshot snapshot, String selector) { + Objects.requireNonNull(snapshot, "snapshot must not be null"); + if (selector == null || selector.isBlank() || isOrdinalSelector(selector)) { + return Optional.empty(); + } + String normalized = selector.trim().toLowerCase(Locale.ROOT); + return snapshot.visibleWorlds().stream() + .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) + .findFirst(); + } + + public Optional resolveSnapshotOrdinal( + DiscoverySnapshot current, WorldOrdinalTarget originatingTarget) { + Objects.requireNonNull(current, "current must not be null"); + Objects.requireNonNull(originatingTarget, "originatingTarget must not be null"); + List matches = + current.ordinalTargets().stream() + .filter(target -> target.ordinal() == originatingTarget.ordinal()) + .filter(originatingTarget::equals) + .toList(); + if (matches.size() != 1) { + return Optional.empty(); + } + return current.visibleWorlds().stream() + .filter(world -> world.slug().equalsIgnoreCase(originatingTarget.worldSlug())) + .filter( + world -> + world.realms().stream() + .filter(RealmView::visible) + .anyMatch(realm -> realm.tenantId() == originatingTarget.tenantId())) + .findFirst(); + } + + public static boolean isOrdinalSelector(String selector) { + if (selector == null || selector.isBlank()) { + return false; + } + String trimmed = selector.trim(); + if (!trimmed.chars().allMatch(Character::isDigit)) { + return false; + } + return true; } public Optional browseRealms(String worldSelector) { @@ -102,6 +189,17 @@ boolean hasRealmForAdmission(WorldView world, String selector) { } public Optional resolveDefaultRealm(WorldView world) { + if (world == null) { + return Optional.empty(); + } + List visibleRealms = visibleRealms(world); + if (visibleRealms.isEmpty()) { + return Optional.empty(); + } + return resolveDefaultRealm(world, normalizeWorlds(worldSupplier.get())); + } + + private Optional resolveDefaultRealm(WorldView world, List catalogWorlds) { if (world == null) { return Optional.empty(); } @@ -116,23 +214,95 @@ public Optional resolveDefaultRealm(WorldView world) { } if (publicProductionRealms.size() == 1) { RealmView publicRealm = publicProductionRealms.getFirst(); - return hasValidPublicProductionRealm(publicRealm.tenantId()) + return hasValidPublicProductionRealm(catalogWorlds, publicRealm.tenantId()) ? Optional.of(publicRealm) : Optional.empty(); } - // Preserve explicit non-public presentation when the selected tenant has a valid public - // production realm elsewhere in the catalogue. A tenant with zero public realms is invalid - // authority, so it must not become a default by falling back to the first visible row. return visibleRealms.stream() - .allMatch(realm -> hasValidPublicProductionRealm(realm.tenantId())) + .allMatch(realm -> hasValidPublicProductionRealm(catalogWorlds, realm.tenantId())) ? Optional.of(visibleRealms.getFirst()) : Optional.empty(); } + private boolean hasValidPublicProductionRealm(List catalogWorlds, long tenantId) { + long count = + catalogWorlds.stream() + .flatMap(world -> world.realms().stream()) + .filter(realm -> realm.tenantId() == tenantId) + .filter(this::isPlayerAddressable) + .filter(RealmView::publicProductionRealm) + .count(); + return count == 1L; + } + + private static String worldTargetFingerprint(WorldView world, RealmView defaultRealm) { + return fingerprint( + List.of( + world.slug(), + world.displayName(), + Long.toString(defaultRealm.tenantId()), + defaultRealm.slug(), + Long.toString(defaultRealm.catalogRevision()), + Long.toString(defaultRealm.pointerVersion()), + defaultRealm.realmId() == null ? "" : defaultRealm.realmId().toString(), + defaultRealm.playableStateNamespaceId() == null + ? "" + : defaultRealm.playableStateNamespaceId().toString(), + Long.toString(defaultRealm.gameInstanceId()), + Boolean.toString(defaultRealm.requiresCharacterSelection()), + defaultRealm.stateScope() == null ? "" : defaultRealm.stateScope(), + defaultRealm.characterCreationPolicy() == null + ? "" + : defaultRealm.characterCreationPolicy())); + } + + private static String targetFingerprintInput(WorldOrdinalTarget target) { + return target.ordinal() + + "|" + + target.worldSlug() + + "|" + + target.tenantId() + + "|" + + target.catalogRevision() + + "|" + + target.targetFingerprint(); + } + + private static String fingerprint(List values) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + digest.update(bytes); + } + return java.util.HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + public record DiscoverySnapshot( + WorldsViewOutput output, + String catalogFingerprint, + List ordinalTargets, + List visibleWorlds) { + public DiscoverySnapshot { + Objects.requireNonNull(output, "output must not be null"); + if (catalogFingerprint == null || catalogFingerprint.isBlank()) { + throw new IllegalArgumentException("catalogFingerprint must not be blank"); + } + ordinalTargets = + List.copyOf(Objects.requireNonNull(ordinalTargets, "ordinalTargets must not be null")); + visibleWorlds = + List.copyOf(Objects.requireNonNull(visibleWorlds, "visibleWorlds must not be null")); + } + } + /** * Returns the tenant-wide cardinality of visible, player-addressable public-production realms. - * The scan intentionally spans every authored world because a tenant may have candidates in - * more than one world selector. + * The scan intentionally spans every authored world because a tenant may have candidates in more + * than one world selector. */ public PublicProductionRealmCardinality publicProductionRealmCardinality(long tenantId) { if (tenantId <= 0L) { @@ -167,6 +337,17 @@ public boolean hasValidPublicProductionRealm(WorldView world) { .allMatch(this::hasValidPublicProductionRealm); } + public boolean hasValidPublicProductionRealm(DiscoverySnapshot snapshot, WorldView world) { + Objects.requireNonNull(snapshot, "snapshot must not be null"); + List visibleRealms = visibleRealms(world); + return !visibleRealms.isEmpty() + && visibleRealms.stream() + .map(RealmView::tenantId) + .distinct() + .allMatch( + tenantId -> hasValidPublicProductionRealm(snapshot.visibleWorlds(), tenantId)); + } + public boolean requiresExplicitRealmSelection(WorldView world) { return visibleRealms(world).size() > 1; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java index 6c425dd50a..2761f5c06b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java @@ -68,25 +68,6 @@ public LogoutCommandHandler( "directTextConnectScopeSessionStore must not be null"); } - public LogoutCommandHandler( - SessionAuthenticationService sessionAuthenticationService, - SessionContextService sessionContextService, - GameInstanceService gameInstanceService, - GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, - GameplayPresenceLifecycleService gameplayPresenceLifecycleService, - FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, - ScriptEventPublisher scriptEventPublisher) { - this( - sessionAuthenticationService, - sessionContextService, - gameInstanceService, - gameplayAdmissionPointerAuthorityService, - gameplayPresenceLifecycleService, - firstPartyConnectContextRegistry, - scriptEventPublisher, - new DirectTextConnectScopeSessionStore()); - } - public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) { Objects.requireNonNull(command, "command must not be null"); Optional maybePersistedContext = resolvePersistedSessionContext(sessionId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index edb65d2619..98b697d758 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.OptionalLong; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; @@ -63,32 +64,78 @@ public WorldsCommandHandler( this.entityManagementClient = Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.accountClient = null; - this.connectScopeSessionStore = new DirectTextConnectScopeSessionStore(); + this.connectScopeSessionStore = null; } public WorldsViewOutput browseView() { return worldCatalog.browseView(); } + public WorldsViewOutput browseView( + String transportSessionId, Optional maybeCaller) { + long sessionId = requireTransportSessionId(transportSessionId); + Objects.requireNonNull(maybeCaller, "maybeCaller must not be null"); + if (maybeCaller.isPresent() && maybeCaller.orElseThrow().sessionId() != sessionId) { + throw new DirectTextConnectScopeSessionStore.ConflictingIdentityException( + "transport session did not match authenticated session"); + } + if (connectScopeSessionStore == null) { + throw new DirectTextConnectScopeSessionStore.StoreUnavailableException( + "lobby snapshot storage is unavailable"); + } + GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); + connectScopeSessionStore.replaceWorldSnapshot( + sessionId, + maybeCaller.map(SessionContext::accountId).orElse(0L), + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + Instant.now()); + return snapshot.output(); + } + public java.util.Optional browseRealms(String worldSelector) { return worldCatalog.browseRealms(worldSelector); } public RealmBrowseResult browseRealms(SessionContext sessionContext, String worldSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); - if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + return browseRealms(Long.toString(sessionContext.sessionId()), sessionContext, worldSelector); + } + + public RealmBrowseResult browseRealms( + String transportSessionId, SessionContext sessionContext, String worldSelector) { + Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + OptionalLong parsedSessionId = parseTransportSessionId(transportSessionId); + if (sessionContext.accountId() <= 0 || parsedSessionId.isEmpty()) { return RealmBrowseResult.failure("LOGIN_REQUIRED"); } - if (connectScopeSessionStore != null) { - connectScopeSessionStore.clearWorldScopes(sessionContext, worldSelector); + if (parsedSessionId.getAsLong() != sessionContext.sessionId()) { + return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } - Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); - if (maybeWorld.isEmpty()) { + GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot = worldCatalog.readDiscoverySnapshot(); + WorldSelectorResolution selection = + resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); + if (selection instanceof WorldSelectorResolution.Invalid) { return RealmBrowseResult.invalidSelector(); } + if (selection instanceof WorldSelectorResolution.Stale) { + return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + } + if (selection instanceof WorldSelectorResolution.Unavailable) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } - GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); - if (!worldCatalog.hasValidPublicProductionRealm(world)) { + GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); + if (connectScopeSessionStore == null) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + try { + connectScopeSessionStore.clearWorldScopes(sessionContext, worldSelector); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + if (!worldCatalog.hasValidPublicProductionRealm(catalogSnapshot, world)) { return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } List visibleEntries = new ArrayList<>(); @@ -109,7 +156,7 @@ public RealmBrowseResult browseRealms(SessionContext sessionContext, String worl } } if (realm.publicProductionRealm()) { - if (accountClient == null || connectScopeSessionStore == null) { + if (accountClient == null) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); } DirectTextConnectScopeTarget target = connectScopeTarget(world, realm); @@ -145,11 +192,98 @@ public RealmBrowseResult browseRealms(SessionContext sessionContext, String worl visibleEntries.add(realmEntry(visibleEntries.size() + 1, realm)); } - connectScopeSessionStore.replaceWorldScopes( - sessionContext, worldSelector, world.slug(), issuedScopes); + try { + connectScopeSessionStore.replaceWorldScopes( + sessionContext, worldSelector, world.slug(), issuedScopes); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } return RealmBrowseResult.success(new RealmBrowseViewOutput(world.slug(), visibleEntries)); } + private WorldSelectorResolution resolveLobbyWorld( + SessionContext caller, + String selector, + GameplayWorldCatalog.DiscoverySnapshot currentCatalog) { + if (selector == null || selector.isBlank()) { + return new WorldSelectorResolution.Invalid(); + } + if (!GameplayWorldCatalog.isOrdinalSelector(selector)) { + return worldCatalog + .resolveStableWorld(currentCatalog, selector) + .map(WorldSelectorResolution.Selected::new) + .orElseGet(WorldSelectorResolution.Invalid::new); + } + if (connectScopeSessionStore == null) { + return new WorldSelectorResolution.Unavailable(); + } + Optional maybeSnapshot; + try { + maybeSnapshot = connectScopeSessionStore.worldsSnapshot(caller, Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return new WorldSelectorResolution.Unavailable(); + } + if (maybeSnapshot.isEmpty()) { + return new WorldSelectorResolution.Stale(); + } + DirectTextConnectScopeSessionStore.WorldsSnapshot worldsSnapshot = maybeSnapshot.orElseThrow(); + if (!worldsSnapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + return new WorldSelectorResolution.Stale(); + } + int ordinal; + try { + ordinal = Integer.parseInt(selector.trim()); + } catch (NumberFormatException ex) { + return new WorldSelectorResolution.Stale(); + } + Optional maybeTarget = + worldsSnapshot.ordinalTargets().stream() + .filter(target -> target.ordinal() == ordinal) + .findFirst(); + if (maybeTarget.isEmpty()) { + return new WorldSelectorResolution.Stale(); + } + return worldCatalog + .resolveSnapshotOrdinal(currentCatalog, maybeTarget.orElseThrow()) + .map(WorldSelectorResolution.Selected::new) + .orElseGet(WorldSelectorResolution.Stale::new); + } + + private static OptionalLong parseTransportSessionId(String sessionId) { + if (sessionId == null || sessionId.isBlank()) { + return OptionalLong.empty(); + } + String trimmed = sessionId.trim(); + if (!trimmed.chars().allMatch(Character::isDigit)) { + return OptionalLong.empty(); + } + try { + long parsed = Long.parseLong(trimmed); + return parsed > 0L ? OptionalLong.of(parsed) : OptionalLong.empty(); + } catch (NumberFormatException ex) { + return OptionalLong.empty(); + } + } + + private static long requireTransportSessionId(String sessionId) { + return parseTransportSessionId(sessionId) + .orElseThrow( + () -> + new IllegalArgumentException("positive numeric transport session ID is required")); + } + + private sealed interface WorldSelectorResolution { + record Selected(GameplayWorldCatalog.WorldView world) implements WorldSelectorResolution {} + + record Invalid() implements WorldSelectorResolution {} + + record Stale() implements WorldSelectorResolution {} + + record Unavailable() implements WorldSelectorResolution {} + } + private NonPublicRealmAuthorization authorizeNonPublicRealm( SessionContext sessionContext, GameplayWorldCatalog.WorldView world, @@ -207,8 +341,7 @@ private NonPublicRealmAuthorization authorizeNonPublicRealm( } GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime( - Long.toString(realm.tenantId()), requestId); + accountClient.getTenantEntitlementsForRuntime(Long.toString(realm.tenantId()), requestId); if (entitlementResponse == null) { return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; } @@ -233,8 +366,7 @@ private NonPublicRealmAuthorization authorizeNonPublicRealm( } private boolean isValidEntitlement( - GetTenantEntitlementsForRuntimeResponse response, - GameplayWorldCatalog.RealmView realm) { + GetTenantEntitlementsForRuntimeResponse response, GameplayWorldCatalog.RealmView realm) { return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) && response.getEntitlementVersion() > 0L && response.getTenantBillingSequence() > 0L @@ -331,15 +463,32 @@ private enum NonPublicRealmAuthorization { public JoinMembershipResult joinPublicProductionMembership( SessionContext sessionContext, String worldSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + return joinPublicProductionMembership( + Long.toString(sessionContext.sessionId()), sessionContext, worldSelector); + } + + public JoinMembershipResult joinPublicProductionMembership( + String transportSessionId, SessionContext sessionContext, String worldSelector) { + Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + OptionalLong parsedSessionId = parseTransportSessionId(transportSessionId); + if (parsedSessionId.isEmpty() || parsedSessionId.getAsLong() != sessionContext.sessionId()) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { return JoinMembershipResult.failure("LOGIN_REQUIRED"); } if (accountClient == null || connectScopeSessionStore == null) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } - Optional maybeJoinScope = - connectScopeSessionStore.publicProductionScopeForJoin( - sessionContext, worldSelector, Instant.now()); + Optional maybeJoinScope; + try { + maybeJoinScope = + connectScopeSessionStore.publicProductionScopeForJoin( + sessionContext, worldSelector, Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } if (maybeJoinScope.isEmpty()) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } @@ -457,15 +606,36 @@ record Failure(String code) implements JoinMembershipResult {} public CharacterBrowseResult browseCharacters( SessionContext sessionContext, String worldSelector, String realmSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); - if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + return browseCharacters( + Long.toString(sessionContext.sessionId()), sessionContext, worldSelector, realmSelector); + } + + public CharacterBrowseResult browseCharacters( + String transportSessionId, + SessionContext sessionContext, + String worldSelector, + String realmSelector) { + Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + OptionalLong parsedSessionId = parseTransportSessionId(transportSessionId); + if (sessionContext.accountId() <= 0 || parsedSessionId.isEmpty()) { return CharacterBrowseResult.failure("LOGIN_REQUIRED"); } - java.util.Optional maybeWorld = - worldCatalog.resolveWorld(worldSelector); - if (maybeWorld.isEmpty()) { + if (parsedSessionId.getAsLong() != sessionContext.sessionId()) { + return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + } + GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot = worldCatalog.readDiscoverySnapshot(); + WorldSelectorResolution selection = + resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); + if (selection instanceof WorldSelectorResolution.Invalid) { return CharacterBrowseResult.invalidWorld(); } - GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); + if (selection instanceof WorldSelectorResolution.Stale) { + return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + } + if (selection instanceof WorldSelectorResolution.Unavailable) { + return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } + GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); java.util.Optional maybeRealm = StringUtils.hasText(realmSelector) ? worldCatalog.resolveRealm(world, realmSelector) @@ -480,7 +650,7 @@ public CharacterBrowseResult browseCharacters( } GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); - if (!worldCatalog.hasValidPublicProductionRealm(realm.tenantId()) + if (!worldCatalog.hasValidPublicProductionRealm(catalogSnapshot, world) || !hasCompleteSelectedRealmPointerEvidence(realm)) { return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } @@ -531,9 +701,7 @@ public CharacterBrowseResult browseCharacters( } private CharacterBrowseAuthorization authorizePublicCharacterBrowse( - SessionContext sessionContext, - GameplayWorldCatalog.RealmView realm, - String requestId) { + SessionContext sessionContext, GameplayWorldCatalog.RealmView realm, String requestId) { if (accountClient == null) { return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; } @@ -654,8 +822,7 @@ private boolean isValidMembershipAuthoritySnapshot( && !response.getGameplayAdmissionAllowed(); } - private boolean hasCompleteSelectedRealmPointerEvidence( - GameplayWorldCatalog.RealmView realm) { + private boolean hasCompleteSelectedRealmPointerEvidence(GameplayWorldCatalog.RealmView realm) { return realm.visible() && realm.tenantId() > 0L && realm.gameInstanceId() > 0L diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index fabffe5266..518c9b9bca 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.command.text; import java.util.List; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import org.slf4j.Logger; @@ -28,12 +29,7 @@ public TextCommandDispatchGroup group() { public TextCommandInterpretationResult handle(TextCommandDispatchRequest request) { TextCommandInterpretationResult result = switch (request.command().type()) { - case WORLDS -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( - worldsHandler.browseView()))); + case WORLDS -> handleWorlds(request); case REALMS -> handleRealms(request); case JOIN -> handleJoin(request); case CHARS -> handleChars(request); @@ -53,6 +49,22 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request return result; } + private TextCommandInterpretationResult handleWorlds(TextCommandDispatchRequest request) { + try { + return new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( + worldsHandler.browseView(request.sessionId(), request.sessionContext())))); + } catch (IllegalArgumentException ex) { + return errorResult( + "INVALID_ARGUMENT", "Transport session is unavailable. Reconnect and try again."); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return errorResult("AUTH_UNAVAILABLE", "World list is temporarily unavailable."); + } + } + private TextCommandInterpretationResult handleRealms(TextCommandDispatchRequest request) { if (request.command().realmBrowsePayload().isEmpty() || request.sessionContext().isEmpty()) { return errorResult("INVALID_ARGUMENT", "REALMS requires a world selector after LOGIN."); @@ -60,7 +72,7 @@ private TextCommandInterpretationResult handleRealms(TextCommandDispatchRequest TextCommandPayload.RealmBrowseRequest payload = request.command().realmBrowsePayload().orElseThrow(); return switch (worldsHandler.browseRealms( - request.sessionContext().orElseThrow(), payload.worldSelector())) { + request.sessionId(), request.sessionContext().orElseThrow(), payload.worldSelector())) { case WorldsCommandHandler.RealmBrowseResult.Success success -> new TextCommandInterpretationResult( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), @@ -81,7 +93,7 @@ private TextCommandInterpretationResult handleJoin(TextCommandDispatchRequest re } TextCommandPayload.JoinRequest payload = request.command().joinRequestPayload().orElseThrow(); return switch (worldsHandler.joinPublicProductionMembership( - request.sessionContext().orElseThrow(), payload.worldSelector())) { + request.sessionId(), request.sessionContext().orElseThrow(), payload.worldSelector())) { case WorldsCommandHandler.JoinMembershipResult.Failure failure -> errorResult(failure.code(), joinFailureMessage(failure.code())); case WorldsCommandHandler.JoinMembershipResult.Response response -> @@ -142,7 +154,10 @@ private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest r TextCommandPayload.CharacterBrowseRequest payload = request.command().characterBrowsePayload().orElseThrow(); return switch (worldsHandler.browseCharacters( - request.sessionContext().orElseThrow(), payload.worldSelector(), payload.realmSelector())) { + request.sessionId(), + request.sessionContext().orElseThrow(), + payload.worldSelector(), + payload.realmSelector())) { case WorldsCommandHandler.CharacterBrowseResult.Success success -> new TextCommandInterpretationResult( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), @@ -180,8 +195,7 @@ private String characterBrowseFailureMessage(String code) { "Existing membership is required before browsing characters in that realm."; case "PUBLIC_PRODUCTION_ADMISSION_DENIED" -> "Public joining is not available for this world."; - case "TENANT_BILLING_BLOCKED" -> - "That world is temporarily unavailable for gameplay."; + case "TENANT_BILLING_BLOCKED" -> "That world is temporarily unavailable for gameplay."; case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> "Character authority unavailable. Retry CHARS shortly."; case "ENTITLEMENT_UNAVAILABLE" -> diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index e362bbc763..4e9d7be6a3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -1,7 +1,10 @@ package net.firedevops.firemud.gamesession.service; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.time.Duration; import java.time.Instant; +import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -11,15 +14,125 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; -import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.stereotype.Component; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; -/** Holds Account-issued direct-text scopes only for the transport session that resolved them. */ +/** + * Stores direct-text lobby snapshots and Account-issued scopes by the stable transport session ID. + * Production state is shared through Redis so it survives Game Session instance replacement. + */ @Component public final class DirectTextConnectScopeSessionStore { - private final ConcurrentMap scopesBySessionId = new ConcurrentHashMap<>(); + private static final String KEY_TEMPLATE = "gamesession:lobby:%d"; + private static final Duration WORLDS_SNAPSHOT_TTL = Duration.ofMinutes(5); + private static final Duration MAX_ACCOUNT_SCOPE_TTL = Duration.ofMinutes(15); + private static final int MAX_CAS_ATTEMPTS = 16; + private static final DefaultRedisScript COMPARE_AND_SET_SCRIPT = buildCompareAndSetScript(); + + private final Backend backend; + private final ObjectMapper objectMapper; + + @Autowired + public DirectTextConnectScopeSessionStore( + StringRedisTemplate redisTemplate, ObjectMapper objectMapper) { + this( + new RedisBackend(Objects.requireNonNull(redisTemplate, "redisTemplate must not be null")), + Objects.requireNonNull(objectMapper, "objectMapper must not be null")); + } + + private DirectTextConnectScopeSessionStore(Backend backend, ObjectMapper objectMapper) { + this.backend = Objects.requireNonNull(backend, "backend must not be null"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); + } + + /** + * Creates isolated in-memory storage for focused unit tests; production construction is + * Redis-only. + */ + public static DirectTextConnectScopeSessionStore inMemoryForTest() { + return new DirectTextConnectScopeSessionStore(new InMemoryBackend(), new ObjectMapper()); + } + + public void replaceWorldSnapshot( + long transportSessionId, + long authenticatedAccountId, + String catalogFingerprint, + List ordinalTargets, + Instant now) { + requireTransportSessionId(transportSessionId); + if (authenticatedAccountId < 0L) { + throw new IllegalArgumentException("authenticatedAccountId must not be negative"); + } + Objects.requireNonNull(now, "now must not be null"); + if (catalogFingerprint == null || catalogFingerprint.isBlank()) { + throw new IllegalArgumentException("catalogFingerprint must not be blank"); + } + List safeTargets = + List.copyOf(Objects.requireNonNull(ordinalTargets, "ordinalTargets must not be null")); + validateOrdinalTargets(safeTargets); + long nowMillis = now.toEpochMilli(); + long expiresAtMillis = now.plus(WORLDS_SNAPSHOT_TTL).toEpochMilli(); + + mutate( + transportSessionId, + nowMillis, + current -> { + LobbyRecord record = current == null ? LobbyRecord.empty(transportSessionId) : current; + if (record.sessionId() != transportSessionId) { + throw new ConflictingIdentityException("lobby record transport session did not match"); + } + if (authenticatedAccountId > 0L + && record.accountId() > 0L + && record.accountId() != authenticatedAccountId) { + record = LobbyRecord.empty(transportSessionId); + } + long accountId = + authenticatedAccountId > 0L ? authenticatedAccountId : record.accountId(); + return record.withWorldSnapshot( + accountId, expiresAtMillis, catalogFingerprint, safeTargets); + }); + } + + public Optional worldsSnapshot(SessionContext caller, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); + requireCallerIdentity(caller); + LobbyRecord record = readRecord(caller.sessionId()); + if (record == null + || record.sessionId() != caller.sessionId() + || (record.accountId() > 0L && record.accountId() != caller.accountId())) { + return Optional.empty(); + } + return asWorldsSnapshot(record, now); + } + + public Optional worldsSnapshot(long transportSessionId, Instant now) { + requireTransportSessionId(transportSessionId); + Objects.requireNonNull(now, "now must not be null"); + LobbyRecord record = readRecord(transportSessionId); + if (record == null || record.sessionId() != transportSessionId) { + return Optional.empty(); + } + return asWorldsSnapshot(record, now); + } + + private Optional asWorldsSnapshot(LobbyRecord record, Instant now) { + if (record.worldsExpiresAtEpochMs() <= now.toEpochMilli() + || record.catalogFingerprint() == null + || record.ordinalTargets().isEmpty()) { + return Optional.empty(); + } + return Optional.of( + new WorldsSnapshot( + record.catalogFingerprint(), + Instant.ofEpochMilli(record.worldsExpiresAtEpochMs()), + record.ordinalTargets())); + } public void replaceWorldScopes( SessionContext caller, @@ -35,59 +148,83 @@ public void replaceWorldScopes( } List safeScopes = List.copyOf(Objects.requireNonNull(scopes, "scopes must not be null")); - if (safeScopes.stream().anyMatch(scope -> scope.playerContext().getAccountId().isBlank())) { - throw new IllegalArgumentException("scope caller identity must not be blank"); - } - safeScopes.forEach( - scope -> { - if (!scope.playerContext().getAccountId().equals(Long.toString(caller.accountId())) - || !scope.playerContext().getSessionId().equals(Long.toString(caller.sessionId()))) { - throw new IllegalArgumentException("scope caller identity did not match session"); - } - }); + safeScopes.forEach(scope -> validateScopeIdentity(caller, scope)); + long nowMillis = Instant.now().toEpochMilli(); + List storedScopes = + safeScopes.stream() + .filter(scope -> scope.expiresAt().toEpochMilli() > nowMillis) + .map(scope -> storeScope(scope, nowMillis)) + .toList(); - scopesBySessionId.compute( + mutate( caller.sessionId(), - (sessionId, existing) -> { - Map> byWorld = new HashMap<>(); - Map worldBySelector = new HashMap<>(); - if (existing != null && existing.accountId() == caller.accountId()) { - byWorld.putAll(existing.scopesByWorld()); - worldBySelector.putAll(existing.worldBySelector()); + nowMillis, + current -> { + LobbyRecord record = current == null ? LobbyRecord.empty(caller.sessionId()) : current; + if (record.sessionId() != caller.sessionId()) { + throw new ConflictingIdentityException("lobby record transport session did not match"); + } + if (record.accountId() > 0L && record.accountId() != caller.accountId()) { + record = LobbyRecord.empty(caller.sessionId()).withWorldSnapshotFrom(record); + } + Map> byWorld = new HashMap<>(record.scopesByWorld()); + Map worldBySelector = new HashMap<>(record.worldBySelector()); + byWorld.remove(worldSlug); + worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); + if (!storedScopes.isEmpty()) { + byWorld.put(worldSlug, storedScopes); + worldBySelector.put(worldSlug, worldSlug); + worldBySelector.put(requestedSelector, worldSlug); } - byWorld.put(worldSlug, safeScopes); - worldBySelector.put(worldSlug, worldSlug); - worldBySelector.put(requestedSelector, worldSlug); - return new SessionScopes( - caller.accountId(), Map.copyOf(byWorld), Map.copyOf(worldBySelector)); + return new LobbyRecord( + caller.sessionId(), + caller.accountId(), + record.worldsExpiresAtEpochMs(), + record.catalogFingerprint(), + record.ordinalTargets(), + byWorld, + worldBySelector); }); } public void clearWorldScopes(SessionContext caller, String worldSelector) { Objects.requireNonNull(caller, "caller must not be null"); + requireCallerIdentity(caller); String selector = normalizeSelector(worldSelector); if (selector == null) { return; } - scopesBySessionId.computeIfPresent( + long nowMillis = Instant.now().toEpochMilli(); + mutate( caller.sessionId(), - (sessionId, existing) -> { - if (existing.accountId() != caller.accountId()) { + nowMillis, + current -> { + if (current == null) { return null; } - String worldSlug = existing.worldBySelector().get(selector); + if (current.sessionId() != caller.sessionId()) { + throw new ConflictingIdentityException("lobby record transport session did not match"); + } + LobbyRecord record = current; + if (record.accountId() > 0L && record.accountId() != caller.accountId()) { + record = LobbyRecord.empty(caller.sessionId()).withWorldSnapshotFrom(record); + } + String worldSlug = record.worldBySelector().get(selector); if (worldSlug == null) { - return existing; + return record.withAccountId(caller.accountId()); } - Map> byWorld = new HashMap<>(existing.scopesByWorld()); + Map> byWorld = new HashMap<>(record.scopesByWorld()); byWorld.remove(worldSlug); - Map worldBySelector = new HashMap<>(existing.worldBySelector()); + Map worldBySelector = new HashMap<>(record.worldBySelector()); worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); - if (byWorld.isEmpty()) { - return null; - } - return new SessionScopes( - existing.accountId(), Map.copyOf(byWorld), Map.copyOf(worldBySelector)); + return new LobbyRecord( + caller.sessionId(), + caller.accountId(), + record.worldsExpiresAtEpochMs(), + record.catalogFingerprint(), + record.ordinalTargets(), + byWorld, + worldBySelector); }); } @@ -100,31 +237,24 @@ public Optional publicProductionScope( if (selector == null) { return Optional.empty(); } - SessionScopes sessionScopes = scopesBySessionId.get(caller.sessionId()); - if (sessionScopes == null || sessionScopes.accountId() != caller.accountId()) { - if (sessionScopes != null) { - scopesBySessionId.remove(caller.sessionId(), sessionScopes); - } + LobbyRecord record = readRecord(caller.sessionId()); + if (!matchesCaller(record, caller)) { return Optional.empty(); } - String canonicalWorldSlug = sessionScopes.worldBySelector().get(selector); - if (canonicalWorldSlug == null) { + String worldSlug = record.worldBySelector().get(selector); + if (worldSlug == null) { return Optional.empty(); } - List validScopes = - sessionScopes.scopesByWorld().getOrDefault(canonicalWorldSlug, List.of()).stream() + List publicScopes = + record.scopesByWorld().getOrDefault(worldSlug, List.of()).stream() + .map(DirectTextConnectScopeSessionStore::fromStoredScope) .filter(scope -> scope.expiresAt().isAfter(now)) + .filter(ScopedRealm::publicProductionRealm) .toList(); - List publicScopes = - validScopes.stream().filter(ScopedRealm::publicProductionRealm).toList(); return publicScopes.size() == 1 ? Optional.of(publicScopes.getFirst()) : Optional.empty(); } - /** - * Resolves a public scope and atomically binds one stable JOIN request ID to that scope. Repeated - * JOIN commands reuse the ID; a fresh REALMS response replaces the scope and starts a new logical - * attempt. - */ + /** Atomically binds and reuses one JOIN request ID for the exact Account scope. */ public Optional publicProductionScopeForJoin( SessionContext caller, String worldSelector, Instant now) { Objects.requireNonNull(caller, "caller must not be null"); @@ -134,111 +264,291 @@ public Optional publicProductionScopeForJoin( if (selector == null) { return Optional.empty(); } - AtomicReference selected = new AtomicReference<>(); - scopesBySessionId.computeIfPresent( + long nowMillis = now.toEpochMilli(); + JoinScope[] selected = new JoinScope[1]; + mutate( caller.sessionId(), - (sessionId, sessionScopes) -> { - if (sessionScopes.accountId() != caller.accountId()) { - return sessionScopes; + nowMillis, + current -> { + selected[0] = null; + if (!matchesCaller(current, caller)) { + return current; } - String worldSlug = sessionScopes.worldBySelector().get(selector); + String worldSlug = current.worldBySelector().get(selector); if (worldSlug == null) { - return sessionScopes; + return current; } - List scopes = - sessionScopes.scopesByWorld().getOrDefault(worldSlug, List.of()); - List validPublicScopes = + List scopes = + current.scopesByWorld().getOrDefault(worldSlug, List.of()); + List validPublicScopes = scopes.stream() - .filter(scope -> scope.expiresAt().isAfter(now)) - .filter(ScopedRealm::publicProductionRealm) + .filter(scope -> scope.expiresAtEpochMs() > nowMillis) + .filter(StoredScopedRealm::publicProductionRealm) .toList(); if (validPublicScopes.size() != 1) { - return sessionScopes; + return current; } - - ScopedRealm scope = validPublicScopes.getFirst(); + StoredScopedRealm scope = validPublicScopes.getFirst(); String requestId = scope.joinRequestId(); - ScopedRealm boundScope = scope; - if (requestId.isBlank()) { + StoredScopedRealm boundScope = scope; + if (requestId == null || requestId.isBlank()) { requestId = UUID.randomUUID().toString(); boundScope = scope.withJoinRequestId(requestId); } - if (boundScope != scope) { - ScopedRealm updatedScope = boundScope; - List updatedScopes = + StoredScopedRealm scopeToReplace = scope; + StoredScopedRealm scopeToStore = boundScope; + List updatedScopes = scopes.stream() - .map( - candidate -> - candidate.connectScopeId().equals(scope.connectScopeId()) - ? updatedScope - : candidate) + .map(candidate -> candidate == scopeToReplace ? scopeToStore : candidate) .toList(); - Map> byWorld = new HashMap<>(sessionScopes.scopesByWorld()); + Map> byWorld = new HashMap<>(current.scopesByWorld()); byWorld.put(worldSlug, updatedScopes); - sessionScopes = - new SessionScopes( - sessionScopes.accountId(), byWorld, sessionScopes.worldBySelector()); + current = current.withScopes(byWorld, current.worldBySelector()); } - selected.set(new JoinScope(boundScope, requestId)); - return sessionScopes; - }); - return Optional.ofNullable(selected.get()); - } - - public void clearSession(long sessionId) { - scopesBySessionId.remove(sessionId); - } - - @Scheduled(fixedDelay = 60_000L) - void removeExpiredScopes() { - Instant now = Instant.now(); - scopesBySessionId.forEach( - (sessionId, current) -> { - Map> remainingByWorld = new HashMap<>(); - current - .scopesByWorld() - .forEach( - (worldSlug, worldScopes) -> { - List remaining = - worldScopes.stream() - .filter(scope -> scope.expiresAt().isAfter(now)) - .toList(); - if (!remaining.isEmpty()) { - remainingByWorld.put(worldSlug, remaining); - } - }); - if (remainingByWorld.isEmpty()) { - scopesBySessionId.remove(sessionId, current); - return; - } - Map remainingSelectors = new HashMap<>(current.worldBySelector()); - remainingSelectors - .entrySet() - .removeIf(entry -> !remainingByWorld.containsKey(entry.getValue())); - SessionScopes updated = - new SessionScopes( - current.accountId(), - Map.copyOf(remainingByWorld), - Map.copyOf(remainingSelectors)); - scopesBySessionId.replace(sessionId, current, updated); + selected[0] = new JoinScope(fromStoredScope(boundScope), requestId); + return current; }); + return Optional.ofNullable(selected[0]); + } + + public void clearSession(long transportSessionId) { + requireTransportSessionId(transportSessionId); + backend.delete(key(transportSessionId)); + } + + private void mutate(long transportSessionId, long nowMillis, RecordMutation mutation) { + requireTransportSessionId(transportSessionId); + String key = key(transportSessionId); + for (int attempt = 0; attempt < MAX_CAS_ATTEMPTS; attempt++) { + String currentRaw = backend.get(key); + LobbyRecord current = decode(currentRaw, transportSessionId); + LobbyRecord updated = pruneExpired(mutation.apply(current), nowMillis); + String updatedRaw = encode(updated); + long ttlMillis = remainingTtlMillis(updated, nowMillis); + boolean write = ttlMillis > 0L && updated != null; + if (backend.compareAndSet(key, currentRaw, updatedRaw, write, Math.max(ttlMillis, 1L))) { + return; + } + } + throw new StoreUnavailableException("lobby state changed too often to update atomically"); + } + + private LobbyRecord readRecord(long transportSessionId) { + requireTransportSessionId(transportSessionId); + String currentRaw = backend.get(key(transportSessionId)); + return decode(currentRaw, transportSessionId); + } + + private LobbyRecord decode(String json, long expectedSessionId) { + if (json == null) { + return null; + } + try { + LobbyRecord record = objectMapper.readValue(json, LobbyRecord.class); + if (record == null || record.sessionId() != expectedSessionId || record.accountId() < 0L) { + throw new ConflictingIdentityException("lobby state identity was invalid"); + } + return record.normalized(); + } catch (JacksonException ex) { + throw new StoreUnavailableException("lobby state could not be decoded", ex); + } + } + + private String encode(LobbyRecord record) { + if (record == null) { + return null; + } + try { + return objectMapper.writeValueAsString(record.normalized()); + } catch (JacksonException ex) { + throw new StoreUnavailableException("lobby state could not be encoded", ex); + } + } + + private LobbyRecord pruneExpired(LobbyRecord record, long nowMillis) { + if (record == null) { + return null; + } + long worldsExpiry = + record.worldsExpiresAtEpochMs() > nowMillis ? record.worldsExpiresAtEpochMs() : 0L; + String fingerprint = worldsExpiry > 0L ? record.catalogFingerprint() : null; + List ordinalTargets = + worldsExpiry > 0L ? record.ordinalTargets() : List.of(); + Map> scopesByWorld = new HashMap<>(); + record + .scopesByWorld() + .forEach( + (world, scopes) -> { + List remaining = + scopes.stream().filter(scope -> scope.expiresAtEpochMs() > nowMillis).toList(); + if (!remaining.isEmpty()) { + scopesByWorld.put(world, remaining); + } + }); + Map worldBySelector = new HashMap<>(record.worldBySelector()); + worldBySelector.entrySet().removeIf(entry -> !scopesByWorld.containsKey(entry.getValue())); + if (worldsExpiry == 0L && scopesByWorld.isEmpty()) { + return null; + } + return new LobbyRecord( + record.sessionId(), + record.accountId(), + worldsExpiry, + fingerprint, + ordinalTargets, + scopesByWorld, + worldBySelector); } - private void requireCallerIdentity(SessionContext caller) { - if (caller.accountId() <= 0 || caller.sessionId() <= 0) { - throw new IllegalArgumentException( - "authenticated account and transport session are required"); + private long remainingTtlMillis(LobbyRecord record, long nowMillis) { + if (record == null) { + return 0L; + } + long maxExpiry = record.worldsExpiresAtEpochMs(); + for (List scopes : record.scopesByWorld().values()) { + for (StoredScopedRealm scope : scopes) { + maxExpiry = Math.max(maxExpiry, scope.expiresAtEpochMs()); + } } + return maxExpiry - nowMillis; } - private String normalizeSelector(String selector) { + private StoredScopedRealm storeScope(ScopedRealm scope, long nowMillis) { + long requestedExpiry = scope.expiresAt().toEpochMilli(); + long boundedExpiry = Math.min(requestedExpiry, nowMillis + MAX_ACCOUNT_SCOPE_TTL.toMillis()); + if (boundedExpiry <= nowMillis) { + throw new IllegalArgumentException("Account scope must not be expired"); + } + String contextBase64 = Base64.getEncoder().encodeToString(scope.playerContext().toByteArray()); + return new StoredScopedRealm( + scope.realmSlug(), + scope.publicProductionRealm(), + scope.connectScopeId(), + boundedExpiry, + contextBase64, + scope.joinRequestId()); + } + + private static ScopedRealm fromStoredScope(StoredScopedRealm stored) { + try { + PlayerExecutionContext context = + PlayerExecutionContext.parseFrom( + Base64.getDecoder().decode(stored.playerContextBase64())); + return new ScopedRealm( + stored.realmSlug(), + stored.publicProductionRealm(), + stored.connectScopeId(), + Instant.ofEpochMilli(stored.expiresAtEpochMs()), + context, + stored.joinRequestId()); + } catch (IOException | IllegalArgumentException ex) { + throw new StoreUnavailableException("stored Account scope was invalid", ex); + } + } + + private static void validateScopeIdentity(SessionContext caller, ScopedRealm scope) { + Objects.requireNonNull(scope, "scope must not be null"); + PlayerExecutionContext context = scope.playerContext(); + if (!Long.toString(caller.accountId()).equals(context.getAccountId()) + || !Long.toString(caller.sessionId()).equals(context.getSessionId())) { + throw new ConflictingIdentityException("Account scope caller identity did not match session"); + } + } + + private static boolean matchesCaller(LobbyRecord record, SessionContext caller) { + return record != null + && record.sessionId() == caller.sessionId() + && record.accountId() == caller.accountId(); + } + + private static void validateOrdinalTargets(List targets) { + for (int index = 0; index < targets.size(); index++) { + WorldOrdinalTarget target = + Objects.requireNonNull(targets.get(index), "target must not be null"); + if (target.ordinal() != index + 1) { + throw new IllegalArgumentException("world ordinal targets must be contiguous and ordered"); + } + } + } + + private static void requireCallerIdentity(SessionContext caller) { + if (caller.accountId() <= 0L) { + throw new IllegalArgumentException("authenticated account is required"); + } + requireTransportSessionId(caller.sessionId()); + } + + public static void requireTransportSessionId(long transportSessionId) { + if (transportSessionId <= 0L) { + throw new IllegalArgumentException("positive transport session ID is required"); + } + } + + private String key(long transportSessionId) { + return String.format(KEY_TEMPLATE, transportSessionId); + } + + private static String normalizeSelector(String selector) { if (selector == null || selector.isBlank()) { return null; } return selector.trim().toLowerCase(Locale.ROOT); } + private static DefaultRedisScript buildCompareAndSetScript() { + DefaultRedisScript script = new DefaultRedisScript<>(); + script.setResultType(Long.class); + script.setScriptText( + """ + local current = redis.call('GET', KEYS[1]) + if ARGV[1] == '1' then + if current ~= ARGV[2] then return 0 end + elseif current then + return 0 + end + if ARGV[3] == '1' then + redis.call('SET', KEYS[1], ARGV[4], 'PX', ARGV[5]) + else + redis.call('DEL', KEYS[1]) + end + return 1 + """); + return script; + } + + public record WorldOrdinalTarget( + int ordinal, + String worldSlug, + long tenantId, + long catalogRevision, + String targetFingerprint) { + public WorldOrdinalTarget { + if (ordinal < 1 || tenantId <= 0L || catalogRevision < 0L) { + throw new IllegalArgumentException("world ordinal target authority was invalid"); + } + if (worldSlug == null + || worldSlug.isBlank() + || targetFingerprint == null + || targetFingerprint.isBlank()) { + throw new IllegalArgumentException("world ordinal target identity must not be blank"); + } + } + } + + public record WorldsSnapshot( + String catalogFingerprint, Instant expiresAt, List ordinalTargets) { + public WorldsSnapshot { + if (catalogFingerprint == null || catalogFingerprint.isBlank()) { + throw new IllegalArgumentException("catalogFingerprint must not be blank"); + } + Objects.requireNonNull(expiresAt, "expiresAt must not be null"); + ordinalTargets = + List.copyOf(Objects.requireNonNull(ordinalTargets, "ordinalTargets must not be null")); + validateOrdinalTargets(ordinalTargets); + } + } + @SuppressFBWarnings( value = "EI_EXPOSE_REP", justification = "Generated protobuf execution contexts are immutable value messages.") @@ -269,11 +579,6 @@ public ScopedRealm( Objects.requireNonNull(playerContext, "playerContext must not be null"); joinRequestId = joinRequestId == null ? "" : joinRequestId; } - - private ScopedRealm withJoinRequestId(String requestId) { - return new ScopedRealm( - realmSlug, publicProductionRealm, connectScopeId, expiresAt, playerContext, requestId); - } } public record JoinScope(ScopedRealm scope, String requestId) { @@ -285,15 +590,228 @@ public record JoinScope(ScopedRealm scope, String requestId) { } } - private record SessionScopes( + public static final class StoreUnavailableException extends RuntimeException { + public StoreUnavailableException(String message) { + super(message); + } + + public StoreUnavailableException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class ConflictingIdentityException extends RuntimeException { + public ConflictingIdentityException(String message) { + super(message); + } + } + + @FunctionalInterface + private interface RecordMutation { + LobbyRecord apply(LobbyRecord current); + } + + private interface Backend { + String get(String key); + + boolean compareAndSet( + String key, String expectedValue, String newValue, boolean write, long ttlMillis); + + void delete(String key); + } + + private static final class RedisBackend implements Backend { + private final StringRedisTemplate redisTemplate; + + private RedisBackend(StringRedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + @Override + public String get(String key) { + try { + return redisTemplate.opsForValue().get(key); + } catch (RuntimeException ex) { + throw new StoreUnavailableException("Redis lobby state read failed", ex); + } + } + + @Override + public boolean compareAndSet( + String key, String expectedValue, String newValue, boolean write, long ttlMillis) { + try { + Long updated = + redisTemplate.execute( + COMPARE_AND_SET_SCRIPT, + List.of(key), + expectedValue == null ? "0" : "1", + expectedValue == null ? "" : expectedValue, + write ? "1" : "0", + newValue == null ? "" : newValue, + Long.toString(Math.max(ttlMillis, 1L))); + return Long.valueOf(1L).equals(updated); + } catch (RuntimeException ex) { + throw new StoreUnavailableException("Redis lobby state atomic update failed", ex); + } + } + + @Override + public void delete(String key) { + try { + redisTemplate.delete(key); + } catch (RuntimeException ex) { + throw new StoreUnavailableException("Redis lobby state clear failed", ex); + } + } + } + + private static final class InMemoryBackend implements Backend { + private final ConcurrentMap values = new ConcurrentHashMap<>(); + + @Override + public String get(String key) { + MemoryValue value = values.get(key); + if (value == null) { + return null; + } + if (value.expiresAtMillis() <= System.currentTimeMillis()) { + values.remove(key, value); + return null; + } + return value.value(); + } + + @Override + public synchronized boolean compareAndSet( + String key, String expectedValue, String newValue, boolean write, long ttlMillis) { + String current = get(key); + if (!Objects.equals(current, expectedValue)) { + return false; + } + if (!write) { + values.remove(key); + } else { + values.put(key, new MemoryValue(newValue, System.currentTimeMillis() + ttlMillis)); + } + return true; + } + + @Override + public void delete(String key) { + values.remove(key); + } + + private record MemoryValue(String value, long expiresAtMillis) {} + } + + private record StoredScopedRealm( + String realmSlug, + boolean publicProductionRealm, + String connectScopeId, + long expiresAtEpochMs, + String playerContextBase64, + String joinRequestId) { + private StoredScopedRealm { + Objects.requireNonNull(realmSlug, "realmSlug must not be null"); + Objects.requireNonNull(connectScopeId, "connectScopeId must not be null"); + Objects.requireNonNull(playerContextBase64, "playerContextBase64 must not be null"); + joinRequestId = joinRequestId == null ? "" : joinRequestId; + } + + private StoredScopedRealm withJoinRequestId(String requestId) { + return new StoredScopedRealm( + realmSlug, + publicProductionRealm, + connectScopeId, + expiresAtEpochMs, + playerContextBase64, + requestId); + } + } + + private record LobbyRecord( + long sessionId, long accountId, - Map> scopesByWorld, + long worldsExpiresAtEpochMs, + String catalogFingerprint, + List ordinalTargets, + Map> scopesByWorld, Map worldBySelector) { - private SessionScopes { - Map> safeWorlds = new HashMap<>(); - scopesByWorld.forEach((slug, scopes) -> safeWorlds.put(slug, List.copyOf(scopes))); - scopesByWorld = Map.copyOf(safeWorlds); - worldBySelector = Map.copyOf(worldBySelector); + private LobbyRecord { + ordinalTargets = ordinalTargets == null ? List.of() : List.copyOf(ordinalTargets); + Map> scopesCopy = new HashMap<>(); + if (scopesByWorld != null) { + scopesByWorld.forEach((slug, scopes) -> scopesCopy.put(slug, List.copyOf(scopes))); + } + scopesByWorld = Map.copyOf(scopesCopy); + worldBySelector = worldBySelector == null ? Map.of() : Map.copyOf(worldBySelector); + } + + private static LobbyRecord empty(long sessionId) { + return new LobbyRecord(sessionId, 0L, 0L, null, List.of(), Map.of(), Map.of()); + } + + private LobbyRecord normalized() { + if (sessionId <= 0L || accountId < 0L) { + throw new ConflictingIdentityException("lobby state identity was invalid"); + } + return new LobbyRecord( + sessionId, + accountId, + worldsExpiresAtEpochMs, + catalogFingerprint, + ordinalTargets, + scopesByWorld, + worldBySelector); + } + + private LobbyRecord withWorldSnapshot( + long accountId, + long expiresAtEpochMs, + String fingerprint, + List targets) { + return new LobbyRecord( + sessionId, + accountId, + expiresAtEpochMs, + fingerprint, + targets, + scopesByWorld, + worldBySelector); + } + + private LobbyRecord withWorldSnapshotFrom(LobbyRecord other) { + return new LobbyRecord( + sessionId, + accountId, + other.worldsExpiresAtEpochMs(), + other.catalogFingerprint(), + other.ordinalTargets(), + scopesByWorld, + worldBySelector); + } + + private LobbyRecord withAccountId(long updatedAccountId) { + return new LobbyRecord( + sessionId, + updatedAccountId, + worldsExpiresAtEpochMs, + catalogFingerprint, + ordinalTargets, + scopesByWorld, + worldBySelector); + } + + private LobbyRecord withScopes( + Map> updatedScopes, Map updatedSelectors) { + return new LobbyRecord( + sessionId, + accountId, + worldsExpiresAtEpochMs, + catalogFingerprint, + ordinalTargets, + updatedScopes, + updatedSelectors); } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java new file mode 100644 index 0000000000..3aef226645 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class RedisDirectTextConnectScopeSessionStoreTest { + private static final long SESSION_ID = 4401L; + private static final long ACCOUNT_ID = 7L; + private static final String REDIS_KEY = "gamesession:lobby:4401"; + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + private LettuceConnectionFactory connectionFactory; + private StringRedisTemplate redisTemplate; + + @BeforeEach + void setUpRedis() { + connectionFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379))); + connectionFactory.afterPropertiesSet(); + redisTemplate = new StringRedisTemplate(connectionFactory); + redisTemplate.afterPropertiesSet(); + redisTemplate.delete(REDIS_KEY); + } + + @AfterEach + void tearDownRedis() { + if (redisTemplate != null) { + redisTemplate.delete(REDIS_KEY); + } + if (connectionFactory != null) { + connectionFactory.destroy(); + } + } + + @Test + void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws Exception { + DirectTextConnectScopeSessionStore firstInstance = newStoreInstance(); + SessionContext caller = session(); + Instant now = Instant.now(); + DirectTextConnectScopeSessionStore.WorldOrdinalTarget target = + new DirectTextConnectScopeSessionStore.WorldOrdinalTarget( + 1, "demo-world", 22L, 13L, "target-fingerprint-v13"); + + firstInstance.replaceWorldSnapshot( + SESSION_ID, 0L, "catalog-fingerprint-v13", List.of(target), now); + firstInstance.replaceWorldScopes( + caller, + "1", + "demo-world", + List.of( + new DirectTextConnectScopeSessionStore.ScopedRealm( + "production", + true, + "account-connect-scope-17", + now.plusSeconds(600), + playerContext(caller)))); + + List replacementInstances = + java.util.stream.IntStream.range(0, 8).mapToObj(ignored -> newStoreInstance()).toList(); + assertThat(replacementInstances.getFirst().worldsSnapshot(caller, Instant.now())) + .hasValueSatisfying( + snapshot -> { + assertThat(snapshot.catalogFingerprint()).isEqualTo("catalog-fingerprint-v13"); + assertThat(snapshot.ordinalTargets()).containsExactly(target); + }); + + ExecutorService workers = Executors.newFixedThreadPool(replacementInstances.size()); + CountDownLatch ready = new CountDownLatch(replacementInstances.size()); + CountDownLatch start = new CountDownLatch(1); + try { + List> attempts = new ArrayList<>(); + for (DirectTextConnectScopeSessionStore replacement : replacementInstances) { + attempts.add( + workers.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent JOIN test did not start"); + } + return replacement + .publicProductionScopeForJoin(caller, "1", Instant.now()) + .orElseThrow() + .requestId(); + })); + } + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + List requestIds = new ArrayList<>(); + for (Future attempt : attempts) { + requestIds.add(attempt.get(10, TimeUnit.SECONDS)); + } + assertThat(requestIds).doesNotContainNull(); + assertThat(requestIds).containsOnly(requestIds.getFirst()); + + DirectTextConnectScopeSessionStore replacement = replacementInstances.getLast(); + replacement.clearWorldScopes(caller, "1"); + assertThat(firstInstance.publicProductionScopeForJoin(caller, "1", Instant.now())).isEmpty(); + + replacement.replaceWorldScopes( + caller, + "1", + "demo-world", + List.of( + new DirectTextConnectScopeSessionStore.ScopedRealm( + "production", + true, + "account-connect-scope-18", + Instant.now().plusSeconds(600), + playerContext(caller)))); + String freshRequestId = + firstInstance + .publicProductionScopeForJoin(caller, "1", Instant.now()) + .orElseThrow() + .requestId(); + assertThat(freshRequestId).isNotEqualTo(requestIds.getFirst()); + + replacement.clearSession(SESSION_ID); + assertThat(firstInstance.worldsSnapshot(caller, Instant.now())).isEmpty(); + assertThat(firstInstance.publicProductionScopeForJoin(caller, "1", Instant.now())).isEmpty(); + } finally { + workers.shutdownNow(); + } + } + + private DirectTextConnectScopeSessionStore newStoreInstance() { + return new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); + } + + private static SessionContext session() { + return new SessionContext(SESSION_ID, 22L, ACCOUNT_ID, 7001L, 9L, "R-1", "unused-test-jwt"); + } + + private static PlayerExecutionContext playerContext(SessionContext caller) { + return PlayerExecutionContext.newBuilder() + .setAccountId(Long.toString(caller.accountId())) + .setSessionId(Long.toString(caller.sessionId())) + .setTenantId("22") + .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") + .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") + .setPlayableStateScope("SHARED") + .setGameInstanceId("9") + .build(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 5bbeaaba34..7cfdc5909e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -36,7 +36,8 @@ void visibleWorldsDropsWorldSlugSharedAcrossTenants() { pointer("other", "Other World", "production", "Other Live", 2L, 22L, 9L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); - assertThat(catalog.visibleWorlds()).extracting(GameplayWorldCatalog.WorldView::slug) + assertThat(catalog.visibleWorlds()) + .extracting(GameplayWorldCatalog.WorldView::slug) .containsExactly("other"); assertThat(catalog.resolveWorld("demo")).isEmpty(); } @@ -51,7 +52,8 @@ void visibleWorldsGroupsMultipleRealmsForTheSameTenantWorldSlug() { GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); GameplayWorldCatalog.WorldView world = catalog.resolveWorld("demo").orElseThrow(); - assertThat(world.realms()).extracting(GameplayWorldCatalog.RealmView::slug) + assertThat(world.realms()) + .extracting(GameplayWorldCatalog.RealmView::slug) .containsExactly("production", "event"); } @@ -206,8 +208,7 @@ void publicProductionCardinalityCountsExactlyOneAcrossTheTenantCatalogue() { assertThat(catalog.publicProductionRealmCardinality(7L)) .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); - assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())) - .isPresent(); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())).isPresent(); } @Test @@ -232,8 +233,7 @@ void publicProductionCardinalityCountsSameTenantCandidatesAcrossWorlds() { assertThat(catalog.publicProductionRealmCardinality(7L)) .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); - assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())) - .isEmpty(); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())).isEmpty(); } @Test @@ -259,8 +259,7 @@ void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { assertThat(catalog.publicProductionRealmCardinality(7L)) .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); - assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())) - .isPresent(); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())).isPresent(); } @Test @@ -281,8 +280,7 @@ void numericWorldSelectionUsesTheSameFilteredSetAsWorldBrowsePresentation() { @Test void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { - java.util.UUID realmId = - java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); + java.util.UUID realmId = java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); java.util.UUID playableStateNamespaceId = java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412"); when(authorityService.listPointers()) @@ -307,7 +305,9 @@ void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); GameplayWorldCatalog.RealmView realm = - catalog.resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production").orElseThrow(); + catalog + .resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production") + .orElseThrow(); assertThat(realm.catalogRevision()).isEqualTo(29L); assertThat(realm.realmId()).isEqualTo(realmId); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java index a2175fe179..12a473f5d8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java @@ -8,6 +8,7 @@ import java.util.Optional; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -43,7 +44,8 @@ class LogoutCommandHandlerTest { gameplayAdmissionPointerAuthorityService, gameplayPresenceLifecycleService, firstPartyConnectContextRegistry, - scriptEventPublisher); + scriptEventPublisher, + DirectTextConnectScopeSessionStore.inMemoryForTest()); @Test void logoutPreservesDurableReplayContextWithoutStoppingSharedRuntime() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index d6ea6b84cd..ee89c1e494 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -294,7 +294,7 @@ void setUp() { worldCatalog, entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()); + DirectTextConnectScopeSessionStore.inMemoryForTest()); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); interpreter = @@ -309,7 +309,8 @@ void setUp() { pointerAuthorityService, gameplayPresenceLifecycleService, firstPartyConnectContextRegistry, - scriptEventPublisher), + scriptEventPublisher, + DirectTextConnectScopeSessionStore.inMemoryForTest()), playHandler, moveHandler, afkHandler, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 277d2773c5..7c7abb15ed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -12,8 +12,8 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.time.Instant; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -365,7 +365,8 @@ void setUp() { gameplayPresenceLifecycleService); GameplayWorldCatalog worldCatalog = GameplayWorldCatalog.forWorldViews( - List.of(worldView("demo", "Demo World", 22L, 1L, false), + List.of( + worldView("demo", "Demo World", 22L, 1L, false), worldView("sandbox", "Builder Sandbox", 23L, 2L, true))); LoginCommandHandler loginHandler = new LoginCommandHandler( @@ -432,7 +433,7 @@ void setUp() { worldCatalog, entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()); + DirectTextConnectScopeSessionStore.inMemoryForTest()); LookResult lookResult = LookResult.newBuilder() @@ -490,7 +491,8 @@ void setUp() { pointerAuthorityService, gameplayPresenceLifecycleService, firstPartyConnectContextRegistry, - scriptEventPublisher), + scriptEventPublisher, + DirectTextConnectScopeSessionStore.inMemoryForTest()), playHandler, moveHandler, afkHandler, @@ -1072,8 +1074,7 @@ private static GameplayWorldCatalog.WorldView worldView( "ALLOW_NEW", 1L, UUID.nameUUIDFromBytes((slug + ":realm").getBytes(StandardCharsets.UTF_8)), - UUID.nameUUIDFromBytes( - (slug + ":namespace").getBytes(StandardCharsets.UTF_8))))); + UUID.nameUUIDFromBytes((slug + ":namespace").getBytes(StandardCharsets.UTF_8))))); } private static GameplayAdmissionPointerSnapshot pointer( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 6dfc238152..0a7b59b5ea 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -5,6 +5,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -64,6 +65,127 @@ void browseRealmsReturnsStructuredRealmList() { assertThat(response.realms().get(0).characterCreationPolicy()).isEqualTo("ALLOW_NEW"); } + @Test + void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { + GameplayWorldCatalog.RealmView realmA = + new GameplayWorldCatalog.RealmView( + "production", + "A", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + GameplayWorldCatalog.RealmView realmB = + new GameplayWorldCatalog.RealmView( + "production", + "B", + 23L, + 2L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + GameplayWorldCatalog.WorldView worldA = + new GameplayWorldCatalog.WorldView("a", "A", List.of(realmA)); + GameplayWorldCatalog.WorldView worldB = + new GameplayWorldCatalog.WorldView("b", "B", List.of(realmB)); + AtomicReference> worlds = + new AtomicReference<>(List.of(worldA, worldB)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldSupplier(worlds::get), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + localHandler.browseView("7", Optional.of(authenticatedSession())); + worlds.set(List.of(worldB, worldA)); + + assertThat(localHandler.browseRealms("7", authenticatedSession(), "1")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + + @Test + void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { + GameplayWorldCatalog.RealmView realmA = + new GameplayWorldCatalog.RealmView( + "production", + "A", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + GameplayWorldCatalog.RealmView realmB = + new GameplayWorldCatalog.RealmView( + "production", + "B", + 23L, + 2L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + GameplayWorldCatalog.WorldView worldA = + new GameplayWorldCatalog.WorldView("a", "A", List.of(realmA)); + GameplayWorldCatalog.WorldView worldB = + new GameplayWorldCatalog.WorldView("b", "B", List.of(realmB)); + AtomicReference> worlds = + new AtomicReference<>(List.of(worldA, worldB)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-a") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldSupplier(worlds::get), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + localHandler.browseView("7", Optional.of(authenticatedSession())); + worlds.set(List.of(worldB, worldA)); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms("7", authenticatedSession(), "a"); + + assertThat(result) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().worldSlug()).isEqualTo("a")); + Mockito.verify(accountClient) + .issueDirectTextConnectScope( + Mockito.argThat(context -> context.getTenantId().equals("22")), Mockito.any()); + } + @Test void browseRealmsToleratesNullRealmEnums() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); @@ -113,7 +235,8 @@ void browseCharactersReturnsStructuredCharacterList() { .setLevel(12) .build()) .build()); - WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); + WorldsCommandHandler localHandler = + authenticatedHandler(gameplayCatalogProperties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( @@ -166,7 +289,8 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .setLevel(5) .build()) .build()); - WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); + WorldsCommandHandler localHandler = + authenticatedHandler(gameplayCatalogProperties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( @@ -187,11 +311,15 @@ void browseCharactersUsesIsolatedStateRealmRoster() { @Test void browseCharactersRejectsMismatchedOrDuplicateEntityRows() { AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when(accountClient.getTenantMembershipForRuntime(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(activeMembership()); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(publicProductionProperties(), accountClient); + WorldsCommandHandler localHandler = + authenticatedHandler(publicProductionProperties(), accountClient); net.firedevops.firemud.entitymanagement.v1.Character valid = net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") @@ -204,20 +332,27 @@ void browseCharactersRejectsMismatchedOrDuplicateEntityRows() { List.of( valid.toBuilder().setTenantId("23").build(), valid.toBuilder().setAccountId("456").build(), - valid.toBuilder().setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED).build(), + valid.toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .build(), valid.toBuilder().clearId().build(), valid.toBuilder().clearName().build())) { - Mockito.when(entityManagementClient.listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(ListCharactersByAccountResponse.newBuilder().addCharacters(invalid).build()); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); } - Mockito.when(entityManagementClient.listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder() - .addCharacters(valid) - .addCharacters(valid) - .build()); + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + ListCharactersByAccountResponse.newBuilder() + .addCharacters(valid) + .addCharacters(valid) + .build()); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); } @@ -237,8 +372,9 @@ void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { "demo", null); - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure( - "ADMISSION_POINTER_UNAVAILABLE")); + assertThat(result) + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @@ -249,9 +385,9 @@ void browseCharactersReturnsJoinRequiredForPublicNonMemberWithoutReadingEntityRo Mockito.when( accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - publicMembership(false, false, 0L, 0L, "MISSING")); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING")); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); @@ -270,9 +406,9 @@ void browseCharactersReturnsJoinRequiredForPublicInactiveMemberWithoutReadingEnt Mockito.when( accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - publicMembership(true, false, 3L, 4L, "INACTIVE")); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicMembership(true, false, 3L, 4L, "INACTIVE")); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); @@ -290,17 +426,20 @@ void browseCharactersFailsClosedForUnknownPublicMembershipLifecycleWithoutReadin } @Test - void browseCharactersFailsClosedForActivePublicMembershipWithoutAdmissionWithoutReadingEntityRoster() { + void + browseCharactersFailsClosedForActivePublicMembershipWithoutAdmissionWithoutReadingEntityRoster() { assertPublicMembershipFailsClosed(publicMembership(true, false, 1L, 1L, "ACTIVE")); } @Test - void browseCharactersFailsClosedForAbsentPublicMembershipWithActiveLifecycleWithoutReadingEntityRoster() { + void + browseCharactersFailsClosedForAbsentPublicMembershipWithActiveLifecycleWithoutReadingEntityRoster() { assertPublicMembershipFailsClosed(publicMembership(false, false, 0L, 0L, "ACTIVE")); } @Test - void browseCharactersFailsClosedForInactivePublicMembershipWithAdmissionWithoutReadingEntityRoster() { + void + browseCharactersFailsClosedForInactivePublicMembershipWithAdmissionWithoutReadingEntityRoster() { assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "INACTIVE")); } @@ -324,7 +463,8 @@ void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEnt .setMembershipLifecycleState("MISSING") .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(false)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); @@ -358,7 +498,8 @@ void browseCharactersReturnsUnavailableEntitlementBeforeReadingPublicEntityRoste .setMembershipLifecycleState("MISSING") .setEvaluatedAt("2026-03-30T00:00:00Z") .build()); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( @@ -374,8 +515,7 @@ void browseCharactersReturnsUnavailableEntitlementBeforeReadingPublicEntityRoste assertThat(result) .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "ENTITLEMENT_UNAVAILABLE")); + new WorldsCommandHandler.CharacterBrowseResult.Failure("ENTITLEMENT_UNAVAILABLE")); Mockito.verifyNoInteractions(entityManagementClient); } @@ -483,34 +623,75 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() UUID namespaceId = UUID.randomUUID(); GameplayWorldCatalog.RealmView complete = new GameplayWorldCatalog.RealmView( - "production", "Live Realm", 22L, 1L, 1L, true, true, false, "SHARED", - "ALLOW_NEW", 1L, realmId, namespaceId); + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + realmId, + namespaceId); AccountClient accountClient = Mockito.mock(AccountClient.class); - for (GameplayWorldCatalog.RealmView incomplete : List.of( - new GameplayWorldCatalog.RealmView( - complete.slug(), complete.displayName(), complete.tenantId(), - complete.gameInstanceId(), complete.pointerVersion(), complete.visible(), - complete.publicProductionRealm(), complete.requiresCharacterSelection(), - complete.stateScope(), complete.characterCreationPolicy(), 0L, realmId, namespaceId), - new GameplayWorldCatalog.RealmView( - complete.slug(), complete.displayName(), complete.tenantId(), - complete.gameInstanceId(), complete.pointerVersion(), complete.visible(), - complete.publicProductionRealm(), complete.requiresCharacterSelection(), - complete.stateScope(), complete.characterCreationPolicy(), 1L, null, namespaceId), - new GameplayWorldCatalog.RealmView( - complete.slug(), complete.displayName(), complete.tenantId(), - complete.gameInstanceId(), complete.pointerVersion(), complete.visible(), - complete.publicProductionRealm(), complete.requiresCharacterSelection(), - complete.stateScope(), complete.characterCreationPolicy(), 1L, realmId, null))) { + for (GameplayWorldCatalog.RealmView incomplete : + List.of( + new GameplayWorldCatalog.RealmView( + complete.slug(), + complete.displayName(), + complete.tenantId(), + complete.gameInstanceId(), + complete.pointerVersion(), + complete.visible(), + complete.publicProductionRealm(), + complete.requiresCharacterSelection(), + complete.stateScope(), + complete.characterCreationPolicy(), + 0L, + realmId, + namespaceId), + new GameplayWorldCatalog.RealmView( + complete.slug(), + complete.displayName(), + complete.tenantId(), + complete.gameInstanceId(), + complete.pointerVersion(), + complete.visible(), + complete.publicProductionRealm(), + complete.requiresCharacterSelection(), + complete.stateScope(), + complete.characterCreationPolicy(), + 1L, + null, + namespaceId), + new GameplayWorldCatalog.RealmView( + complete.slug(), + complete.displayName(), + complete.tenantId(), + complete.gameInstanceId(), + complete.pointerVersion(), + complete.visible(), + complete.publicProductionRealm(), + complete.requiresCharacterSelection(), + complete.stateScope(), + complete.characterCreationPolicy(), + 1L, + realmId, + null))) { WorldsCommandHandler localHandler = new WorldsCommandHandler( - GameplayWorldCatalog.forWorldViews(List.of( - new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(incomplete)))), - entityManagementClient, accountClient, new DirectTextConnectScopeSessionStore()); + GameplayWorldCatalog.forWorldViews( + List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(incomplete)))), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure( - "ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); } Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @@ -518,24 +699,26 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() @Test void browseCharactersRejectsIncompleteOrStaleEntitlementBeforeReadingRoster() { AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(activeMembership()); WorldsCommandHandler localHandler = authenticatedHandler(publicProductionProperties(), accountClient); GetTenantEntitlementsForRuntimeResponse valid = publicEntitlement(true); - for (GetTenantEntitlementsForRuntimeResponse invalid : List.of( - valid.toBuilder().setEntitlementVersion(0L).build(), - valid.toBuilder().setTenantBillingSequence(0L).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().minusSeconds(16).toString()).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().plusSeconds(30).toString()).build())) { - Mockito.when(accountClient.getTenantEntitlementsForRuntime( - Mockito.anyString(), Mockito.anyString())) + for (GetTenantEntitlementsForRuntimeResponse invalid : + List.of( + valid.toBuilder().setEntitlementVersion(0L).build(), + valid.toBuilder().setTenantBillingSequence(0L).build(), + valid.toBuilder().setEvaluatedAt(Instant.now().minusSeconds(16).toString()).build(), + valid.toBuilder().setEvaluatedAt(Instant.now().plusSeconds(30).toString()).build())) { + Mockito.when( + accountClient.getTenantEntitlementsForRuntime( + Mockito.anyString(), Mockito.anyString())) .thenReturn(invalid); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure( - "ENTITLEMENT_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); } Mockito.verifyNoInteractions(entityManagementClient); } @@ -550,7 +733,8 @@ void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRo accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(activeMembership()); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") @@ -571,8 +755,7 @@ void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRo assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); Mockito.verify(entityManagementClient) - .listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -678,7 +861,8 @@ void authenticatedBrowseIncludesPrivateRealmForActiveMemberWithExactGrant() { Mockito.anyString(), Mockito.anyString())) .thenReturn(grant(true)); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") @@ -717,7 +901,8 @@ void authenticatedBrowseRejectsPrivateRealmWhenEntitlementTenantDoesNotMatch() { Mockito.anyString(), Mockito.anyString())) .thenReturn(grant(true)); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("23") @@ -731,7 +916,8 @@ void authenticatedBrowseRejectsPrivateRealmWhenEntitlementTenantDoesNotMatch() { WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "preview"); - assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); + assertThat(result) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); } @Test @@ -753,7 +939,8 @@ void authenticatedBrowseOmitsPrivateRealmWhenGameplayEntitlementIsUnavailable() Mockito.anyString(), Mockito.anyString())) .thenReturn(grant(true)); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") @@ -793,7 +980,8 @@ void authenticatedBrowseFailsClosedWhenGameplayEntitlementIsUnavailable() { Mockito.anyString(), Mockito.anyString())) .thenReturn(grant(true)); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( @@ -845,7 +1033,7 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()); + DirectTextConnectScopeSessionStore.inMemoryForTest()); WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "demo"); @@ -864,20 +1052,32 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySuccess() { GameplayWorldCatalog.RealmView realm = new GameplayWorldCatalog.RealmView( - "production", "Live Realm", 22L, 1L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, - UUID.randomUUID(), UUID.randomUUID()); + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) - .thenReturn(IssueDirectTextConnectScopeResponse.newBuilder() - .setError(ErrorDetail.newBuilder().setCode("REALM_UNAVAILABLE")) - .build()); + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("REALM_UNAVAILABLE")) + .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()); + DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("REALM_UNAVAILABLE")); @@ -887,12 +1087,34 @@ void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySucces void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { GameplayWorldCatalog.RealmView realmA = new GameplayWorldCatalog.RealmView( - "production", "A", 22L, 1L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, - UUID.randomUUID(), UUID.randomUUID()); + "production", + "A", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); GameplayWorldCatalog.RealmView realmB = new GameplayWorldCatalog.RealmView( - "production", "B", 23L, 2L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, - UUID.randomUUID(), UUID.randomUUID()); + "production", + "B", + 23L, + 2L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); GameplayWorldCatalog.WorldView worldA = new GameplayWorldCatalog.WorldView("a", "A", List.of(realmA)); GameplayWorldCatalog.WorldView worldB = @@ -902,17 +1124,27 @@ void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(worlds::get); AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) - .thenReturn(IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId("scope-a") - .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) - .build()); - Mockito.when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(JoinPublicProductionMembershipResponse.newBuilder() - .setSuccess(false).setOutcomeCode("CONNECT_SCOPE_MISMATCH").build()); + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-a") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + Mockito.when( + accountClient.joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("CONNECT_SCOPE_MISMATCH") + .build()); WorldsCommandHandler localHandler = - new WorldsCommandHandler(catalog, entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()); + new WorldsCommandHandler( + catalog, + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + localHandler.browseView("7", Optional.of(authenticatedSession())); assertThat(localHandler.browseRealms(authenticatedSession(), "1")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); worlds.set(List.of(worldB, worldA)); @@ -921,12 +1153,17 @@ void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { localHandler.joinPublicProductionMembership(authenticatedSession(), "1"); assertThat(join).isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); - assertThat(((WorldsCommandHandler.JoinMembershipResult.Response) join).response().getOutcomeCode()) + assertThat( + ((WorldsCommandHandler.JoinMembershipResult.Response) join).response().getOutcomeCode()) .isEqualTo("CONNECT_SCOPE_MISMATCH"); - Mockito.verify(accountClient).joinPublicProductionMembership( - Mockito.argThat(context -> context.getTenantId().equals("22") - && context.getRealmId().equals(realmA.realmId().toString())), - Mockito.eq("scope-a"), Mockito.anyString()); + Mockito.verify(accountClient) + .joinPublicProductionMembership( + Mockito.argThat( + context -> + context.getTenantId().equals("22") + && context.getRealmId().equals(realmA.realmId().toString())), + Mockito.eq("scope-a"), + Mockito.anyString()); Mockito.verifyNoInteractions(entityManagementClient); } @@ -934,34 +1171,62 @@ void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { void joinRejectsRetainedScopeWhenTenantPublicRealmBecomesAmbiguous() { GameplayWorldCatalog.RealmView originalRealm = new GameplayWorldCatalog.RealmView( - "production", "A", 22L, 1L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, - UUID.randomUUID(), UUID.randomUUID()); + "production", + "A", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); GameplayWorldCatalog.RealmView conflictingRealm = new GameplayWorldCatalog.RealmView( - "production", "B", 22L, 2L, 1L, true, true, false, "SHARED", "ALLOW_NEW", 1L, - UUID.randomUUID(), UUID.randomUUID()); + "production", + "B", + 22L, + 2L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); GameplayWorldCatalog.WorldView originalWorld = new GameplayWorldCatalog.WorldView("a", "A", List.of(originalRealm)); AtomicReference> worlds = new AtomicReference<>(List.of(originalWorld)); AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) - .thenReturn(IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId("scope-a") - .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) - .build()); + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-a") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( - GameplayWorldCatalog.forWorldSupplier(worlds::get), entityManagementClient, - accountClient, new DirectTextConnectScopeSessionStore()); + GameplayWorldCatalog.forWorldSupplier(worlds::get), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseRealms(authenticatedSession(), "a")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - worlds.set(List.of(originalWorld, - new GameplayWorldCatalog.WorldView("b", "B", List.of(conflictingRealm)))); + worlds.set( + List.of( + originalWorld, + new GameplayWorldCatalog.WorldView("b", "B", List.of(conflictingRealm)))); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "a")) - .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo( + WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verify(accountClient, Mockito.never()) .joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString()); } @@ -978,8 +1243,7 @@ void authenticatedBrowseFailsClosedWhenTenantHasNoPublicProductionRealm() { localHandler.browseRealms(authenticatedSession(), "preview"); assertThat(result) - .isEqualTo( - WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient); } @@ -995,8 +1259,7 @@ void authenticatedBrowseFailsClosedWhenPublicProductionRealmIsDuplicatedAcrossWo localHandler.browseRealms(authenticatedSession(), "demo"); assertThat(result) - .isEqualTo( - WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient); } @@ -1006,7 +1269,7 @@ private WorldsCommandHandler authenticatedHandler( TestGameplayWorldCatalogs.fromProperties(properties), entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()); + DirectTextConnectScopeSessionStore.inMemoryForTest()); } private GameplayCatalogProperties publicProductionProperties() { @@ -1016,8 +1279,7 @@ private GameplayCatalogProperties publicProductionProperties() { return properties; } - private void assertPublicMembershipFailsClosed( - GetTenantMembershipForRuntimeResponse membership) { + private void assertPublicMembershipFailsClosed(GetTenantMembershipForRuntimeResponse membership) { AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( accountClient.getTenantMembershipForRuntime( @@ -1083,8 +1345,7 @@ private GetRealmAccessGrantForRuntimeResponse grant(boolean granted) { return grant("preview", granted); } - private GetRealmAccessGrantForRuntimeResponse grant( - String worldSlug, boolean granted) { + private GetRealmAccessGrantForRuntimeResponse grant(String worldSlug, boolean granted) { return GetRealmAccessGrantForRuntimeResponse.newBuilder() .setAccountId("123") .setTenantId("22") @@ -1109,7 +1370,8 @@ private void stubActivePrivateAuthorization(AccountClient accountClient, String Mockito.anyString(), Mockito.anyString())) .thenReturn(grant(worldSlug, true)); - Mockito.when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 6737652e77..7e80a90e65 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -39,7 +39,9 @@ class WorldsTextCommandDispatchHandlerTest { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient), + entityManagementClient, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @Test @@ -51,7 +53,7 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { TextCommandInterpretationResult result = handler.handle( new TextCommandDispatchRequest( - "session-1", + "7", new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), false, Optional.of(context))); @@ -127,7 +129,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()), + DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -136,7 +138,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { TextCommandInterpretationResult result = scopedHandler.handle( new TextCommandDispatchRequest( - "session-1", + "7", new TextCommand(TextCommandType.REALMS, List.of("sandbox"), "REALMS sandbox"), false, Optional.of(context))); @@ -211,12 +213,12 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()), + DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); TextCommandInterpretationResult result = scopedHandler.handle( new TextCommandDispatchRequest( - "session-1", + "7", new TextCommand(TextCommandType.CHARS, List.of("demo"), "CHARS demo"), false, Optional.of(context))); @@ -274,7 +276,7 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), entityManagementClient, accountClient, - new DirectTextConnectScopeSessionStore()), + DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -283,8 +285,9 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( TextCommandInterpretationResult result = scopedHandler.handle( new TextCommandDispatchRequest( - "session-1", - new TextCommand(TextCommandType.CHARS, List.of("demo", "production"), "CHARS demo production"), + "7", + new TextCommand( + TextCommandType.CHARS, List.of("demo", "production"), "CHARS demo production"), false, Optional.of(context))); @@ -299,7 +302,7 @@ void skipsCommandEventWithoutGameplayContext() { TextCommandInterpretationResult result = handler.handle( new TextCommandDispatchRequest( - "session-1", + "71", new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), false, Optional.empty())); @@ -311,7 +314,8 @@ void skipsCommandEventWithoutGameplayContext() { @Test void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { AccountClient accountClient = Mockito.mock(AccountClient.class); - DirectTextConnectScopeSessionStore scopeStore = new DirectTextConnectScopeSessionStore(); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); UUID realmId = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); UUID namespaceId = UUID.fromString("42d234a2-7487-4dda-a7e5-a3831214328e"); GameplayWorldCatalog catalog = @@ -460,7 +464,10 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, entityManagementClient, accountClient, new DirectTextConnectScopeSessionStore()), + catalog, + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 1faab651a6..503fe866ee 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Instant; import java.util.List; @@ -8,81 +9,69 @@ import org.junit.jupiter.api.Test; class DirectTextConnectScopeSessionStoreTest { - private final DirectTextConnectScopeSessionStore store = new DirectTextConnectScopeSessionStore(); + private final DirectTextConnectScopeSessionStore store = + DirectTextConnectScopeSessionStore.inMemoryForTest(); @Test void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { SessionContext caller = session(7L, 41L); - Instant expiry = Instant.parse("2030-01-01T00:00:00Z"); + Instant now = Instant.now(); + Instant expiry = now.plusSeconds(3600); store.replaceWorldScopes( caller, "1", "demo-world", List.of(scopedRealm(caller, "demo-world", "scope-secret", expiry))); - assertThat(store.publicProductionScope(caller, "1", Instant.parse("2029-01-01T00:00:00Z"))) + assertThat(store.publicProductionScope(caller, "1", now)) .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("scope-secret")); - assertThat( - store.publicProductionScope( - session(8L, 41L), "1", Instant.parse("2029-01-01T00:00:00Z"))) - .isEmpty(); - assertThat( - store.publicProductionScope( - session(7L, 42L), "1", Instant.parse("2029-01-01T00:00:00Z"))) - .isEmpty(); + assertThat(store.publicProductionScope(session(8L, 41L), "1", now)).isEmpty(); + assertThat(store.publicProductionScope(session(7L, 42L), "1", now)).isEmpty(); } @Test void refusesExpiredAndAmbiguousPublicScopes() { SessionContext caller = session(7L, 41L); + Instant now = Instant.now(); store.replaceWorldScopes( caller, "demo-world", "demo-world", - List.of( - scopedRealm( - caller, "production", "expired-scope", Instant.parse("2029-01-01T00:00:00Z")))); + List.of(scopedRealm(caller, "production", "expired-scope", now.minusSeconds(1)))); - assertThat( - store.publicProductionScope( - caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z"))) - .isEmpty(); + assertThat(store.publicProductionScope(caller, "demo-world", now)).isEmpty(); store.replaceWorldScopes( caller, "demo-world", "demo-world", List.of( - scopedRealm(caller, "production-a", "scope-a", Instant.parse("2031-01-01T00:00:00Z")), - scopedRealm(caller, "production-b", "scope-b", Instant.parse("2031-01-01T00:00:00Z")))); + scopedRealm(caller, "production-a", "scope-a", now.plusSeconds(3600)), + scopedRealm(caller, "production-b", "scope-b", now.plusSeconds(3600)))); - assertThat( - store.publicProductionScope( - caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z"))) - .isEmpty(); + assertThat(store.publicProductionScope(caller, "demo-world", now)).isEmpty(); } @Test void clearsPriorScopeBeforeReplacingTheWorldBinding() { SessionContext caller = session(7L, 41L); + Instant now = Instant.now(); store.replaceWorldScopes( caller, "1", "demo-world", - List.of( - scopedRealm( - caller, "production", "scope-secret", Instant.parse("2031-01-01T00:00:00Z")))); + List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(3600)))); store.clearWorldScopes(caller, "1"); - assertThat(store.publicProductionScope(caller, "1", Instant.parse("2030-01-01T00:00:00Z"))) - .isEmpty(); + assertThat(store.publicProductionScope(caller, "1", now)).isEmpty(); } @Test void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { SessionContext caller = session(7L, 41L); - Instant expiry = Instant.parse("2031-01-01T00:00:00Z"); + Instant now = Instant.now(); + Instant expiry = now.plusSeconds(3600); store.replaceWorldScopes( caller, "demo-world", @@ -90,15 +79,9 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { List.of(scopedRealm(caller, "production", "scope-first", expiry))); DirectTextConnectScopeSessionStore.JoinScope firstAttempt = - store - .publicProductionScopeForJoin( - caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) - .orElseThrow(); + store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); DirectTextConnectScopeSessionStore.JoinScope retryAttempt = - store - .publicProductionScopeForJoin( - caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) - .orElseThrow(); + store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); assertThat(firstAttempt.requestId()).isEqualTo(retryAttempt.requestId()); assertThat(firstAttempt.scope().connectScopeId()) @@ -111,15 +94,54 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { "demo-world", List.of(scopedRealm(caller, "production", "scope-second", expiry))); DirectTextConnectScopeSessionStore.JoinScope newAttempt = - store - .publicProductionScopeForJoin( - caller, "demo-world", Instant.parse("2030-01-01T00:00:00Z")) - .orElseThrow(); + store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); assertThat(newAttempt.scope().connectScopeId()).isEqualTo("scope-second"); assertThat(newAttempt.requestId()).isNotEqualTo(firstAttempt.requestId()); } + @Test + void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { + SessionContext caller = session(41L, 7L); + Instant now = Instant.now(); + DirectTextConnectScopeSessionStore.WorldOrdinalTarget target = + new DirectTextConnectScopeSessionStore.WorldOrdinalTarget( + 1, "demo-world", 22L, 13L, "target-fingerprint"); + store.replaceWorldSnapshot(caller.sessionId(), 0L, "catalog-fingerprint", List.of(target), now); + + assertThat(store.worldsSnapshot(caller, now)) + .hasValueSatisfying( + snapshot -> { + assertThat(snapshot.catalogFingerprint()).isEqualTo("catalog-fingerprint"); + assertThat(snapshot.ordinalTargets()).containsExactly(target); + assertThat(snapshot.expiresAt()).isBeforeOrEqualTo(now.plusSeconds(301)); + }); + + store.replaceWorldScopes( + caller, + "1", + "demo-world", + List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(86_400)))); + DirectTextConnectScopeSessionStore.JoinScope selected = + store.publicProductionScopeForJoin(caller, "1", now).orElseThrow(); + + assertThat(selected.scope().expiresAt()).isBeforeOrEqualTo(now.plusSeconds(901)); + assertThat(selected.scope().playerContext().getAccountId()).isEqualTo("7"); + assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); + } + + @Test + void rejectsInvalidTransportIdsAndScopesBoundToAnotherIdentity() { + assertThatThrownBy(() -> store.clearSession(0L)).isInstanceOf(IllegalArgumentException.class); + + SessionContext caller = session(7L, 41L); + DirectTextConnectScopeSessionStore.ScopedRealm mismatchedScope = + scopedRealm(session(8L, 41L), "production", "scope-secret", Instant.now().plusSeconds(60)); + assertThatThrownBy( + () -> store.replaceWorldScopes(caller, "demo", "demo", List.of(mismatchedScope))) + .isInstanceOf(DirectTextConnectScopeSessionStore.ConflictingIdentityException.class); + } + private static SessionContext session(long sessionId, long accountId) { return new SessionContext(sessionId, 22L, accountId, 7001L, 9L, "jwt"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java index e0f723ec0f..fd99b9cc6a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java @@ -38,10 +38,45 @@ void explicitOpaqueTransportSessionIdIsNormalizedToStableNumericSessionId() { assertThat(secondSessionId).isEqualTo(firstSessionId); } + @Test + void trustedProxyConnectionIdProvidesStableSessionAcrossReplacedGameSessionHops() { + Map first = handshakeAttributes(null, "tcp-connection-481", "game-instance-a"); + Map replacement = + handshakeAttributes(null, "tcp-connection-481", "game-instance-b"); + + String firstSessionId = + (String) first.get(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR); + String replacementSessionId = + (String) replacement.get(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR); + + assertThat(firstSessionId).matches("\\d+"); + assertThat(replacementSessionId).isEqualTo(firstSessionId); + assertThat(first.get(GameSessionWebSocketHandshakeInterceptor.BOOTSTRAP_GAME_INSTANCE_ATTR)) + .isNotEqualTo( + replacement.get(GameSessionWebSocketHandshakeInterceptor.BOOTSTRAP_GAME_INSTANCE_ATTR)); + } + private Map handshakeAttributes(String transportSessionId) { + return handshakeAttributes(transportSessionId, null, null); + } + + private Map handshakeAttributes( + String transportSessionId, String proxyConnectionId, String bootstrapGameInstanceId) { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/ws/game"); - servletRequest.addHeader( - GameSessionWebSocketHandshakeInterceptor.TRANSPORT_SESSION_HEADER, transportSessionId); + if (transportSessionId != null) { + servletRequest.addHeader( + GameSessionWebSocketHandshakeInterceptor.TRANSPORT_SESSION_HEADER, transportSessionId); + } + if (proxyConnectionId != null) { + servletRequest.addHeader( + GameSessionWebSocketHandshakeInterceptor.PROXY_CONNECTION_HEADER, proxyConnectionId); + servletRequest.addHeader( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_HEADER, "trusted_tcp_proxy"); + } + if (bootstrapGameInstanceId != null) { + servletRequest.addHeader( + GameSessionWebSocketHandshakeInterceptor.GAME_INSTANCE_HEADER, bootstrapGameInstanceId); + } ServletServerHttpRequest request = new ServletServerHttpRequest(servletRequest); ServerHttpResponse response = new ServletServerHttpResponse(new MockHttpServletResponse()); Map attributes = new HashMap<>(); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index 4a71ba45b8..c022938d32 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -1,10 +1,10 @@ package net.firedevops.firemud.gamesession.support; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; -import java.nio.charset.StandardCharsets; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 806f70dd32..34a76d945d 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -37,8 +37,10 @@ public class GameplayWebSocketBridgeHandler implements WebSocketHandler, SmartLi private static final CloseStatus PLANNED_DRAIN = new CloseStatus(1000, "logout;subreason=gateway_restart"); private static final String CONNECTION_MODE_HEADER = "X-Firemud-Connection-Mode"; + private static final String TRUSTED_TCP_PROXY_MODE = "trusted_tcp_proxy"; private static final String CONNECT_CONTEXT_HEADER = "X-Firemud-Connect-Context"; private static final String TRANSPORT_SESSION_HEADER = "X-Firemud-Transport-Session-Id"; + private static final String PROXY_CONNECTION_HEADER = "X-Proxy-Connection-Id"; private static final String WORLD_SLUG_HEADER = "X-World-Slug"; private static final String REALM_SLUG_HEADER = "X-Realm-Slug"; private static final String POINTER_VERSION_HEADER = "X-Pointer-Version"; @@ -53,7 +55,7 @@ public class GameplayWebSocketBridgeHandler implements WebSocketHandler, SmartLi REALM_SLUG_HEADER, POINTER_VERSION_HEADER, "X-Requires-Solo-Tick", - "X-Proxy-Connection-Id", + PROXY_CONNECTION_HEADER, CONNECTION_MODE_HEADER, CONNECT_CONTEXT_HEADER, TRANSPORT_SESSION_HEADER); @@ -98,6 +100,14 @@ public Mono handle(WebSocketSession downstream) { .doFinally(signal -> activeBridges.remove(state)); } } + HttpHeaders sourceHeaders = downstream.getHandshakeInfo().getHeaders(); + if (isTrustedTcpProxy(sourceHeaders) + && !StringUtils.hasText(sourceHeaders.getFirst(PROXY_CONNECTION_HEADER))) { + return closeDownstream( + state, + gameplayWebSocketObservability.classify(new CloseStatus(1008, "policy_violation"))) + .doFinally(signal -> activeBridges.remove(state)); + } HttpHeaders upstreamHeaders = buildUpstreamHeaders(downstream); URI upstreamUri = URI.create(properties.upstreamUrl()); @@ -427,6 +437,12 @@ private HttpHeaders buildUpstreamHeaders(WebSocketSession downstream) { headers.set(name, value); } }); + if (isTrustedTcpProxy(source)) { + // The authenticated proxy connection ID is stable across Gateway WebSocket replacements. + // Do not turn a Gateway hop ID or any received transport header into session identity. + headers.remove(TRANSPORT_SESSION_HEADER); + return headers; + } if (!StringUtils.hasText(headers.getFirst(TRANSPORT_SESSION_HEADER))) { headers.set( TRANSPORT_SESSION_HEADER, Long.toUnsignedString(stablePositiveLong(downstream.getId()))); @@ -434,6 +450,10 @@ private HttpHeaders buildUpstreamHeaders(WebSocketSession downstream) { return headers; } + private static boolean isTrustedTcpProxy(HttpHeaders headers) { + return TRUSTED_TCP_PROXY_MODE.equals(headers.getFirst(CONNECTION_MODE_HEADER)); + } + private long stablePositiveLong(String value) { try { byte[] digest = diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java index 694dd1e2a5..12ad5ee2c7 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java @@ -88,9 +88,10 @@ void gatewayRebindsUpstreamAfterAbruptDropWithoutDroppingClientSocket() throws E probe.awaitStartsWith("OK LOOK", Duration.ofSeconds(5)); assertThat(probe.responses()).contains(LookCommandConstants.LOOK_RESPONSE); } - assertThat(UPSTREAM.seenTransportSessionIds()).hasSize(2); - assertThat(UPSTREAM.seenTransportSessionIds().get(0)) - .isEqualTo(UPSTREAM.seenTransportSessionIds().get(1)); + assertThat(UPSTREAM.seenIdentities()) + .containsExactly( + new UpstreamIdentity("trusted_tcp_proxy", "bridge-test-conn", null), + new UpstreamIdentity("trusted_tcp_proxy", "bridge-test-conn", null)); } @Test @@ -120,9 +121,10 @@ void gatewayRebindsAfterRealUpstreamRestartWithoutDroppingClientSocket() throws probe.awaitStartsWith("OK LOOK", Duration.ofSeconds(30)); } - assertThat(UPSTREAM.seenTransportSessionIds()).hasSize(2); - assertThat(UPSTREAM.seenTransportSessionIds().get(0)) - .isEqualTo(UPSTREAM.seenTransportSessionIds().get(1)); + assertThat(UPSTREAM.seenIdentities()) + .containsExactly( + new UpstreamIdentity("trusted_tcp_proxy", "bridge-test-conn", null), + new UpstreamIdentity("trusted_tcp_proxy", "bridge-test-conn", null)); } private static synchronized void ensureStarted() { @@ -202,8 +204,8 @@ String websocketUrl() { return "ws://localhost:" + port + "/ws/game"; } - List seenTransportSessionIds() { - return TEST_UPSTREAM_STATE.get().seenTransportSessionIds(); + List seenIdentities() { + return TEST_UPSTREAM_STATE.get().seenIdentities(); } void restart() { @@ -284,15 +286,16 @@ static final class UpstreamStub implements WebSocketHandler { @Override public Mono handle(org.springframework.web.reactive.socket.WebSocketSession session) { - String transportSessionId = - session.getHandshakeInfo().getHeaders().getFirst("X-Firemud-Transport-Session-Id"); - if (transportSessionId != null) { - state.recordTransportSessionId(transportSessionId); - } + UpstreamIdentity identity = + new UpstreamIdentity( + session.getHandshakeInfo().getHeaders().getFirst("X-Firemud-Connection-Mode"), + session.getHandshakeInfo().getHeaders().getFirst("X-Proxy-Connection-Id"), + session.getHandshakeInfo().getHeaders().getFirst("X-Firemud-Transport-Session-Id")); + state.recordIdentity(identity); state.incrementConnectionCount(); return session - .send(Mono.just(session.textMessage("UPSTREAM_READY " + transportSessionId))) + .send(Mono.just(session.textMessage("UPSTREAM_READY " + identity.proxyConnectionId()))) .then( session .receive() @@ -313,13 +316,16 @@ private Mono handleCommand( } } + private record UpstreamIdentity( + String connectionMode, String proxyConnectionId, String transportSessionId) {} + private static final class UpstreamRuntimeState { - private final List seenTransportSessionIds = new CopyOnWriteArrayList<>(); + private final List seenIdentities = new CopyOnWriteArrayList<>(); private final AtomicBoolean firstConnectionDropped = new AtomicBoolean(false); private final AtomicInteger connectionCount = new AtomicInteger(); - void recordTransportSessionId(String transportSessionId) { - seenTransportSessionIds.add(transportSessionId); + void recordIdentity(UpstreamIdentity identity) { + seenIdentities.add(identity); } void incrementConnectionCount() { @@ -330,8 +336,8 @@ int connectionCount() { return connectionCount.get(); } - List seenTransportSessionIds() { - return seenTransportSessionIds; + List seenIdentities() { + return seenIdentities; } boolean markFirstConnectionDropped() { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index 6017efe5b7..b1ebfa5ff3 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -11,6 +12,8 @@ import java.net.URI; import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -70,25 +73,67 @@ void openLoggingContextPrefersTransportSessionHeader() { } @Test - void bridgeGeneratesTransportSessionIdWhenTrustedAdmissionProvidesNone() { + void trustedProxyBridgeForwardsStableConnectionIdWithoutHopOrTransportSessionId() { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + List upstreamHeaders = new ArrayList<>(); + when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) + .thenAnswer( + invocation -> { + HttpHeaders captured = new HttpHeaders(); + HttpHeaders forwarded = invocation.getArgument(1); + captured.putAll(forwarded); + upstreamHeaders.add(captured); + return Mono.never(); + }); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "ws://game-session-service:8080/ws/game", 0, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null)); + + for (String replaceableHopId : List.of("gateway-hop-a", "gateway-hop-b")) { + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshakeInfo = mock(HandshakeInfo.class); + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); + headers.set("X-Proxy-Connection-Id", "tcp-connection-481"); + // Even a transport header on a trusted-proxy request is not forwarded as session identity. + headers.set("X-Firemud-Transport-Session-Id", "9999"); + + when(downstream.getId()).thenReturn(replaceableHopId); + when(downstream.getHandshakeInfo()).thenReturn(handshakeInfo); + when(handshakeInfo.getHeaders()).thenReturn(headers); + when(downstream.send(any())).thenReturn(Mono.never()); + when(downstream.receive()).thenReturn(Flux.never()); + + StepVerifier.create(handler.handle(downstream)) + .expectSubscription() + .thenAwait(Duration.ofMillis(100)) + .thenCancel() + .verify(); + } + + assertThat(upstreamHeaders).hasSize(2); + for (HttpHeaders forwarded : upstreamHeaders) { + assertThat(forwarded.getFirst("X-Firemud-Connection-Mode")).isEqualTo("trusted_tcp_proxy"); + assertThat(forwarded.getFirst("X-Proxy-Connection-Id")).isEqualTo("tcp-connection-481"); + assertThat(forwarded.getFirst("X-Firemud-Transport-Session-Id")).isNull(); + } + } + + @Test + void trustedProxyBridgeFailsClosedWhenAuthenticatedConnectionIdIsMissing() { ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); WebSocketSession downstream = mock(WebSocketSession.class); HandshakeInfo handshakeInfo = mock(HandshakeInfo.class); HttpHeaders headers = new HttpHeaders(); headers.set("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); - AtomicReference upstreamHeaders = new AtomicReference<>(); - - when(downstream.getId()).thenReturn("downstream"); + headers.set("X-Firemud-Transport-Session-Id", "9001"); when(downstream.getHandshakeInfo()).thenReturn(handshakeInfo); when(handshakeInfo.getHeaders()).thenReturn(headers); - when(downstream.send(any())).thenReturn(Mono.never()); - when(downstream.receive()).thenReturn(Flux.never()); - when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - upstreamHeaders.set(invocation.getArgument(1)); - return Mono.never(); - }); + when(downstream.close(any(CloseStatus.class))).thenReturn(Mono.empty()); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -98,18 +143,14 @@ void bridgeGeneratesTransportSessionIdWhenTrustedAdmissionProvidesNone() { new RuntimeIdentity( "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null)); - StepVerifier.create(handler.handle(downstream)) - .expectSubscription() - .thenAwait(Duration.ofMillis(100)) - .thenCancel() - .verify(); + StepVerifier.create(handler.handle(downstream)).verifyComplete(); - assertThat(upstreamHeaders.get()).isNotNull(); - assertThat(upstreamHeaders.get().getFirst("X-Firemud-Connection-Mode")) - .isEqualTo("trusted_tcp_proxy"); - assertThat(upstreamHeaders.get().getFirst("X-Firemud-Transport-Session-Id")) - .matches("\\d+") - .isNotEqualTo("9001"); + ArgumentCaptor closeStatus = ArgumentCaptor.forClass(CloseStatus.class); + verify(downstream).close(closeStatus.capture()); + assertThat(closeStatus.getValue().getCode()).isEqualTo(1008); + assertThat(closeStatus.getValue().getReason()).isEqualTo("policy_violation"); + verify(client, never()) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); } @Test From 5780865e5ab6948ee6369a4c23a07a3f82706788 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:59:33 +1300 Subject: [PATCH 006/105] Carry generated request identity into public REALMS scope --- .../command/text/WorldsCommandHandler.java | 5 +- .../text/WorldsCommandHandlerTest.java | 47 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 98b697d758..47adc089d3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -163,7 +163,7 @@ public RealmBrowseResult browseRealms( if (target == null) { return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - PlayerExecutionContext playerContext = playerContext(sessionContext, realm); + PlayerExecutionContext playerContext = playerContext(sessionContext, realm, requestId); IssueDirectTextConnectScopeResponse scopeResponse = accountClient.issueDirectTextConnectScope(playerContext, target); if (scopeResponse.hasError()) { @@ -535,7 +535,7 @@ private DirectTextConnectScopeTarget connectScopeTarget( } private PlayerExecutionContext playerContext( - SessionContext caller, GameplayWorldCatalog.RealmView realm) { + SessionContext caller, GameplayWorldCatalog.RealmView realm, String requestId) { return PlayerExecutionContext.newBuilder() .setAccountId(Long.toString(caller.accountId())) .setSessionId(Long.toString(caller.sessionId())) @@ -544,6 +544,7 @@ private PlayerExecutionContext playerContext( .setPlayableStateNamespaceId(realm.playableStateNamespaceId().toString()) .setPlayableStateScope(realm.stateScope()) .setGameInstanceId(Long.toString(realm.gameInstanceId())) + .setRequestId(requestId) .build(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 0a7b59b5ea..88edd4d7b0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -1048,6 +1049,52 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); } + @Test + void authenticatedBrowseCarriesGeneratedRequestIdIntoPublicScopeContext() { + UUID realmId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + GameplayWorldCatalog.RealmView realm = + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + realmId, + namespaceId); + AccountClient accountClient = Mockito.mock(AccountClient.class); + AtomicReference issuedContext = new AtomicReference<>(); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenAnswer( + invocation -> { + issuedContext.set(invocation.getArgument(0)); + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-1") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build(); + }); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews( + List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + WorldsCommandHandler.RealmBrowseResult result = + localHandler.browseRealms(authenticatedSession(), "demo"); + + assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(issuedContext) + .hasValueSatisfying(context -> assertThat(context.getRequestId()).isNotBlank()); + } + @Test void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySuccess() { GameplayWorldCatalog.RealmView realm = From 5a3e7ae8be9a51cfbdc2dfeb8a65dccf053dec33 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:21:41 +1300 Subject: [PATCH 007/105] Bind numeric world and realm selections to exact lobby snapshots --- .../command/text/GameplayWorldCatalog.java | 120 +++++++++ .../command/text/PlayCommandHandler.java | 250 +++++++++++++++++- .../command/text/WorldsCommandHandler.java | 101 ++++++- .../DirectTextConnectScopeSessionStore.java | 180 +++++++++++-- .../text/GameplayWorldCatalogTest.java | 50 ++++ .../command/text/PlayCommandHandlerTest.java | 60 ++++- .../text/SessionResumptionFlowTest.java | 3 +- .../text/TextCommandInterpreterTest.java | 3 +- .../text/WorldsCommandHandlerTest.java | 62 +++++ ...irectTextConnectScopeSessionStoreTest.java | 23 ++ 10 files changed, 816 insertions(+), 36 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 86fdbd6387..c2ed4da430 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -17,6 +17,7 @@ import java.util.function.Supplier; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.RealmOrdinalTarget; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.WorldOrdinalTarget; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -141,6 +142,75 @@ public Optional browseRealms(String worldSelector) { .map(world -> new RealmBrowseViewOutput(world.slug(), realmEntries(world))); } + /** Reads the current realm catalog and records the exact response-local ordinal targets. */ + public RealmDiscoverySnapshot readRealmDiscoverySnapshot(WorldView world) { + Objects.requireNonNull(world, "world must not be null"); + return realmDiscoverySnapshot(world, visibleRealms(world)); + } + + /** Builds a REALMS snapshot whose ordinals match the filtered response entries. */ + public RealmDiscoverySnapshot realmDiscoverySnapshot( + WorldView world, List responseRealms) { + Objects.requireNonNull(world, "world must not be null"); + List visibleCatalogRealms = visibleRealms(world); + List safeResponseRealms = + List.copyOf(Objects.requireNonNull(responseRealms, "responseRealms must not be null")); + if (safeResponseRealms.stream().anyMatch(realm -> !visibleCatalogRealms.contains(realm))) { + throw new IllegalArgumentException("REALMS response contains a non-visible realm"); + } + List targets = new ArrayList<>(safeResponseRealms.size()); + for (int index = 0; index < safeResponseRealms.size(); index++) { + RealmView realm = safeResponseRealms.get(index); + targets.add( + new RealmOrdinalTarget( + index + 1, + realm.slug(), + realm.tenantId(), + realm.catalogRevision(), + realm.pointerVersion(), + realmTargetFingerprint(world, realm))); + } + List catalogTargets = new ArrayList<>(visibleCatalogRealms.size()); + for (int index = 0; index < visibleCatalogRealms.size(); index++) { + RealmView realm = visibleCatalogRealms.get(index); + catalogTargets.add( + new RealmOrdinalTarget( + index + 1, + realm.slug(), + realm.tenantId(), + realm.catalogRevision(), + realm.pointerVersion(), + realmTargetFingerprint(world, realm))); + } + return new RealmDiscoverySnapshot( + world.slug(), + fingerprint( + catalogTargets.stream() + .map(GameplayWorldCatalog::realmTargetFingerprintInput) + .toList()), + List.copyOf(targets)); + } + + /** Resolves a numeric REALMS target by identity, never by its current ordinal. */ + public Optional resolveRealmSnapshotOrdinal( + WorldView world, RealmDiscoverySnapshot current, RealmOrdinalTarget originatingTarget) { + Objects.requireNonNull(world, "world must not be null"); + Objects.requireNonNull(current, "current must not be null"); + Objects.requireNonNull(originatingTarget, "originatingTarget must not be null"); + if (!world.slug().equalsIgnoreCase(current.worldSlug())) { + return Optional.empty(); + } + return visibleRealms(world).stream() + .filter(realm -> realm.slug().equalsIgnoreCase(originatingTarget.realmSlug())) + .filter(realm -> realm.tenantId() == originatingTarget.tenantId()) + .filter(realm -> realm.catalogRevision() == originatingTarget.catalogRevision()) + .filter(realm -> realm.pointerVersion() == originatingTarget.pointerVersion()) + .filter( + realm -> + realmTargetFingerprint(world, realm).equals(originatingTarget.targetFingerprint())) + .findFirst(); + } + public Optional resolveWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); @@ -256,6 +326,42 @@ private static String worldTargetFingerprint(WorldView world, RealmView defaultR : defaultRealm.characterCreationPolicy())); } + private static String realmTargetFingerprint(WorldView world, RealmView realm) { + return fingerprint( + List.of( + world.slug(), + world.displayName(), + realm.slug(), + realm.displayName(), + Long.toString(realm.tenantId()), + Long.toString(realm.gameInstanceId()), + Long.toString(realm.pointerVersion()), + Long.toString(realm.catalogRevision()), + realm.realmId() == null ? "" : realm.realmId().toString(), + realm.playableStateNamespaceId() == null + ? "" + : realm.playableStateNamespaceId().toString(), + Boolean.toString(realm.visible()), + Boolean.toString(realm.publicProductionRealm()), + Boolean.toString(realm.requiresCharacterSelection()), + realm.stateScope() == null ? "" : realm.stateScope(), + realm.characterCreationPolicy() == null ? "" : realm.characterCreationPolicy())); + } + + private static String realmTargetFingerprintInput(RealmOrdinalTarget target) { + return target.ordinal() + + "|" + + target.realmSlug() + + "|" + + target.tenantId() + + "|" + + target.catalogRevision() + + "|" + + target.pointerVersion() + + "|" + + target.targetFingerprint(); + } + private static String targetFingerprintInput(WorldOrdinalTarget target) { return target.ordinal() + "|" @@ -299,6 +405,20 @@ public record DiscoverySnapshot( } } + public record RealmDiscoverySnapshot( + String worldSlug, String catalogFingerprint, List ordinalTargets) { + public RealmDiscoverySnapshot { + if (worldSlug == null || worldSlug.isBlank()) { + throw new IllegalArgumentException("worldSlug must not be blank"); + } + if (catalogFingerprint == null || catalogFingerprint.isBlank()) { + throw new IllegalArgumentException("catalogFingerprint must not be blank"); + } + ordinalTargets = + List.copyOf(Objects.requireNonNull(ordinalTargets, "ordinalTargets must not be null")); + } + } + /** * Returns the tenant-wide cardinality of visible, player-addressable public-production realms. * The scan intentionally spans every authored world because a tenant may have candidates in more diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 42bad054e1..cd9f45bdb5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; @@ -59,6 +60,7 @@ public class PlayCommandHandler { private final SessionContextService sessionContextService; private final SessionRoutingNormalizationService sessionRoutingNormalizationService; private final GameplayWorldCatalog gameplayWorldCatalog; + private final DirectTextConnectScopeSessionStore connectScopeSessionStore; private final GameLogicProperties gameLogicProperties; private final AccountClient accountClient; private final EntityManagementClient entityManagementClient; @@ -70,6 +72,7 @@ public class PlayCommandHandler { private final Counter takeoverCounter; private final Counter resumeCounter; + @org.springframework.beans.factory.annotation.Autowired public PlayCommandHandler( SessionAuthenticationService sessionAuthenticationService, SessionContextService sessionContextService, @@ -82,7 +85,8 @@ public PlayCommandHandler( FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, GameplayPresenceLifecycleService gameplayPresenceLifecycleService, ScriptEventPublisher scriptEventPublisher, - MeterRegistry meterRegistry) { + MeterRegistry meterRegistry, + DirectTextConnectScopeSessionStore connectScopeSessionStore) { this.sessionAuthenticationService = Objects.requireNonNull( sessionAuthenticationService, "sessionAuthenticationService must not be null"); @@ -94,6 +98,9 @@ public PlayCommandHandler( "sessionRoutingNormalizationService must not be null"); this.gameplayWorldCatalog = Objects.requireNonNull(gameplayWorldCatalog, "gameplayWorldCatalog must not be null"); + this.connectScopeSessionStore = + Objects.requireNonNull( + connectScopeSessionStore, "connectScopeSessionStore must not be null"); this.gameLogicProperties = Objects.requireNonNull(gameLogicProperties, "gameLogicProperties must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); @@ -167,9 +174,33 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } ResolvedPlaySelection selection = maybeSelection.orElseThrow(); - Optional maybeWorld = - gameplayWorldCatalog.resolveWorld(selection.worldSelector()); - if (maybeWorld.isEmpty()) { + GameplayWorldCatalog.DiscoverySnapshot currentCatalog = + gameplayWorldCatalog.readDiscoverySnapshot(); + WorldSelectorResolution worldSelection = + resolvePlayWorld(context, selection.worldSelector(), currentCatalog); + if (worldSelection instanceof WorldSelectorResolution.Unavailable) { + return failure( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE, + "error.play.authority-unavailable", + Map.of(), + tenantTag, + null, + null, + null); + } + if (worldSelection instanceof WorldSelectorResolution.Stale) { + return failure( + "CONNECT_SCOPE_MISMATCH", + "World selection is stale; run WORLDS again.", + "error.play.connect-scope-mismatch", + Map.of(), + tenantTag, + null, + null, + null); + } + if (worldSelection instanceof WorldSelectorResolution.Invalid) { return failure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_MESSAGE, @@ -180,10 +211,47 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { null, null); } + GameplayWorldCatalog.WorldView selectedWorld = + ((WorldSelectorResolution.Selected) worldSelection).world(); + if (!gameplayWorldCatalog.hasValidPublicProductionRealm(currentCatalog, selectedWorld)) { + return failure( + "ADMISSION_POINTER_UNAVAILABLE", + "Gameplay admission pointer is unavailable", + "error.play.authority-unavailable", + Map.of(), + tenantTag, + null, + null, + null); + } - GameplayWorldCatalog.WorldView selectedWorld = maybeWorld.get(); - if (!gameplayWorldCatalog.hasValidPublicProductionRealm(selectedWorld)) { - return admissionPointerUnavailableFailure(tenantTag, null); + boolean numericRealmSelector = + GameplayWorldCatalog.isOrdinalSelector(selection.explicitRealmSelector()); + RealmSelectorResolution realmSelection = + numericRealmSelector + ? resolvePlayRealm(context, selectedWorld, selection.explicitRealmSelector()) + : new RealmSelectorResolution.NoSelection(); + if (realmSelection instanceof RealmSelectorResolution.Unavailable) { + return failure( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE, + "error.play.authority-unavailable", + Map.of(), + tenantTag, + null, + null, + null); + } + if (realmSelection instanceof RealmSelectorResolution.Stale) { + return failure( + "CONNECT_SCOPE_MISMATCH", + "Realm selection is stale; run REALMS again.", + "error.play.connect-scope-mismatch", + Map.of(), + tenantTag, + null, + null, + null); } FirstPartyConnectContextResolution connectContextResolution = FirstPartyConnectContextResolution.resolve( @@ -195,11 +263,40 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { ? Long.toString(context.bootstrapGameInstanceId()) : null); } + if (!numericRealmSelector) { + realmSelection = + StringUtils.hasText(selection.explicitRealmSelector()) + ? resolvePlayRealm(context, selectedWorld, selection.explicitRealmSelector()) + : new RealmSelectorResolution.NoSelection(); + } + if (realmSelection instanceof RealmSelectorResolution.Unavailable) { + return failure( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE, + "error.play.authority-unavailable", + Map.of(), + tenantTag, + null, + null, + null); + } + if (realmSelection instanceof RealmSelectorResolution.Stale) { + return failure( + "CONNECT_SCOPE_MISMATCH", + "Realm selection is stale; run REALMS again.", + "error.play.connect-scope-mismatch", + Map.of(), + tenantTag, + null, + null, + null); + } Optional maybeRealm = - selection.explicitRealmSelector() != null - ? gameplayWorldCatalog.resolveRealmForAdmission( - selectedWorld, selection.explicitRealmSelector()) - : selectDefaultRealm(selectedWorld, connectContextResolution.connectContext()); + realmSelection instanceof RealmSelectorResolution.Selected selected + ? Optional.of(selected.realm()) + : selection.explicitRealmSelector() != null + ? Optional.empty() + : selectDefaultRealm(selectedWorld, connectContextResolution.connectContext()); if (maybeRealm.isEmpty()) { return failure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, @@ -964,6 +1061,129 @@ private boolean maybeRecordFreshEntryFallback( return true; } + private WorldSelectorResolution resolvePlayWorld( + SessionContext context, + String selector, + GameplayWorldCatalog.DiscoverySnapshot currentCatalog) { + if (!StringUtils.hasText(selector)) { + return new WorldSelectorResolution.Invalid(); + } + if (!GameplayWorldCatalog.isOrdinalSelector(selector)) { + return gameplayWorldCatalog + .resolveStableWorld(currentCatalog, selector) + .map(WorldSelectorResolution.Selected::new) + .orElseGet(WorldSelectorResolution.Invalid::new); + } + Optional maybeSnapshot; + try { + maybeSnapshot = connectScopeSessionStore.worldsSnapshot(context, Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return new WorldSelectorResolution.Unavailable(); + } + if (maybeSnapshot.isEmpty()) { + return new WorldSelectorResolution.Stale(); + } + DirectTextConnectScopeSessionStore.WorldsSnapshot snapshot = maybeSnapshot.orElseThrow(); + if (!snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + return new WorldSelectorResolution.Stale(); + } + int ordinal; + try { + ordinal = Integer.parseInt(selector.trim()); + } catch (NumberFormatException ex) { + return new WorldSelectorResolution.Stale(); + } + Optional maybeTarget = + snapshot.ordinalTargets().stream() + .filter(target -> target.ordinal() == ordinal) + .findFirst(); + if (maybeTarget.isEmpty()) { + return new WorldSelectorResolution.Stale(); + } + return gameplayWorldCatalog + .resolveSnapshotOrdinal(currentCatalog, maybeTarget.orElseThrow()) + .map(WorldSelectorResolution.Selected::new) + .orElseGet(WorldSelectorResolution.Stale::new); + } + + private RealmSelectorResolution resolvePlayRealm( + SessionContext context, GameplayWorldCatalog.WorldView world, String selector) { + if (!StringUtils.hasText(selector)) { + return new RealmSelectorResolution.NoSelection(); + } + if (!GameplayWorldCatalog.isOrdinalSelector(selector)) { + return gameplayWorldCatalog + .resolveRealmForAdmission(world, selector) + .map(RealmSelectorResolution.Selected::new) + .orElseGet(RealmSelectorResolution.Invalid::new); + } + Optional maybeSnapshot; + try { + maybeSnapshot = connectScopeSessionStore.realmsSnapshot(context, world.slug(), Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return new RealmSelectorResolution.Unavailable(); + } + if (maybeSnapshot.isEmpty()) { + return new RealmSelectorResolution.Stale(); + } + DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = + gameplayWorldCatalog.readRealmDiscoverySnapshot(world); + if (!snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { + return new RealmSelectorResolution.Stale(); + } + int ordinal; + try { + ordinal = Integer.parseInt(selector.trim()); + } catch (NumberFormatException ex) { + return new RealmSelectorResolution.Stale(); + } + Optional maybeTarget = + snapshot.ordinalTargets().stream() + .filter(target -> target.ordinal() == ordinal) + .findFirst(); + if (maybeTarget.isEmpty()) { + return new RealmSelectorResolution.Stale(); + } + return gameplayWorldCatalog + .resolveRealmSnapshotOrdinal(world, currentRealmCatalog, maybeTarget.orElseThrow()) + .map(RealmSelectorResolution.Selected::new) + .orElseGet(RealmSelectorResolution.Stale::new); + } + + private sealed interface WorldSelectorResolution + permits WorldSelectorResolution.Selected, + WorldSelectorResolution.Invalid, + WorldSelectorResolution.Stale, + WorldSelectorResolution.Unavailable { + record Selected(GameplayWorldCatalog.WorldView world) implements WorldSelectorResolution {} + + record Invalid() implements WorldSelectorResolution {} + + record Stale() implements WorldSelectorResolution {} + + record Unavailable() implements WorldSelectorResolution {} + } + + private sealed interface RealmSelectorResolution + permits RealmSelectorResolution.Selected, + RealmSelectorResolution.NoSelection, + RealmSelectorResolution.Invalid, + RealmSelectorResolution.Stale, + RealmSelectorResolution.Unavailable { + record Selected(GameplayWorldCatalog.RealmView realm) implements RealmSelectorResolution {} + + record NoSelection() implements RealmSelectorResolution {} + + record Invalid() implements RealmSelectorResolution {} + + record Stale() implements RealmSelectorResolution {} + + record Unavailable() implements RealmSelectorResolution {} + } + private Optional resolveSelection( TextCommandPayload.PlayRequest playRequest) { String worldSelector = playRequest.worldSelector(); @@ -983,8 +1203,14 @@ private Optional resolveSelection( new ResolvedPlaySelection(worldSelector.trim(), secondSelector, characterSelector)); } + if (StringUtils.hasText(secondSelector) + && (GameplayWorldCatalog.isOrdinalSelector(worldSelector) + || GameplayWorldCatalog.isOrdinalSelector(secondSelector))) { + return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), secondSelector, null)); + } Optional maybeWorld = - gameplayWorldCatalog.resolveWorld(worldSelector); + gameplayWorldCatalog.resolveStableWorld( + gameplayWorldCatalog.readDiscoverySnapshot(), worldSelector); if (maybeWorld.isPresent() && StringUtils.hasText(secondSelector) && !gameplayWorldCatalog.hasRealmForAdmission(maybeWorld.orElseThrow(), secondSelector)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 47adc089d3..eebfd4e616 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -139,6 +139,7 @@ public RealmBrowseResult browseRealms( return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } List visibleEntries = new ArrayList<>(); + List responseRealms = new ArrayList<>(); List issuedScopes = new ArrayList<>(); String requestId = sessionContext.sessionId() + ":" + UUID.randomUUID(); for (GameplayWorldCatalog.RealmView realm : worldCatalog.visibleRealms(world)) { @@ -190,11 +191,20 @@ public RealmBrowseResult browseRealms( realm.slug(), true, scopeResponse.getConnectScopeId(), expiresAt, playerContext)); } visibleEntries.add(realmEntry(visibleEntries.size() + 1, realm)); + responseRealms.add(realm); } try { - connectScopeSessionStore.replaceWorldScopes( - sessionContext, worldSelector, world.slug(), issuedScopes); + GameplayWorldCatalog.RealmDiscoverySnapshot realmSnapshot = + worldCatalog.realmDiscoverySnapshot(world, responseRealms); + connectScopeSessionStore.replaceRealmSnapshot( + sessionContext, + worldSelector, + world.slug(), + realmSnapshot.catalogFingerprint(), + realmSnapshot.ordinalTargets(), + issuedScopes, + Instant.now()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); @@ -274,6 +284,73 @@ private static long requireTransportSessionId(String sessionId) { new IllegalArgumentException("positive numeric transport session ID is required")); } + private RealmSelectorResolution resolveLobbyRealm( + SessionContext caller, + GameplayWorldCatalog.WorldView world, + String selector, + GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog) { + if (!StringUtils.hasText(selector)) { + return new RealmSelectorResolution.NoSelection(); + } + if (!GameplayWorldCatalog.isOrdinalSelector(selector)) { + return worldCatalog + .resolveRealm(world, selector) + .map(RealmSelectorResolution.Selected::new) + .orElseGet(RealmSelectorResolution.Invalid::new); + } + if (connectScopeSessionStore == null) { + return new RealmSelectorResolution.Unavailable(); + } + Optional maybeSnapshot; + try { + maybeSnapshot = connectScopeSessionStore.realmsSnapshot(caller, world.slug(), Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return new RealmSelectorResolution.Unavailable(); + } + if (maybeSnapshot.isEmpty()) { + return new RealmSelectorResolution.Stale(); + } + DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); + if (!snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + return new RealmSelectorResolution.Stale(); + } + int ordinal; + try { + ordinal = Integer.parseInt(selector.trim()); + } catch (NumberFormatException ex) { + return new RealmSelectorResolution.Stale(); + } + Optional maybeTarget = + snapshot.ordinalTargets().stream() + .filter(target -> target.ordinal() == ordinal) + .findFirst(); + if (maybeTarget.isEmpty()) { + return new RealmSelectorResolution.Stale(); + } + return worldCatalog + .resolveRealmSnapshotOrdinal(world, currentCatalog, maybeTarget.orElseThrow()) + .map(RealmSelectorResolution.Selected::new) + .orElseGet(RealmSelectorResolution.Stale::new); + } + + private sealed interface RealmSelectorResolution + permits RealmSelectorResolution.Selected, + RealmSelectorResolution.NoSelection, + RealmSelectorResolution.Invalid, + RealmSelectorResolution.Stale, + RealmSelectorResolution.Unavailable { + record Selected(GameplayWorldCatalog.RealmView realm) implements RealmSelectorResolution {} + + record NoSelection() implements RealmSelectorResolution {} + + record Invalid() implements RealmSelectorResolution {} + + record Stale() implements RealmSelectorResolution {} + + record Unavailable() implements RealmSelectorResolution {} + } + private sealed interface WorldSelectorResolution { record Selected(GameplayWorldCatalog.WorldView world) implements WorldSelectorResolution {} @@ -637,12 +714,24 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = + worldCatalog.readRealmDiscoverySnapshot(world); + RealmSelectorResolution realmSelection = + resolveLobbyRealm(sessionContext, world, realmSelector, currentRealmCatalog); + if (realmSelection instanceof RealmSelectorResolution.Unavailable) { + return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } + if (realmSelection instanceof RealmSelectorResolution.Stale) { + return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + } java.util.Optional maybeRealm = - StringUtils.hasText(realmSelector) - ? worldCatalog.resolveRealm(world, realmSelector) - : worldCatalog.requiresExplicitRealmSelection(world) + realmSelection instanceof RealmSelectorResolution.Selected selected + ? java.util.Optional.of(selected.realm()) + : StringUtils.hasText(realmSelector) ? java.util.Optional.empty() - : worldCatalog.resolveDefaultRealm(world); + : worldCatalog.requiresExplicitRealmSelection(world) + ? java.util.Optional.empty() + : worldCatalog.resolveDefaultRealm(world); if (StringUtils.hasText(realmSelector) && maybeRealm.isEmpty()) { return CharacterBrowseResult.invalidRealm(world.slug()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index 4e9d7be6a3..f367c3b180 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -139,6 +139,19 @@ public void replaceWorldScopes( String requestedWorldSelector, String canonicalWorldSlug, List scopes) { + replaceRealmSnapshot( + caller, requestedWorldSelector, canonicalWorldSlug, null, List.of(), scopes, Instant.now()); + } + + /** Atomically stores the exact REALMS response and any Account scopes it produced. */ + public void replaceRealmSnapshot( + SessionContext caller, + String requestedWorldSelector, + String canonicalWorldSlug, + String catalogFingerprint, + List ordinalTargets, + List scopes, + Instant now) { Objects.requireNonNull(caller, "caller must not be null"); requireCallerIdentity(caller); String requestedSelector = normalizeSelector(requestedWorldSelector); @@ -146,15 +159,27 @@ public void replaceWorldScopes( if (requestedSelector == null || worldSlug == null) { throw new IllegalArgumentException("world selectors must not be blank"); } + Objects.requireNonNull(now, "now must not be null"); + List safeTargets = + List.copyOf(Objects.requireNonNull(ordinalTargets, "ordinalTargets must not be null")); + if (catalogFingerprint == null) { + if (!safeTargets.isEmpty()) { + throw new IllegalArgumentException("catalogFingerprint must not be null"); + } + } else if (catalogFingerprint.isBlank()) { + throw new IllegalArgumentException("catalogFingerprint must not be blank"); + } + validateRealmOrdinalTargets(safeTargets); List safeScopes = List.copyOf(Objects.requireNonNull(scopes, "scopes must not be null")); safeScopes.forEach(scope -> validateScopeIdentity(caller, scope)); - long nowMillis = Instant.now().toEpochMilli(); + long nowMillis = now.toEpochMilli(); List storedScopes = safeScopes.stream() .filter(scope -> scope.expiresAt().toEpochMilli() > nowMillis) .map(scope -> storeScope(scope, nowMillis)) .toList(); + long snapshotExpiresAtMillis = now.plus(WORLDS_SNAPSHOT_TTL).toEpochMilli(); mutate( caller.sessionId(), @@ -165,17 +190,27 @@ public void replaceWorldScopes( throw new ConflictingIdentityException("lobby record transport session did not match"); } if (record.accountId() > 0L && record.accountId() != caller.accountId()) { - record = LobbyRecord.empty(caller.sessionId()).withWorldSnapshotFrom(record); + record = LobbyRecord.empty(caller.sessionId()); } Map> byWorld = new HashMap<>(record.scopesByWorld()); Map worldBySelector = new HashMap<>(record.worldBySelector()); + Map realmsByWorld = new HashMap<>(record.realmsByWorld()); byWorld.remove(worldSlug); + realmsByWorld.remove(worldSlug); worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); if (!storedScopes.isEmpty()) { byWorld.put(worldSlug, storedScopes); worldBySelector.put(worldSlug, worldSlug); worldBySelector.put(requestedSelector, worldSlug); } + if (catalogFingerprint != null) { + worldBySelector.put(worldSlug, worldSlug); + worldBySelector.put(requestedSelector, worldSlug); + realmsByWorld.put( + worldSlug, + new StoredRealmsSnapshot( + worldSlug, catalogFingerprint, snapshotExpiresAtMillis, safeTargets)); + } return new LobbyRecord( caller.sessionId(), caller.accountId(), @@ -183,10 +218,36 @@ record = LobbyRecord.empty(caller.sessionId()).withWorldSnapshotFrom(record); record.catalogFingerprint(), record.ordinalTargets(), byWorld, - worldBySelector); + worldBySelector, + realmsByWorld); }); } + public Optional realmsSnapshot( + SessionContext caller, String canonicalWorldSlug, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); + requireCallerIdentity(caller); + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (worldSlug == null) { + return Optional.empty(); + } + LobbyRecord record = readRecord(caller.sessionId()); + if (!matchesCaller(record, caller)) { + return Optional.empty(); + } + StoredRealmsSnapshot snapshot = record.realmsByWorld().get(worldSlug); + if (snapshot == null || snapshot.expiresAtEpochMs() <= now.toEpochMilli()) { + return Optional.empty(); + } + return Optional.of( + new RealmsSnapshot( + snapshot.worldSlug(), + snapshot.catalogFingerprint(), + Instant.ofEpochMilli(snapshot.expiresAtEpochMs()), + snapshot.ordinalTargets())); + } + public void clearWorldScopes(SessionContext caller, String worldSelector) { Objects.requireNonNull(caller, "caller must not be null"); requireCallerIdentity(caller); @@ -207,14 +268,16 @@ public void clearWorldScopes(SessionContext caller, String worldSelector) { } LobbyRecord record = current; if (record.accountId() > 0L && record.accountId() != caller.accountId()) { - record = LobbyRecord.empty(caller.sessionId()).withWorldSnapshotFrom(record); + record = LobbyRecord.empty(caller.sessionId()); } String worldSlug = record.worldBySelector().get(selector); if (worldSlug == null) { return record.withAccountId(caller.accountId()); } Map> byWorld = new HashMap<>(record.scopesByWorld()); + Map realmsByWorld = new HashMap<>(record.realmsByWorld()); byWorld.remove(worldSlug); + realmsByWorld.remove(worldSlug); Map worldBySelector = new HashMap<>(record.worldBySelector()); worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); return new LobbyRecord( @@ -224,7 +287,8 @@ record = LobbyRecord.empty(caller.sessionId()).withWorldSnapshotFrom(record); record.catalogFingerprint(), record.ordinalTargets(), byWorld, - worldBySelector); + worldBySelector, + realmsByWorld); }); } @@ -386,9 +450,23 @@ private LobbyRecord pruneExpired(LobbyRecord record, long nowMillis) { scopesByWorld.put(world, remaining); } }); + Map realmsByWorld = new HashMap<>(); + record + .realmsByWorld() + .forEach( + (world, snapshot) -> { + if (snapshot.expiresAtEpochMs() > nowMillis) { + realmsByWorld.put(world, snapshot); + } + }); Map worldBySelector = new HashMap<>(record.worldBySelector()); - worldBySelector.entrySet().removeIf(entry -> !scopesByWorld.containsKey(entry.getValue())); - if (worldsExpiry == 0L && scopesByWorld.isEmpty()) { + worldBySelector + .entrySet() + .removeIf( + entry -> + !scopesByWorld.containsKey(entry.getValue()) + && !realmsByWorld.containsKey(entry.getValue())); + if (worldsExpiry == 0L && scopesByWorld.isEmpty() && realmsByWorld.isEmpty()) { return null; } return new LobbyRecord( @@ -398,7 +476,8 @@ private LobbyRecord pruneExpired(LobbyRecord record, long nowMillis) { fingerprint, ordinalTargets, scopesByWorld, - worldBySelector); + worldBySelector, + realmsByWorld); } private long remainingTtlMillis(LobbyRecord record, long nowMillis) { @@ -411,6 +490,9 @@ private long remainingTtlMillis(LobbyRecord record, long nowMillis) { maxExpiry = Math.max(maxExpiry, scope.expiresAtEpochMs()); } } + for (StoredRealmsSnapshot snapshot : record.realmsByWorld().values()) { + maxExpiry = Math.max(maxExpiry, snapshot.expiresAtEpochMs()); + } return maxExpiry - nowMillis; } @@ -472,6 +554,16 @@ private static void validateOrdinalTargets(List targets) { } } + private static void validateRealmOrdinalTargets(List targets) { + for (int index = 0; index < targets.size(); index++) { + RealmOrdinalTarget target = + Objects.requireNonNull(targets.get(index), "target must not be null"); + if (target.ordinal() != index + 1) { + throw new IllegalArgumentException("realm ordinal targets must be contiguous and ordered"); + } + } + } + private static void requireCallerIdentity(SessionContext caller) { if (caller.accountId() <= 0L) { throw new IllegalArgumentException("authenticated account is required"); @@ -536,6 +628,26 @@ public record WorldOrdinalTarget( } } + public record RealmOrdinalTarget( + int ordinal, + String realmSlug, + long tenantId, + long catalogRevision, + long pointerVersion, + String targetFingerprint) { + public RealmOrdinalTarget { + if (ordinal < 1 || tenantId <= 0L || catalogRevision < 0L || pointerVersion < 0L) { + throw new IllegalArgumentException("realm ordinal target authority was invalid"); + } + if (realmSlug == null + || realmSlug.isBlank() + || targetFingerprint == null + || targetFingerprint.isBlank()) { + throw new IllegalArgumentException("realm ordinal target identity must not be blank"); + } + } + } + public record WorldsSnapshot( String catalogFingerprint, Instant expiresAt, List ordinalTargets) { public WorldsSnapshot { @@ -549,6 +661,25 @@ public record WorldsSnapshot( } } + public record RealmsSnapshot( + String worldSlug, + String catalogFingerprint, + Instant expiresAt, + List ordinalTargets) { + public RealmsSnapshot { + if (worldSlug == null || worldSlug.isBlank()) { + throw new IllegalArgumentException("worldSlug must not be blank"); + } + if (catalogFingerprint == null || catalogFingerprint.isBlank()) { + throw new IllegalArgumentException("catalogFingerprint must not be blank"); + } + Objects.requireNonNull(expiresAt, "expiresAt must not be null"); + ordinalTargets = + List.copyOf(Objects.requireNonNull(ordinalTargets, "ordinalTargets must not be null")); + validateRealmOrdinalTargets(ordinalTargets); + } + } + @SuppressFBWarnings( value = "EI_EXPOSE_REP", justification = "Generated protobuf execution contexts are immutable value messages.") @@ -729,6 +860,18 @@ private StoredScopedRealm withJoinRequestId(String requestId) { } } + private record StoredRealmsSnapshot( + String worldSlug, + String catalogFingerprint, + long expiresAtEpochMs, + List ordinalTargets) { + private StoredRealmsSnapshot { + Objects.requireNonNull(worldSlug, "worldSlug must not be null"); + Objects.requireNonNull(catalogFingerprint, "catalogFingerprint must not be null"); + ordinalTargets = List.copyOf(ordinalTargets == null ? List.of() : ordinalTargets); + } + } + private record LobbyRecord( long sessionId, long accountId, @@ -736,7 +879,8 @@ private record LobbyRecord( String catalogFingerprint, List ordinalTargets, Map> scopesByWorld, - Map worldBySelector) { + Map worldBySelector, + Map realmsByWorld) { private LobbyRecord { ordinalTargets = ordinalTargets == null ? List.of() : List.copyOf(ordinalTargets); Map> scopesCopy = new HashMap<>(); @@ -745,10 +889,11 @@ private record LobbyRecord( } scopesByWorld = Map.copyOf(scopesCopy); worldBySelector = worldBySelector == null ? Map.of() : Map.copyOf(worldBySelector); + realmsByWorld = realmsByWorld == null ? Map.of() : Map.copyOf(realmsByWorld); } private static LobbyRecord empty(long sessionId) { - return new LobbyRecord(sessionId, 0L, 0L, null, List.of(), Map.of(), Map.of()); + return new LobbyRecord(sessionId, 0L, 0L, null, List.of(), Map.of(), Map.of(), Map.of()); } private LobbyRecord normalized() { @@ -762,7 +907,8 @@ private LobbyRecord normalized() { catalogFingerprint, ordinalTargets, scopesByWorld, - worldBySelector); + worldBySelector, + realmsByWorld); } private LobbyRecord withWorldSnapshot( @@ -777,7 +923,8 @@ private LobbyRecord withWorldSnapshot( fingerprint, targets, scopesByWorld, - worldBySelector); + worldBySelector, + realmsByWorld); } private LobbyRecord withWorldSnapshotFrom(LobbyRecord other) { @@ -788,7 +935,8 @@ private LobbyRecord withWorldSnapshotFrom(LobbyRecord other) { other.catalogFingerprint(), other.ordinalTargets(), scopesByWorld, - worldBySelector); + worldBySelector, + realmsByWorld); } private LobbyRecord withAccountId(long updatedAccountId) { @@ -799,7 +947,8 @@ private LobbyRecord withAccountId(long updatedAccountId) { catalogFingerprint, ordinalTargets, scopesByWorld, - worldBySelector); + worldBySelector, + realmsByWorld); } private LobbyRecord withScopes( @@ -811,7 +960,8 @@ private LobbyRecord withScopes( catalogFingerprint, ordinalTargets, updatedScopes, - updatedSelectors); + updatedSelectors, + realmsByWorld); } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 7cfdc5909e..d5d4759bbf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.util.List; +import java.util.UUID; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.junit.jupiter.api.Test; @@ -314,6 +315,55 @@ void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { assertThat(realm.playableStateNamespaceId()).isEqualTo(playableStateNamespaceId); } + @Test + void realmSnapshotResolvesByExactTargetIdentityAfterResponseOrdinalChanges() { + GameplayWorldCatalog.RealmView production = + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.RealmView preview = + new GameplayWorldCatalog.RealmView( + "preview", + "Preview Realm", + 7L, + 12L, + 4L, + true, + false, + false, + "SHARED", + "ALLOW_NEW", + 30L, + UUID.fromString("a11df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("b2a958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.WorldView original = + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(production, preview)); + GameplayWorldCatalog.WorldView reordered = + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(preview, production)); + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(List.of(reordered)); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + GameplayWorldCatalog.forWorldViews(List.of(original)) + .realmDiscoverySnapshot(original, List.of(production, preview)); + + assertThat( + catalog.resolveRealmSnapshotOrdinal( + reordered, snapshot, snapshot.ordinalTargets().get(0))) + .contains(production); + assertThat(catalog.readRealmDiscoverySnapshot(reordered).catalogFingerprint()) + .isNotEqualTo(snapshot.catalogFingerprint()); + } + private static GameplayWorldCatalog.WorldView worldWithTargetRealm( String realmSlug, boolean visible) { return new GameplayWorldCatalog.WorldView( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 1ba3bea2ac..8805c3f0d5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.presentation.ErrorOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; @@ -62,6 +63,8 @@ class PlayCommandHandlerTest { private final GameplayWorldCatalog worldCatalog = TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); private final SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + private final DirectTextConnectScopeSessionStore connectScopeSessionStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); private PlayCommandHandler handler; @BeforeEach @@ -99,7 +102,8 @@ void setUp() { firstPartyConnectContextRegistry, gameplayPresenceLifecycleService, scriptEventPublisher, - meterRegistry); + meterRegistry, + connectScopeSessionStore); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -236,6 +240,60 @@ void playPromotesSessionIntoGameplay() { "play-spawn:1:1:7001:1"); } + @Test + void numericWorldPlayRejectsReorderedWorldSnapshotBeforeAdmissionSideEffects() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); + connectScopeSessionStore.replaceWorldSnapshot( + context.sessionId(), + context.accountId(), + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + java.time.Instant.now()); + gameplayCatalogProperties.setWorlds( + List.of( + gameplayCatalogProperties.getWorlds().get(1), + gameplayCatalogProperties.getWorlds().get(0))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("1"), "PLAY 1")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + + @Test + void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "1"), "PLAY demo 1")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { gameplayCatalogProperties diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index ee89c1e494..5b62578eb7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -288,7 +288,8 @@ void setUp() { firstPartyConnectContextRegistry, gameplayPresenceLifecycleService, scriptEventPublisher, - meterRegistry); + meterRegistry, + DirectTextConnectScopeSessionStore.inMemoryForTest()); worldsHandler = new WorldsCommandHandler( worldCatalog, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 7c7abb15ed..a0d7e75db1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -392,7 +392,8 @@ void setUp() { firstPartyConnectContextRegistry, gameplayPresenceLifecycleService, scriptEventPublisher, - meterRegistry); + meterRegistry, + DirectTextConnectScopeSessionStore.inMemoryForTest()); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); WhoCommandHandler whoHandler = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 88edd4d7b0..31323beffd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -187,6 +187,68 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { Mockito.argThat(context -> context.getTenantId().equals("22")), Mockito.any()); } + @Test + void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() { + GameplayWorldCatalog.RealmView production = + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + GameplayWorldCatalog.RealmView preview = + new GameplayWorldCatalog.RealmView( + "preview", + "Preview Realm", + 23L, + 2L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + GameplayWorldCatalog.WorldView original = + new GameplayWorldCatalog.WorldView("demo", "Demo World", List.of(production, preview)); + AtomicReference> worlds = + new AtomicReference<>(List.of(original)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldSupplier(worlds::get), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + localHandler.browseRealms("7", authenticatedSession(), "demo"); + Mockito.clearInvocations(accountClient, entityManagementClient); + worlds.set( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(preview, production)))); + + assertThat(localHandler.browseCharacters("7", authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + @Test void browseRealmsToleratesNullRealmEnums() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 503fe866ee..2901800c48 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -130,6 +130,29 @@ void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); } + @Test + void storesRealmsResponseSnapshotOnlyForTheIssuingAccountAndBeforeExpiry() { + SessionContext caller = session(41L, 7L); + Instant now = Instant.now(); + DirectTextConnectScopeSessionStore.RealmOrdinalTarget target = + new DirectTextConnectScopeSessionStore.RealmOrdinalTarget( + 1, "production", 22L, 29L, 3L, "realm-target-fingerprint"); + store.replaceRealmSnapshot( + caller, "demo", "demo", "realm-catalog-fingerprint", List.of(target), List.of(), now); + + assertThat(store.realmsSnapshot(caller, "demo", now)) + .hasValueSatisfying( + snapshot -> { + assertThat(snapshot.worldSlug()).isEqualTo("demo"); + assertThat(snapshot.catalogFingerprint()).isEqualTo("realm-catalog-fingerprint"); + assertThat(snapshot.ordinalTargets()).containsExactly(target); + assertThat(snapshot.expiresAt()).isBeforeOrEqualTo(now.plusSeconds(301)); + }); + assertThat(store.realmsSnapshot(session(41L, 8L), "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(session(42L, 7L), "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(caller, "demo", now.plusSeconds(301))).isEmpty(); + } + @Test void rejectsInvalidTransportIdsAndScopesBoundToAnotherIdentity() { assertThatThrownBy(() -> store.clearSession(0L)).isInstanceOf(IllegalArgumentException.class); From 64fb10bf1d9805c00b6f8f32c9c70138675e4ac6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:25:47 +1300 Subject: [PATCH 008/105] Limit public world discovery to own public realm --- .../command/text/GameplayWorldCatalog.java | 16 +++++++++++++--- .../command/text/GameplayWorldCatalogTest.java | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index c2ed4da430..17b796c9b8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -62,7 +62,7 @@ public DiscoverySnapshot readDiscoverySnapshot() { catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); List discoverableWorlds = visibleWorlds.stream() - .filter(world -> resolveDefaultRealm(world, catalogWorlds).isPresent()) + .filter(world -> hasPublicDiscoveryRealm(world, catalogWorlds)) .toList(); ArrayList entries = new ArrayList<>(discoverableWorlds.size()); ArrayList targets = new ArrayList<>(discoverableWorlds.size()); @@ -553,11 +553,21 @@ private List worldEntries() { } private List discoverableWorlds() { - return visibleWorlds().stream() - .filter(world -> resolveDefaultRealm(world).isPresent()) + List catalogWorlds = normalizeWorlds(worldSupplier.get()); + return catalogWorlds.stream() + .filter(this::hasVisibleRealmEntries) + .filter(world -> hasPublicDiscoveryRealm(world, catalogWorlds)) .toList(); } + private boolean hasPublicDiscoveryRealm(WorldView world, List catalogWorlds) { + List publicProductionRealms = + visibleRealms(world).stream().filter(RealmView::publicProductionRealm).toList(); + return publicProductionRealms.size() == 1 + && hasValidPublicProductionRealm( + catalogWorlds, publicProductionRealms.getFirst().tenantId()); + } + private List realmEntries(WorldView world) { List realms = visibleRealms(world); ArrayList entries = new ArrayList<>(realms.size()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index d5d4759bbf..97f8150def 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -237,6 +237,24 @@ void publicProductionCardinalityCountsSameTenantCandidatesAcrossWorlds() { assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())).isEmpty(); } + @Test + void publicWorldsExcludePrivateOnlyWorldsFromSameTenant() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("public-world", "production", 7L, true), + worldWithRealm("private-world", "private", 7L, false))); + + assertThat(catalog.browseView().worlds()) + .extracting( + net.firedevops.firemud.gamesession.presentation.WorldsViewOutput.WorldEntry::slug) + .containsExactly("public-world"); + assertThat(catalog.resolveWorld("1")) + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("public-world")); + assertThat(catalog.resolveWorld("2")).isEmpty(); + assertThat(catalog.resolveWorld("private-world")).isPresent(); + } + @Test void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { GameplayWorldCatalog catalog = From 7c4c5235933d1c9a60eb7d5da4ccbf180b86aed7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:56:55 +1300 Subject: [PATCH 009/105] Disambiguate numeric-world PLAY after exact world resolution --- .../command/text/PlayCommandHandler.java | 28 ++++----- .../command/text/PlayCommandHandlerTest.java | 61 +++++++++++++++++++ 2 files changed, 74 insertions(+), 15 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index cd9f45bdb5..68f0ef2f0b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -173,11 +173,11 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { null); } - ResolvedPlaySelection selection = maybeSelection.orElseThrow(); + ResolvedPlaySelection requestedSelection = maybeSelection.orElseThrow(); GameplayWorldCatalog.DiscoverySnapshot currentCatalog = gameplayWorldCatalog.readDiscoverySnapshot(); WorldSelectorResolution worldSelection = - resolvePlayWorld(context, selection.worldSelector(), currentCatalog); + resolvePlayWorld(context, requestedSelection.worldSelector(), currentCatalog); if (worldSelection instanceof WorldSelectorResolution.Unavailable) { return failure( GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, @@ -213,6 +213,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } GameplayWorldCatalog.WorldView selectedWorld = ((WorldSelectorResolution.Selected) worldSelection).world(); + ResolvedPlaySelection selection = disambiguateSelection(requestedSelection, selectedWorld); if (!gameplayWorldCatalog.hasValidPublicProductionRealm(currentCatalog, selectedWorld)) { return failure( "ADMISSION_POINTER_UNAVAILABLE", @@ -1202,21 +1203,18 @@ private Optional resolveSelection( return Optional.of( new ResolvedPlaySelection(worldSelector.trim(), secondSelector, characterSelector)); } + return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), secondSelector, null)); + } - if (StringUtils.hasText(secondSelector) - && (GameplayWorldCatalog.isOrdinalSelector(worldSelector) - || GameplayWorldCatalog.isOrdinalSelector(secondSelector))) { - return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), secondSelector, null)); + private ResolvedPlaySelection disambiguateSelection( + ResolvedPlaySelection requestedSelection, GameplayWorldCatalog.WorldView selectedWorld) { + String secondSelector = requestedSelection.explicitRealmSelector(); + if (!StringUtils.hasText(secondSelector) + || GameplayWorldCatalog.isOrdinalSelector(secondSelector) + || gameplayWorldCatalog.hasRealmForAdmission(selectedWorld, secondSelector)) { + return requestedSelection; } - Optional maybeWorld = - gameplayWorldCatalog.resolveStableWorld( - gameplayWorldCatalog.readDiscoverySnapshot(), worldSelector); - if (maybeWorld.isPresent() - && StringUtils.hasText(secondSelector) - && !gameplayWorldCatalog.hasRealmForAdmission(maybeWorld.orElseThrow(), secondSelector)) { - return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), null, secondSelector)); - } - return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), secondSelector, null)); + return new ResolvedPlaySelection(requestedSelection.worldSelector(), null, secondSelector); } private Optional selectDefaultRealm( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 7cf38414df..662186ffdb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -285,6 +285,67 @@ void numericWorldPlayRejectsReorderedWorldSnapshotBeforeAdmissionSideEffects() { scriptEventPublisher); } + @Test + void numericWorldPlayTreatsUnrecognizedSecondSelectorAsCharacterWhenDefaultRealmIsUnambiguous() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); + connectScopeSessionStore.replaceWorldSnapshot( + context.sessionId(), + context.accountId(), + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + java.time.Instant.now()); + when(entityManagementClient.findCharacterByName( + context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Sora")) + .thenReturn( + Optional.of( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("7001") + .setName("Sora") + .build())); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("1", "Sora"), "PLAY 1 Sora")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as Sora"); + } + + @Test + void numericWorldCharacterPlayRejectsStaleWorldSnapshotBeforeAdmissionSideEffects() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); + connectScopeSessionStore.replaceWorldSnapshot( + context.sessionId(), + context.accountId(), + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + java.time.Instant.now()); + gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setPointerVersion(2L); + + PlayCommandHandlingResult result = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("1", "Sora"), "PLAY 1 Sora")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { SessionContext context = From c13726c2a3931643f37adcac03a82d68883aa050 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:03:17 +1300 Subject: [PATCH 010/105] Fail closed on logout replay and preserve player join authority --- .../game-session-service/protocols.md | 2 + .../game-session-service/runtime-and-data.md | 4 +- .../player-access-and-session.md | 4 +- .../command/text/GameplayWorldCatalog.java | 177 ++++++-- .../command/text/LogoutCommandHandler.java | 144 ++----- .../command/text/TextCommandInterpreter.java | 27 ++ .../WorldsTextCommandDispatchHandler.java | 2 +- .../GameSessionWebSocketHandler.java | 51 ++- ...essionWebSocketHandlerIntegrationTest.java | 70 ++-- .../text/GameplayWorldCatalogTest.java | 7 +- .../text/LogoutCommandHandlerTest.java | 394 ++++-------------- .../text/SessionResumptionFlowTest.java | 77 ++-- .../text/TextCommandInterpreterTest.java | 10 +- .../text/WorldsCommandHandlerTest.java | 77 ++++ .../WorldsTextCommandDispatchHandlerTest.java | 26 +- ...ionAccountCrossServiceIntegrationTest.java | 8 +- 16 files changed, 498 insertions(+), 582 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 77e44c073c..ddf7a4ad3a 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -14,6 +14,8 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` may return `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the current `PLAY` consumer does not classify the latter specifically as `INACTIVE`, and direct-text clients can then issue `JOIN` without creating or restoring membership implicitly. Current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration` in the runtime membership response, but the current text `PLAY` consumer still decides from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; it does not yet consume the lifecycle or authority-generation fields, so an `ACTIVE` or `INACTIVE` classification remains target-only in `PLAY`. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +For logout and retained private semantic context, [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) owns the binding termination fence and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) owns namespace-scoped `resumeContextGeneration` and replay eligibility. Current player text handling rejects `LOGOUT` before side effects, and first-party private semantic transcript replay is gated when durable episode/binding termination proof is unavailable; fresh authoritative `LOOK` remains available. This fail-closed child behavior does not establish the durable successor protocol or complete either ADR. + Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). ### Reset and Recovery Consequence 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 3cceb48a92..d6cb5b132e 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -31,7 +31,7 @@ The sections below define the target-state runtime contract. Current implementat - Current tick/session coordination also bypasses the target key/script boundary: `TickQueueControlService`/`TickServiceImpl` build untagged `gamesession:tick:*` keys and pass queue, pending, and lock keys together to Lua, while `RedisSessionContextService` performs watched multi-key writes across untagged `sessionctx:*` families. Those calls are not proven same-slot and can fail with `CROSSSLOT` on a supported Redis Cluster profile; the live families are not represented by the canonical builder/registry contract. This records current implementation/proof drift only; migration must use the canonical tagged builders, registered scripts, reset inventory, and fenced readback before claiming cluster support. - The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. - The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and places it in the persisted `SessionContext.jwt` value, which is serialized into Redis by `RedisSessionContextService`. This contradicts the process-local/no-raw-delegation-JWT boundary in ADR 0031. The target binding must persist only bounded non-secret evidence such as the token hash or opaque rebind handle; stripping the token, fenced cleanup of existing values, and focused no-secret serialization proof remain implementation work. -- Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. +- Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. Current player text handling rejects `LOGOUT` before side effects and gates private semantic transcript replay when durable termination proof is unavailable; fresh `LOOK` remains. This is fail-closed child behavior, not completion of the durable successor or either [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) or [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). - The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. @@ -198,7 +198,7 @@ Game Session persists the latest processed `disconnectSequence` per ` catalogWorlds = normalizeWorlds(worldSupplier.get()); + CatalogState catalogState = readCatalogState(); + List catalogWorlds = catalogState.worlds(); List visibleWorlds = catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); List discoverableWorlds = visibleWorlds.stream() - .filter(world -> hasPublicDiscoveryRealm(world, catalogWorlds)) + .filter(world -> hasPublicDiscoveryRealm(world, catalogState)) .toList(); ArrayList entries = new ArrayList<>(discoverableWorlds.size()); ArrayList targets = new ArrayList<>(discoverableWorlds.size()); for (WorldView world : discoverableWorlds) { - RealmView defaultRealm = resolveDefaultRealm(world, catalogWorlds).orElseThrow(); + RealmView defaultRealm = resolveDefaultRealm(world, catalogState).orElseThrow(); int ordinal = entries.size() + 1; entries.add( new WorldsViewOutput.WorldEntry( @@ -102,7 +103,8 @@ public DiscoverySnapshot readDiscoverySnapshot() { fingerprint( exactTargets.stream().map(GameplayWorldCatalog::targetFingerprintInput).toList()), exactTargets, - visibleWorlds); + visibleWorlds, + catalogState.publicProductionCounts()); } public Optional resolveStableWorld(DiscoverySnapshot snapshot, String selector) { @@ -227,19 +229,43 @@ public Optional resolveWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List catalogWorlds = normalizeWorlds(worldSupplier.get()); + CatalogState catalogState = readCatalogState(); + List catalogWorlds = catalogState.worlds(); List visibleWorlds = catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); - return resolveWorld(selector, visibleWorlds, discoverableWorlds(visibleWorlds, catalogWorlds)); + return resolveWorld( + selector, + visibleWorlds, + discoverableWorlds(visibleWorlds, catalogState)); } public Optional resolveWorldFromAuthoritySnapshot(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List visibleWorlds = visibleWorldsFromAuthoritySnapshot(); + if (authorityPointerSupplier == null) { + List visibleWorlds = visibleWorldsFromAuthoritySnapshot(); + CatalogState catalogState = + new CatalogState(visibleWorlds, publicProductionCounts(visibleWorlds)); + return resolveWorld(selector, visibleWorlds, visibleWorlds) + .filter(world -> hasValidPublicProductionRealm(world, catalogState)); + } + List pointers = authorityPointerSupplier.get(); + if (pointers == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (!hasCompleteAuthorityPointer(pointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer is incomplete"); + } + } + CatalogState catalogState = catalogStateFromPointers(pointers); + List visibleWorlds = + catalogState.worlds().stream().filter(this::hasVisibleRealmEntries).toList(); return resolveWorld(selector, visibleWorlds, visibleWorlds) - .filter(world -> hasValidPublicProductionRealm(world, visibleWorlds)); + .filter(world -> hasValidPublicProductionRealm(world, catalogState)); } private Optional resolveWorld( @@ -293,10 +319,11 @@ public Optional resolveDefaultRealm(WorldView world) { if (visibleRealms.isEmpty()) { return Optional.empty(); } - return resolveDefaultRealm(world, normalizeWorlds(worldSupplier.get())); + CatalogState catalogState = readCatalogState(); + return resolveDefaultRealm(world, catalogState); } - private Optional resolveDefaultRealm(WorldView world, List catalogWorlds) { + private Optional resolveDefaultRealm(WorldView world, CatalogState catalogState) { if (world == null) { return Optional.empty(); } @@ -311,27 +338,16 @@ private Optional resolveDefaultRealm(WorldView world, List } if (publicProductionRealms.size() == 1) { RealmView publicRealm = publicProductionRealms.getFirst(); - return hasValidPublicProductionRealm(catalogWorlds, publicRealm.tenantId()) + return hasValidPublicProductionRealm(catalogState, publicRealm.tenantId()) ? Optional.of(publicRealm) : Optional.empty(); } return visibleRealms.stream() - .allMatch(realm -> hasValidPublicProductionRealm(catalogWorlds, realm.tenantId())) + .allMatch(realm -> hasValidPublicProductionRealm(catalogState, realm.tenantId())) ? Optional.of(visibleRealms.getFirst()) : Optional.empty(); } - private boolean hasValidPublicProductionRealm(List catalogWorlds, long tenantId) { - long count = - catalogWorlds.stream() - .flatMap(world -> world.realms().stream()) - .filter(realm -> realm.tenantId() == tenantId) - .filter(this::isPlayerAddressable) - .filter(RealmView::publicProductionRealm) - .count(); - return count == 1L; - } - private static String worldTargetFingerprint(WorldView world, RealmView defaultRealm) { return fingerprint( List.of( @@ -419,7 +435,8 @@ public record DiscoverySnapshot( WorldsViewOutput output, String catalogFingerprint, List ordinalTargets, - List visibleWorlds) { + List visibleWorlds, + Map publicProductionCounts) { public DiscoverySnapshot { Objects.requireNonNull(output, "output must not be null"); if (catalogFingerprint == null || catalogFingerprint.isBlank()) { @@ -429,6 +446,10 @@ public record DiscoverySnapshot( List.copyOf(Objects.requireNonNull(ordinalTargets, "ordinalTargets must not be null")); visibleWorlds = List.copyOf(Objects.requireNonNull(visibleWorlds, "visibleWorlds must not be null")); + publicProductionCounts = + Map.copyOf( + Objects.requireNonNull( + publicProductionCounts, "publicProductionCounts must not be null")); } } @@ -455,13 +476,10 @@ public PublicProductionRealmCardinality publicProductionRealmCardinality(long te if (tenantId <= 0L) { return PublicProductionRealmCardinality.ZERO; } - long count = - normalizeWorlds(worldSupplier.get()).stream() - .flatMap(world -> world.realms().stream()) - .filter(realm -> realm.tenantId() == tenantId) - .filter(this::isPlayerAddressable) - .filter(RealmView::publicProductionRealm) - .count(); + return cardinality(readCatalogState().publicProductionCounts().getOrDefault(tenantId, 0L)); + } + + private static PublicProductionRealmCardinality cardinality(long count) { return switch (Long.compare(count, 1L)) { case -1 -> PublicProductionRealmCardinality.ZERO; case 0 -> PublicProductionRealmCardinality.EXACTLY_ONE; @@ -476,16 +494,16 @@ public boolean hasValidPublicProductionRealm(long tenantId) { /** Returns whether every tenant represented by this selected world has unambiguous authority. */ public boolean hasValidPublicProductionRealm(WorldView world) { - return hasValidPublicProductionRealm(world, normalizeWorlds(worldSupplier.get())); + return hasValidPublicProductionRealm(world, readCatalogState()); } - private boolean hasValidPublicProductionRealm(WorldView world, List catalogWorlds) { + private boolean hasValidPublicProductionRealm(WorldView world, CatalogState catalogState) { List visibleRealms = visibleRealms(world); return !visibleRealms.isEmpty() && visibleRealms.stream() .map(RealmView::tenantId) .distinct() - .allMatch(tenantId -> hasValidPublicProductionRealm(catalogWorlds, tenantId)); + .allMatch(tenantId -> hasValidPublicProductionRealm(catalogState, tenantId)); } public boolean hasValidPublicProductionRealm(DiscoverySnapshot snapshot, WorldView world) { @@ -496,7 +514,8 @@ public boolean hasValidPublicProductionRealm(DiscoverySnapshot snapshot, WorldVi .map(RealmView::tenantId) .distinct() .allMatch( - tenantId -> hasValidPublicProductionRealm(snapshot.visibleWorlds(), tenantId)); + tenantId -> + snapshot.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L); } public boolean requiresExplicitRealmSelection(WorldView world) { @@ -562,7 +581,7 @@ public List visibleRealms(WorldView world) { } public List visibleWorlds() { - return normalizeWorlds(worldSupplier.get()).stream() + return readCatalogState().worlds().stream() .filter(this::hasVisibleRealmEntries) .toList(); } @@ -594,10 +613,11 @@ public List visibleWorldsFromAuthoritySnapshot() { } private List worldEntries() { - List worlds = discoverableWorlds(); + CatalogState catalogState = readCatalogState(); + List worlds = discoverableWorlds(catalogState); ArrayList entries = new ArrayList<>(worlds.size()); for (WorldView world : worlds) { - RealmView defaultRealm = resolveDefaultRealm(world).orElseThrow(); + RealmView defaultRealm = resolveDefaultRealm(world, catalogState).orElseThrow(); entries.add( new WorldsViewOutput.WorldEntry( entries.size() + 1, @@ -610,25 +630,28 @@ private List worldEntries() { } private List discoverableWorlds() { - List catalogWorlds = normalizeWorlds(worldSupplier.get()); + return discoverableWorlds(readCatalogState()); + } + + private List discoverableWorlds(CatalogState catalogState) { + List catalogWorlds = catalogState.worlds(); List visibleWorlds = catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); - return discoverableWorlds(visibleWorlds, catalogWorlds); + return discoverableWorlds(visibleWorlds, catalogState); } private List discoverableWorlds( - List visibleWorlds, List catalogWorlds) { + List visibleWorlds, CatalogState catalogState) { return visibleWorlds.stream() - .filter(world -> hasPublicDiscoveryRealm(world, catalogWorlds)) + .filter(world -> hasPublicDiscoveryRealm(world, catalogState)) .toList(); } - private boolean hasPublicDiscoveryRealm(WorldView world, List catalogWorlds) { + private boolean hasPublicDiscoveryRealm(WorldView world, CatalogState catalogState) { List publicProductionRealms = visibleRealms(world).stream().filter(RealmView::publicProductionRealm).toList(); return publicProductionRealms.size() == 1 - && hasValidPublicProductionRealm( - catalogWorlds, publicProductionRealms.getFirst().tenantId()); + && hasValidPublicProductionRealm(catalogState, publicProductionRealms.getFirst().tenantId()); } private List realmEntries(WorldView world) { @@ -661,6 +684,60 @@ private boolean isPlayerAddressable(RealmView realm) { && realm.tenantId() > 0L; } + private boolean hasValidPublicProductionRealm(CatalogState catalogState, long tenantId) { + return tenantId > 0L + && catalogState.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L; + } + + private CatalogState readCatalogState() { + if (authorityPointerSupplier == null) { + List worlds = normalizeWorlds(worldSupplier.get()); + return new CatalogState(worlds, publicProductionCounts(worlds)); + } + List pointers = authorityPointerSupplier.get(); + if (pointers == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + return catalogStateFromPointers(pointers); + } + + private static CatalogState catalogStateFromPointers( + List pointers) { + return new CatalogState(toWorlds(pointers), publicProductionCountsFromPointers(pointers)); + } + + private Map publicProductionCounts(List worlds) { + Map counts = new LinkedHashMap<>(); + for (WorldView world : worlds) { + if (world.realms() == null) { + continue; + } + for (RealmView realm : world.realms()) { + if (isPlayerAddressable(realm) && realm.publicProductionRealm()) { + counts.merge(realm.tenantId(), 1L, Long::sum); + } + } + } + return Map.copyOf(counts); + } + + private static Map publicProductionCountsFromPointers( + List pointers) { + Map counts = new LinkedHashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (hasCompleteAuthorityPointer(pointer) + && pointer.visible() + && pointer.tenantId() > 0L + && pointer.realmSlug() != null + && !pointer.realmSlug().isBlank() + && pointer.publicProductionRealm()) { + counts.merge(pointer.tenantId(), 1L, Long::sum); + } + } + return Map.copyOf(counts); + } + private static List normalizeWorlds(List worlds) { if (worlds == null) { return List.of(); @@ -672,6 +749,16 @@ private static List normalizeWorlds(List worlds) { .toList(); } + private record CatalogState(List worlds, Map publicProductionCounts) { + private CatalogState { + worlds = List.copyOf(Objects.requireNonNull(worlds, "worlds must not be null")); + publicProductionCounts = + Map.copyOf( + Objects.requireNonNull( + publicProductionCounts, "publicProductionCounts must not be null")); + } + } + private static List toWorlds(List pointers) { Map worlds = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java index 2761f5c06b..fe83169f9f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java @@ -5,104 +5,52 @@ import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; -import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; -import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; -import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; -import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; -import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.SessionIdParsing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -/** Handles deliberate player logout distinct from reconnect-loss recovery. */ +/** Handles deliberate player logout, which remains unavailable until its durable fence exists. */ @Component public final class LogoutCommandHandler { - private final SessionAuthenticationService sessionAuthenticationService; private final SessionContextService sessionContextService; - private final GameInstanceService gameInstanceService; - private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService; - private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; - private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry; - private final ScriptEventPublisher scriptEventPublisher; - private final DirectTextConnectScopeSessionStore directTextConnectScopeSessionStore; @Autowired - public LogoutCommandHandler( - SessionAuthenticationService sessionAuthenticationService, - SessionContextService sessionContextService, - GameInstanceService gameInstanceService, - GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, - GameplayPresenceLifecycleService gameplayPresenceLifecycleService, - FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, - ScriptEventPublisher scriptEventPublisher, - DirectTextConnectScopeSessionStore directTextConnectScopeSessionStore) { - this.sessionAuthenticationService = - Objects.requireNonNull( - sessionAuthenticationService, "sessionAuthenticationService must not be null"); + public LogoutCommandHandler(SessionContextService sessionContextService) { this.sessionContextService = Objects.requireNonNull(sessionContextService, "sessionContextService must not be null"); - this.gameInstanceService = - Objects.requireNonNull(gameInstanceService, "gameInstanceService must not be null"); - this.gameplayAdmissionPointerAuthorityService = - Objects.requireNonNull( - gameplayAdmissionPointerAuthorityService, - "gameplayAdmissionPointerAuthorityService must not be null"); - this.gameplayPresenceLifecycleService = - Objects.requireNonNull( - gameplayPresenceLifecycleService, "gameplayPresenceLifecycleService must not be null"); - this.firstPartyConnectContextRegistry = - Objects.requireNonNull( - firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); - this.scriptEventPublisher = - Objects.requireNonNull(scriptEventPublisher, "scriptEventPublisher must not be null"); - this.directTextConnectScopeSessionStore = - Objects.requireNonNull( - directTextConnectScopeSessionStore, - "directTextConnectScopeSessionStore must not be null"); } public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) { Objects.requireNonNull(command, "command must not be null"); - Optional maybePersistedContext = resolvePersistedSessionContext(sessionId); - Optional maybeContext = - sessionAuthenticationService.resolveSessionContext(sessionId); - if (maybeContext.isEmpty()) { - return failure( - "NOT_LOGGED_IN", "You are not logged in.", "error.logout.not-logged-in", Map.of()); - } - SessionContext context = maybeContext.orElseThrow(); - SessionContext persistedContext = maybePersistedContext.orElse(context); + Optional maybeAuthenticatedContext; try { - if (context.hasGameplayIdentity()) { - scriptEventPublisher.publishCommandEvent(context, logoutCommand(context, command)); - } - boolean stopSession = shouldStopSession(context, persistedContext); - if (stopSession) { - gameInstanceService.stopSession(context.gameInstanceId()); - } - gameplayPresenceLifecycleService.recordDisconnected( - context.sessionId(), AccountRecentPresenceDisposition.LOGOUT); - firstPartyConnectContextRegistry.unregister(context.sessionId()); - sessionContextService.deleteBySessionId(context.tenantId(), context.sessionId()); - directTextConnectScopeSessionStore.clearSession(context.sessionId()); - return new LogoutCommandHandlingResult( - CommandEnqueueResult.success(), - List.of(PlayerOutput.notice("Logged out.", "notice.logout.success", Map.of()))); - } catch (IllegalArgumentException | IllegalStateException ex) { + maybeAuthenticatedContext = + SessionIdParsing.parse(sessionId) + .optionalValue() + .flatMap(sessionContextService::findBySessionId) + .filter(context -> context.accountId() > 0L); + } catch (RuntimeException ex) { + return unavailable(); + } + + if (maybeAuthenticatedContext.isEmpty()) { return failure( - "LOGOUT_FAILED", - "Logout failed.", - "error.logout.failed", - Map.of("reason", Optional.ofNullable(ex.getMessage()).orElse("unknown"))); + "NOT_LOGGED_IN", "You are not logged in.", "error.logout.not-logged-in", Map.of()); } + + return unavailable(); + } + + private LogoutCommandHandlingResult unavailable() { + return failure( + "LOGOUT_UNAVAILABLE", + "Logout is temporarily unavailable. Please try again.", + "error.logout.unavailable", + Map.of()); } private LogoutCommandHandlingResult failure( @@ -111,46 +59,4 @@ private LogoutCommandHandlingResult failure( CommandEnqueueResult.failure(code, message), List.of(PlayerOutput.error(code, message, messageKey, arguments))); } - - private static GameplayCommand logoutCommand(SessionContext context, TextCommand command) { - return ScriptEventGameplayCommands.syntheticWithId( - "logout-command:" - + context.sessionId() - + ":" - + context.gameInstanceId() - + ":" - + context.characterId(), - command, - TextCommandType.LOGOUT.name(), - null); - } - - private boolean shouldStopSession(SessionContext context, SessionContext persistedContext) { - return context.gameInstanceId() > 0 - && isConfirmedIsolatedRuntime(context) - && isConfirmedIsolatedRuntime(persistedContext); - } - - private boolean isConfirmedIsolatedRuntime(SessionContext context) { - if ("ISOLATED".equals(context.playableStateScope())) { - return true; - } - if ("SHARED".equals(context.playableStateScope())) { - return false; - } - return singularRuntimePointer(context) - .map(pointer -> "ISOLATED".equals(pointer.stateScope())) - .orElse(false); - } - - private Optional - singularRuntimePointer(SessionContext context) { - return GameplayAdmissionPointerSnapshots.singularCompletePointer( - gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( - context.tenantId(), context.gameInstanceId())); - } - - private Optional resolvePersistedSessionContext(String sessionIdText) { - return sessionAuthenticationService.resolveSessionContext(sessionIdText); - } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java index a46814bb8f..21a2240dd6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java @@ -235,6 +235,11 @@ public TextCommandInterpreter( public TextCommandInterpretationResult interpret( String sessionId, String rawLine, boolean requiresSoloTick) { + String firstToken = rawLine == null ? "" : rawLine.trim().split("\\s+", 2)[0]; + if (TextCommandType.fromToken(firstToken) == TextCommandType.LOGOUT) { + return interpretLogoutWithoutNormalization( + sessionId, parser.parse(rawLine, registry), requiresSoloTick); + } Optional context = sessionAuthenticationService.resolveSessionContext(sessionId); TextCommandRegistry activeRegistry = registryFor(context); @@ -248,6 +253,9 @@ public TextCommandInterpretationResult interpret( public TextCommandInterpretationResult interpret( String sessionId, TextCommand command, boolean requiresSoloTick) { + if (command.type() == TextCommandType.LOGOUT) { + return interpretLogoutWithoutNormalization(sessionId, command, requiresSoloTick); + } Optional context = sessionAuthenticationService.resolveSessionContext(sessionId); TextCommandRegistry activeRegistry = registryFor(context); @@ -258,6 +266,25 @@ public TextCommandInterpretationResult interpret( return interpret(sessionId, activeCommand, requiresSoloTick, context, activeRegistry); } + private TextCommandInterpretationResult interpretLogoutWithoutNormalization( + String sessionId, TextCommand command, boolean requiresSoloTick) { + // A rejected LOGOUT must not normalize a stale binding (and clear presence) before + // the fail-closed handler runs. The handler performs only a raw session read. + TextCommandDefinition definition = + registry + .findDefinition(command.commandId()) + .orElseGet( + () -> + TextCommandDefinition.extensionDefinition( + command.type(), command.commandId())); + TextCommandInterpretationResult result = + dispatcher.dispatch( + TextCommandDispatchGroup.SESSION, + new TextCommandDispatchRequest( + sessionId, command, requiresSoloTick, Optional.empty())); + return withResolvedCommand(result, command, definition); + } + private TextCommandInterpretationResult interpret( String sessionId, TextCommand command, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index 518c9b9bca..00b73d1308 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -140,7 +140,7 @@ private String joinFailureMessage(String code) { case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> "Account authority unavailable. Retry JOIN shortly."; case "ENTITLEMENT_UNAVAILABLE" -> - "Join policy could not be checked. Use REALMS and JOIN to start a new attempt later."; + "Join policy could not be checked. Retry the same JOIN while its realm scope is valid."; case "LOGIN_REQUIRED" -> "Log in before joining a world."; default -> "The selected world could not be joined."; }; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 3aa81f2452..d2f878fe15 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -180,7 +180,11 @@ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { - try (CombinedLoggingContext ignored = openLoggingContext(session)) { + TextCommand command = parser.parse(message.getPayload()); + try (CombinedLoggingContext ignored = + command.type() == TextCommandType.LOGOUT + ? openRuntimeLoggingContext(session) + : openLoggingContext(session)) { String sessionId = resolveTransportSessionId(session); if (!StringUtils.hasText(sessionId)) { session.sendMessage(new TextMessage("ERROR INVALID_ARGUMENT sessionId header required")); @@ -188,15 +192,31 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) return; } boolean requiresSoloTick = parseSoloTick(session); - TextCommand command = parser.parse(message.getPayload()); if (command.type() == TextCommandType.NOOP) { return; } - ensureBootstrapSessionContextIfMissing(session, sessionId); + if (command.type() != TextCommandType.LOGOUT) { + ensureBootstrapSessionContextIfMissing(session, sessionId); + } TextCommandInterpretationResult interpretation = interpreter.interpret(sessionId, command, requiresSoloTick); TextCommand resolvedCommand = interpretation.resolvedCommand() == null ? command : interpretation.resolvedCommand(); + if (command.type() == TextCommandType.LOGOUT) { + // No authentication normalization, bootstrap, prompt, locale write, or retained + // output read may accompany this fail-closed response. + sendProtocolMessage( + session, + outputProjector.projectCommandResponse( + session, + resolvedCommand, + interpretation, + interpretation.outputs(), + resolveLocaleTag(session), + settingsResolver.presentation(null), + null)); + return; + } recordGameplayActivity(sessionId, interpretation); Optional maybeContext = resolveNormalizedSessionContext(session, sessionId); PresentationProperties effectivePresentation = @@ -229,7 +249,7 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) outputs, resolveLocaleTag(session, sessionId), effectivePresentation); - maybeReplayScreenBufferAndRefreshLook( + maybeRenderFreshReconnectLook( session, sessionId, command, interpretation, maybeContext); maybeCloseAfterSuccessfulLogout(session, command, interpretation); } @@ -457,7 +477,7 @@ private void maybeAppendToScreenBuffer( replayEntries)); } - private void maybeReplayScreenBufferAndRefreshLook( + private void maybeRenderFreshReconnectLook( WebSocketSession session, String sessionId, TextCommand command, @@ -477,14 +497,10 @@ private void maybeReplayScreenBufferAndRefreshLook( .ifPresent( context -> { try (GameplayLoggingContext ignored = GameplayLoggingContext.from(context)) { - Optional maybeBuffer = - screenBufferService.get( - context.tenantId(), context.gameInstanceId(), context.characterId()); - if (maybeBuffer.isEmpty()) { - return; - } - maybeBuffer.ifPresent( - buffer -> sendReplayEntries(session, buffer, "screen buffer")); + // Private semantic replay stays closed until the durable resume-context + // generation and termination evidence required by ADR 0134 is available. + // A connect context or reconnect recommendation alone does not authorize + // reading retained private output. Fresh current state remains available. String localeTag = resolveLocaleTag(session, sessionId); PresentationProperties effectivePresentation = settingsResolver.presentation(context); @@ -619,6 +635,15 @@ private CombinedLoggingContext openLoggingContext(WebSocketSession session) { return new CombinedLoggingContext(runtimeContext, gameplayContext); } + private CombinedLoggingContext openRuntimeLoggingContext(WebSocketSession session) { + String correlationId = resolveTransportSessionId(session); + if (!StringUtils.hasText(correlationId)) { + correlationId = session.getId(); + } + return new CombinedLoggingContext( + RuntimeLoggingContext.open(runtimeIdentity, correlationId), GameplayLoggingContext.empty()); + } + private record CombinedLoggingContext( RuntimeLoggingContext runtimeContext, GameplayLoggingContext gameplayContext) implements AutoCloseable { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 2e83f690bd..53a1889ace 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.argThat; -import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.never; @@ -600,22 +599,20 @@ void websocketQuickLookUsesDistinctCommandLabelAndPrompt() throws Exception { } @Test - void websocketLogoutRetainsReplayStateAndClosesTransport() throws Exception { - GameplayWebSocketDriver.CloseEvent closeEvent; + void websocketLogoutFailsClosedWithoutDeletingSessionOrClosingTransport() throws Exception { try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("41")) { client.send("LOGOUT"); - closeEvent = client.awaitClosed(); + client.awaitContains("LOGOUT_UNAVAILABLE"); + assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isPresent(); + assertThat(client.responses()).noneMatch(payload -> payload.contains("OK LOGOUT")); } - assertThat(closeEvent.statusCode()).isEqualTo(CloseStatus.NORMAL.getCode()); - assertThat(closeEvent.reason()).isEqualTo("logout"); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEmpty(); verify(screenBufferService, never()).clear(22L, 1L, 123L); verify(commandService, never()).enqueue("41", "LOGOUT", false); } @Test - void freshLoginAfterLogoutDoesNotReplayStaleReconnectBuffer() throws Exception { + void freshReconnectAfterRejectedLogoutDoesNotReplayStaleBuffer() throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( Optional.of( @@ -640,7 +637,8 @@ void freshLoginAfterLogoutDoesNotReplayStaleReconnectBuffer() throws Exception { } @Test - void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception { + void unexpectedDisconnectKeepsFreshReconnectLookButDoesNotReplayPrivateContext() + throws Exception { clearInvocations(screenBufferService); when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( @@ -661,16 +659,17 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { - client.awaitContains("RECONNECT REPLAY APPEARS"); + client.awaitContains("Room: Login Hall"); secondPayloads = client.responses(); GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 1, java.time.Duration.ofSeconds(5)); assertThat(gameplayPresenceService.listConnectedByGameInstance(22L, 1L)) .anySatisfy(presence -> assertThat(presence.sessionId()).isEqualTo(42L)); } - assertThat(secondPayloads).anyMatch(payload -> payload.contains("RECONNECT REPLAY APPEARS")); + assertThat(secondPayloads).noneMatch(payload -> payload.contains("RECONNECT REPLAY APPEARS")); assertThat(secondPayloads).anyMatch(payload -> payload.startsWith("OK PLAY")); - verify(screenBufferService, atLeastOnce()).get(22L, 1L, 123L); + assertThat(secondPayloads).anyMatch(payload -> payload.contains("Room: Login Hall")); + verify(screenBufferService, never()).get(22L, 1L, 123L); verify(screenBufferService, never()).clear(22L, 1L, 123L); } @@ -1014,7 +1013,8 @@ void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { } @Test - void websocketFirstPartyReconnectReplaysBufferedScreenAndFreshLookAfterPlay() throws Exception { + void websocketFirstPartyReconnectSkipsPrivateContextAndKeepsFreshLookAfterPlay() + throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( Optional.of( @@ -1035,11 +1035,6 @@ void websocketFirstPartyReconnectReplaysBufferedScreenAndFreshLookAfterPlay() th client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.awaitMatching( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("Recent combat line"), - "replayed transcript chunk"); client.awaitMatching( payload -> "player_output".equals(json(payload).path("eventType").asText()) @@ -1063,10 +1058,12 @@ && containsKind(json(payload), "PROMPT"), GameplayStructuredCommandAssertions.isStructuredCommand( payload, "PLAY", "play", "META", "SESSION")); assertThat(payloads) - .anyMatch( + .noneMatch( payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("Recent combat line")); + ("transcript_chunk".equals(json(payload).path("eventType").asText()) + || "transcript_entry".equals(json(payload).path("eventType").asText())) + && (payload.contains("Recent combat line") + || payload.contains("Second recent line"))); assertThat(payloads) .anyMatch( payload -> @@ -1077,10 +1074,11 @@ && containsKind(json(payload), "PROMPT"), payload -> "player_output".equals(json(payload).path("eventType").asText()) && containsKind(json(payload), "PROMPT")); + verify(screenBufferService, never()).get(22L, 1L, 123L); } @Test - void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Exception { + void websocketFirstPartyLogoutDoesNotReplayRetainedContextForFreshReconnect() throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( Optional.of( @@ -1091,7 +1089,6 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep 1, 44L))); - GameplayWebSocketDriver.CloseEvent firstCloseEvent; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "logout-1"))) { client.send("LOGIN"); @@ -1101,10 +1098,14 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); client.send("LOGOUT"); - firstCloseEvent = client.awaitClosed(); + client.awaitMatching( + payload -> + isStructuredCommand(payload, "LOGOUT") + && "LOGOUT_UNAVAILABLE".equals(json(payload).path("errorCode").asText()), + "fail-closed LOGOUT result"); + assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)).isPresent(); } - assertThat(firstCloseEvent.reason()).isEqualTo("logout"); verify(screenBufferService, never()).clear(22L, 1L, 123L); GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); @@ -1119,16 +1120,28 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); + client.awaitMatching( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "VIEW"), + "fresh current view"); secondPayloads = client.responses(); } assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "LOGIN")); assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "PLAY")); assertThat(secondPayloads) - .anyMatch( + .noneMatch( payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) + ("transcript_chunk".equals(json(payload).path("eventType").asText()) + || "transcript_entry".equals(json(payload).path("eventType").asText())) && payload.contains("First-party replay")); + assertThat(secondPayloads) + .anyMatch( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "VIEW")); + verify(screenBufferService, never()).get(22L, 1L, 123L); } @Test @@ -1603,8 +1616,7 @@ private URI websocketUri() { private void performLogoutFlow(String sessionId) throws Exception { try (GameplayWebSocketDriver client = openAdmittedGameplayDriver(sessionId)) { client.send("LOGOUT"); - GameplayWebSocketDriver.CloseEvent closeEvent = client.awaitClosed(); - assertThat(closeEvent.reason()).isEqualTo("logout"); + client.awaitContains("LOGOUT_UNAVAILABLE"); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index df8f96fa42..2eef310f14 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -38,14 +38,17 @@ void visibleWorldsDropsWorldSlugSharedAcrossTenants() { .thenReturn( List.of( pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), - pointer("DEMO", "Other Demo", "preview", "Preview Realm", 2L, 21L, 8L), - pointer("other", "Other World", "production", "Other Live", 2L, 22L, 9L))); + pointer("DEMO", "Other Demo", "production", "Other Live", 2L, 21L, 8L), + pointer("other", "Other World", "production", "Other Live", 1L, 22L, 9L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); assertThat(catalog.visibleWorlds()) .extracting(GameplayWorldCatalog.WorldView::slug) .containsExactly("other"); assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.publicProductionRealmCardinality(1L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); + assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java index 12a473f5d8..8abe810ecd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java @@ -1,370 +1,130 @@ package net.firedevops.firemud.gamesession.command.text; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.Optional; -import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; -import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; -import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; -import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; +import net.firedevops.firemud.gamesession.presentation.PlayerOutputKind; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class LogoutCommandHandlerTest { - private final SessionAuthenticationService sessionAuthenticationService = - Mockito.mock(SessionAuthenticationService.class); private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); - private final GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); - private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService = - Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry = - Mockito.mock(FirstPartyConnectContextRegistry.class); - private final ScriptEventPublisher scriptEventPublisher = - Mockito.mock(ScriptEventPublisher.class); - - private final LogoutCommandHandler handler = - new LogoutCommandHandler( - sessionAuthenticationService, - sessionContextService, - gameInstanceService, - gameplayAdmissionPointerAuthorityService, - gameplayPresenceLifecycleService, - firstPartyConnectContextRegistry, - scriptEventPublisher, - DirectTextConnectScopeSessionStore.inMemoryForTest()); - - @Test - void logoutPreservesDurableReplayContextWithoutStoppingSharedRuntime() { - SessionContext context = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 1L, - "R-1021", - "jwt", - "en-NZ", - 1L, - "demo", - "production", - 1L, - "SHARED"); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("quit")); - - assertThat(result.commandResult().accepted()).isTrue(); - assertThat(result.outputs()).hasSize(1); - verify(scriptEventPublisher) - .publishCommandEvent(context, command("logout-command:41:1:123", "LOGOUT", "quit")); - verify(scriptEventPublisher, never()) - .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); - verify(gameplayPresenceLifecycleService) - .recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); - verify(firstPartyConnectContextRegistry).unregister(41L); - verify(sessionContextService).deleteBySessionId(22L, 41L); - verifyNoMoreInteractions(gameplayPresenceLifecycleService); - } - - @Test - void logoutStopsIsolatedRuntime() { - SessionContext context = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - "demo", - "private", - 1L, - "ISOLATED"); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); - - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService).stopSession(7L); - } + private final LogoutCommandHandler handler = new LogoutCommandHandler(sessionContextService); @Test - void logoutDoesNotStopSharedRuntimeWhenCurrentRuntimeAuthorityIsShared() { - SessionContext context = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 1L, - "R-1021", - "jwt", - "en-NZ", - 1L, - "demo", - "production", - 1L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) - .thenReturn( - java.util.List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "production", - "Production", - 22L, - 1L, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + void authenticatedSharedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { + SessionContext context = context(41L, 123L, 1L, "SHARED"); + when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(context)); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertUnavailable(result); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopSharedRuntimeWhenNormalizationClearsProjectedBinding() { - SessionContext normalizedContext = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 1L, - "R-1021", - "jwt", - "en-NZ", - 1L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")) - .thenReturn(Optional.of(normalizedContext)); + void authenticatedIsolatedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { + SessionContext context = context(41L, 123L, 7L, "ISOLATED"); + when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(context)); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertUnavailable(result); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopRuntimeWhenPointerAuthorityIsUnknown() { - SessionContext context = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn(java.util.List.of()); + void unauthenticatedContextStillReturnsNotLoggedInWithoutMutation() { + when(sessionContextService.findBySessionId(41L)) + .thenReturn(Optional.of(context(41L, 0L, 1L, "SHARED"))); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + assertThat(result.commandResult().errorMessage()).isEqualTo("You are not logged in."); + assertThat(result.outputs()).singleElement().satisfies(output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); + assertThat(output.text()).isEqualTo("ERROR NOT_LOGGED_IN You are not logged in."); + }); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopRuntimeWhenCurrentRuntimeAuthorityIsAmbiguous() { - SessionContext context = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn( - java.util.List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "production", - "Production", - 22L, - 7L, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"), - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "private", - "Private", - 22L, - 7L, - 2L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + void missingSessionStillReturnsNotLoggedIn() { + when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.empty()); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopRuntimeWhenSingularRuntimeAuthorityIsIncomplete() { - SessionContext context = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn( - java.util.List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "production", - "Production", - 22L, - 7L, - 1L, - true, - true, - false, - "", - "ALLOW_NEW"))); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + void invalidSessionIdReturnsNotLoggedInWithoutLookingUpOrMutatingContext() { + LogoutCommandHandlingResult result = handler.handle("not-a-session", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutSkipsGameplayCleanupForPartialGameplayShell() { - SessionContext partial = - new SessionContext( - 41L, - 22L, - 123L, - "demo@example.com", - 123L, - "demo", - 0L, - null, - "jwt", - "en-NZ", - 1L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(partial)); + void unavailableSessionAuthorityReturnsRetryableFailure() { + when(sessionContextService.findBySessionId(41L)) + .thenThrow(new IllegalStateException("session store unavailable")); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); - verify(gameplayPresenceLifecycleService) - .recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertUnavailable(result); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } - @Test - void logoutBeforeLoginReturnsBoundedFailure() { - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.empty()); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); - + private static void assertUnavailable(LogoutCommandHandlingResult result) { assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); - verify(scriptEventPublisher, never()) - .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); - verify(sessionContextService, never()).deleteBySessionId(Mockito.anyLong(), Mockito.anyLong()); + assertThat(result.commandResult().errorCode()).isEqualTo("LOGOUT_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Logout is temporarily unavailable. Please try again."); + assertThat(result.outputs()).singleElement().satisfies(output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); + assertThat(output.text()) + .isEqualTo("ERROR LOGOUT_UNAVAILABLE Logout is temporarily unavailable. Please try again."); + }); } - private static TextCommand logoutCommand(String rawLine) { - return new TextCommand(TextCommandType.LOGOUT, java.util.List.of(), rawLine); + private static TextCommand logoutCommand() { + return new TextCommand(TextCommandType.LOGOUT, java.util.List.of(), "LOGOUT"); } - private static net.firedevops.firemud.gamesession.entity.GameplayCommand command( - String commandId, String commandName, String commandText) { - net.firedevops.firemud.gamesession.entity.GameplayCommand gameplayCommand = - new net.firedevops.firemud.gamesession.entity.GameplayCommand(); - gameplayCommand.setCommandId(commandId); - gameplayCommand.setCommandName(commandName); - gameplayCommand.setCommandText(commandText); - return gameplayCommand; + private static SessionContext context( + long sessionId, long accountId, long gameInstanceId, String scope) { + return new SessionContext( + sessionId, + 22L, + accountId, + "demo@example.com", + 123L, + "demo", + gameInstanceId, + "R-1021", + "jwt", + "en-NZ", + gameInstanceId, + "demo", + scope.equals("ISOLATED") ? "private" : "production", + 1L, + scope); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 5b62578eb7..900ae6cdcf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -303,15 +303,7 @@ void setUp() { commandService, lookHandler, loginHandler, - new LogoutCommandHandler( - sessionAuthenticationService, - sessionContextService, - gameInstanceService, - pointerAuthorityService, - gameplayPresenceLifecycleService, - firstPartyConnectContextRegistry, - scriptEventPublisher, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + new LogoutCommandHandler(sessionContextService), playHandler, moveHandler, afkHandler, @@ -423,44 +415,55 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { } @Test - void logoutClearsSessionSoLaterLoginStartsFreshWithoutResumeOrTakeover() { + void logoutFailsClosedWithoutChangingSessionOrPresence() { TextCommandInterpretationResult firstLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); assertTrue(firstLogin.commandResult().accepted()); TextCommandInterpretationResult firstPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertTrue(firstPlay.commandResult().accepted()); + Mockito.clearInvocations(scriptEventPublisher); TextCommandInterpretationResult logout = interpreter.interpret("1", "LOGOUT", false); - assertTrue(logout.commandResult().accepted()); - assertTrue(sessionContextService.findByTenantAndSessionId(22L, 1L).isEmpty()); - verify(accountRecentPresenceService) + assertFalse(logout.commandResult().accepted()); + assertEquals("LOGOUT_UNAVAILABLE", logout.commandResult().errorCode()); + assertEquals( + "Logout is temporarily unavailable. Please try again.", + logout.commandResult().errorMessage()); + assertTrue(sessionContextService.findByTenantAndSessionId(22L, 1L).isPresent()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(presence -> presence.sessionId() == 1L)); + Mockito.verify(accountRecentPresenceService, Mockito.never()) .recordDisconnect(1L, AccountRecentPresenceDisposition.LOGOUT); - verify(scriptEventPublisher) + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishCommandEvent(Mockito.any(), Mockito.any()); + Mockito.verify(scriptEventPublisher, Mockito.never()) .publishRegionExitEvent( - Mockito.argThat( - context -> - context.sessionId() == 1L - && context.gameInstanceId() == 1L - && context.characterId() == 77L - && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("logout:1:1:77"), - Mockito.eq("LOGOUT")); - - TextCommandInterpretationResult secondLogin = interpreter.interpret("2", LOGIN_PAYLOAD, false); - assertTrue(secondLogin.commandResult().accepted()); - TextCommandInterpretationResult secondPlay = interpreter.interpret("2", PLAY_PAYLOAD, false); - assertTrue(secondPlay.commandResult().accepted()); + Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(firstPartyConnectContextRegistry, Mockito.never()).unregister(1L); + Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); + } - TextCommandInterpretationResult firstLookAfterLogout = - interpreter.interpret("1", LOOK_PAYLOAD, false); - assertFalse(firstLookAfterLogout.commandResult().accepted()); - assertEquals("LOGIN_REQUIRED", firstLookAfterLogout.commandResult().errorCode()); + @Test + void logoutAliasesDoNotNormalizeStaleBindingBeforeFailingClosed() { + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + SessionContext before = sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow(); + when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 2L))); - assertTrue(sessionContextService.findByTenantAndSessionId(22L, 2L).isPresent()); - assertTrue( - gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() - .allMatch(presence -> presence.sessionId() != 1L)); - assertEquals(0.0, meterRegistry.counter("gamesession.session.takeover").count()); - assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); + for (String alias : List.of("LOGOUT", "LOGOFF", "QUIT")) { + TextCommandInterpretationResult result = interpreter.interpret("1", alias, false); + assertFalse(result.commandResult().accepted()); + assertEquals("LOGOUT_UNAVAILABLE", result.commandResult().errorCode()); + assertEquals(before, sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(presence -> presence.sessionId() == 1L)); + } + Mockito.verify(accountRecentPresenceService, Mockito.never()) + .recordDisconnect(1L, AccountRecentPresenceDisposition.LOGOUT); + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index a0d7e75db1..e8ae6b0dcd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -485,15 +485,7 @@ void setUp() { commandService, lookHandler, loginHandler, - new LogoutCommandHandler( - sessionAuthenticationService, - sessionContextService, - gameInstanceService, - pointerAuthorityService, - gameplayPresenceLifecycleService, - firstPartyConnectContextRegistry, - scriptEventPublisher, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + new LogoutCommandHandler(sessionContextService), playHandler, moveHandler, afkHandler, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 44b3d707b6..3aefb0cdfe 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -22,6 +22,8 @@ import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.shared.v1.ErrorDetail; @@ -1371,6 +1373,57 @@ void authenticatedBrowseFailsClosedWhenPublicProductionRealmIsDuplicatedAcrossWo Mockito.verifyNoInteractions(accountClient); } + @Test + void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + List initialPointers = + List.of(authorityPointer("demo", "production", 22L, 1L, true)); + AtomicReference> pointerSnapshot = + new AtomicReference<>(initialPointers); + Mockito.when(authorityService.listPointers()).thenAnswer(invocation -> pointerSnapshot.get()); + + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-a") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + + pointerSnapshot.set( + List.of( + authorityPointer("demo", "production", 22L, 1L, true), + authorityPointer("DEMO", "production", 33L, 2L, true), + authorityPointer("other", "production", 22L, 3L, true))); + + assertThat(catalog.publicProductionRealmCardinality(22L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); + assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); + Mockito.clearInvocations(accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "other")) + .isEqualTo( + WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo( + WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); + Mockito.verifyNoInteractions(entityManagementClient); + } + private WorldsCommandHandler authenticatedHandler( GameplayCatalogProperties properties, AccountClient accountClient) { return new WorldsCommandHandler( @@ -1380,6 +1433,30 @@ private WorldsCommandHandler authenticatedHandler( DirectTextConnectScopeSessionStore.inMemoryForTest()); } + private GameplayAdmissionPointerSnapshot authorityPointer( + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + boolean publicProduction) { + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldSlug, + realmSlug, + realmSlug, + tenantId, + gameInstanceId, + 1L, + true, + publicProduction, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + } + private GameplayCatalogProperties publicProductionProperties() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("demo", 22L, 1L, false))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 7e80a90e65..b95a3d2da9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -351,6 +351,10 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .build()); when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("ENTITLEMENT_UNAVAILABLE") + .build(), JoinPublicProductionMembershipResponse.newBuilder() .setSuccess(false) .setOutcomeCode("AUTH_UNAVAILABLE") @@ -383,10 +387,26 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), false, Optional.of(context))); + TextCommandInterpretationResult finalJoinResult = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); assertThat(realmsResult.commandResult().accepted()).isTrue(); assertThat(firstJoinResult.commandResult().accepted()).isFalse(); - assertThat(retryJoinResult.commandResult().accepted()).isTrue(); + assertThat(firstJoinResult.commandResult().errorCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(firstJoinResult.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isEqualTo( + new net.firedevops.firemud.gamesession.presentation.ErrorOutput( + "ENTITLEMENT_UNAVAILABLE", + "Join policy could not be checked. Retry the same JOIN while its realm scope is valid.")); + assertThat(retryJoinResult.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(finalJoinResult.commandResult().accepted()).isTrue(); assertThat(realmsResult.outputs()) .singleElement() .extracting(output -> output.payload()) @@ -413,7 +433,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { org.mockito.ArgumentCaptor.forClass(String.class); org.mockito.ArgumentCaptor requestIdCaptor = org.mockito.ArgumentCaptor.forClass(String.class); - Mockito.verify(accountClient, Mockito.times(2)) + Mockito.verify(accountClient, Mockito.times(3)) .joinPublicProductionMembership( joinContextCaptor.capture(), scopeIdCaptor.capture(), requestIdCaptor.capture()); List joinContexts = @@ -423,7 +443,9 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { assertThat(scopeIds.getFirst()).isEqualTo("opaque-account-scope"); assertThat(requestIds.getFirst()).isNotBlank(); assertThat(requestIds.getLast()).isEqualTo(requestIds.getFirst()); + assertThat(requestIds.get(1)).isEqualTo(requestIds.getFirst()); assertThat(scopeIds.getLast()).isEqualTo(scopeIds.getFirst()); + assertThat(scopeIds.get(1)).isEqualTo(scopeIds.getFirst()); assertThat(joinContexts.getFirst().getRequestId()).isEqualTo(requestIds.getFirst()); assertThat(joinContexts.getFirst().getAccountId()).isEqualTo("41"); assertThat(joinContexts.getFirst().getSessionId()).isEqualTo("7"); diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index f50c6ddd3a..496d6abdef 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -395,7 +395,7 @@ void telnetItemAndEquipmentLoopMatchesWebSocketCommandSurface() throws Exception } @Test - void telnetItemLoopStillSucceedsAfterWebSocketLogoutOnSharedRuntime() throws Exception { + void telnetItemLoopStillSucceedsAfterRejectedWebSocketLogoutOnSharedRuntime() throws Exception { ensureTestServicesStarted(); try (GameplayWebSocketDriver webSocketClient = openReadyGatewayWebSocketClient("gateway-1")) { @@ -453,9 +453,9 @@ void telnetItemLoopStillSucceedsAfterWebSocketLogoutOnSharedRuntime() throws Exc webSocketClient.send("LOGOUT"); assertThat( webSocketClient.awaitResponseMatching( - response -> response.contains("OK LOGOUT") && response.contains("Logged out."), - "logout response")) - .contains("OK LOGOUT"); + response -> response.contains("LOGOUT_UNAVAILABLE"), + "fail-closed logout response")) + .contains("LOGOUT_UNAVAILABLE"); } try (GameplayTelnetDriver telnetClient = openReadyTelnetClient()) { From 5d656a1a25953add47b97f02b0ec5c1ae7aa8e42 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:23:52 +1300 Subject: [PATCH 011/105] Remove unreachable logout close and retained replay delivery --- .../GameSessionWebSocketHandler.java | 41 ------------------- 1 file changed, 41 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index d2f878fe15..d52163ecad 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -251,7 +251,6 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) effectivePresentation); maybeRenderFreshReconnectLook( session, sessionId, command, interpretation, maybeContext); - maybeCloseAfterSuccessfulLogout(session, command, interpretation); } } @@ -414,15 +413,6 @@ private void sendProtocolMessage(WebSocketSession session, String text) throws I deliverySession.sendMessage(new TextMessage(text)); } - private void maybeCloseAfterSuccessfulLogout( - WebSocketSession session, TextCommand command, TextCommandInterpretationResult interpretation) - throws IOException { - if (command.type() != TextCommandType.LOGOUT || !interpretation.commandResult().accepted()) { - return; - } - session.close(new CloseStatus(CloseStatus.NORMAL.getCode(), "logout")); - } - private boolean shouldCloseAfterFirstPartyScopeRejection( WebSocketSession session, TextCommand command, @@ -522,37 +512,6 @@ private void maybeRenderFreshReconnectLook( }); } - private void sendReplayChunk(WebSocketSession session, String text, String label) { - try (CombinedLoggingContext ignored = openLoggingContext(session)) { - try { - sendProtocolMessage(session, outputProjector.projectTranscriptChunk(session, label, text)); - } catch (IOException ex) { - logger.warn("Failed to send reconnect {}", label, ex); - } - } - } - - private void sendReplayEntries( - WebSocketSession session, ScreenBufferService.BufferedScreen buffer, String label) { - if (!outputProjector.isFirstPartyWeb(session) - || buffer.entries().stream() - .noneMatch(ScreenBufferService.BufferedEntry::hasStructuredOutput)) { - sendReplayChunk(session, buffer.protocolText(), label); - return; - } - for (ScreenBufferService.BufferedEntry entry : buffer.entries()) { - try (CombinedLoggingContext ignored = openLoggingContext(session)) { - try { - sendProtocolMessage( - session, outputProjector.projectTranscriptEntry(session, label, entry)); - } catch (IOException ex) { - logger.warn("Failed to send reconnect {}", label, ex); - return; - } - } - } - } - private void sendProjectedOutput( WebSocketSession session, PlayerOutput output, From 2f1dc82652eeb749d105662bb5e70f20f7c7b08f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:40:05 +1300 Subject: [PATCH 012/105] Align player-stage checks after CAS reconciliation --- .../command/text/GameplayWorldCatalog.java | 22 +++++----------- .../command/text/TextCommandInterpreter.java | 6 ++--- .../GameSessionWebSocketHandler.java | 3 +-- ...essionWebSocketHandlerIntegrationTest.java | 1 - .../text/LogoutCommandHandlerTest.java | 25 ++++++++++++------- .../text/SessionResumptionFlowTest.java | 3 +-- .../text/WorldsCommandHandlerTest.java | 3 +-- .../PublicInternalRouteBlockFilterTest.java | 3 ++- 8 files changed, 29 insertions(+), 37 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 5840007ede..e8c6fdc7f8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -235,10 +235,7 @@ public Optional resolveWorld(String selector) { List catalogWorlds = catalogState.worlds(); List visibleWorlds = catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); - return resolveWorld( - selector, - visibleWorlds, - discoverableWorlds(visibleWorlds, catalogState)); + return resolveWorld(selector, visibleWorlds, discoverableWorlds(visibleWorlds, catalogState)); } public Optional resolveWorldFromAuthoritySnapshot(String selector) { @@ -516,8 +513,7 @@ public boolean hasValidPublicProductionRealm(DiscoverySnapshot snapshot, WorldVi .map(RealmView::tenantId) .distinct() .allMatch( - tenantId -> - snapshot.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L); + tenantId -> snapshot.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L); } public boolean requiresExplicitRealmSelection(WorldView world) { @@ -583,9 +579,7 @@ public List visibleRealms(WorldView world) { } public List visibleWorlds() { - return readCatalogState().worlds().stream() - .filter(this::hasVisibleRealmEntries) - .toList(); + return readCatalogState().worlds().stream().filter(this::hasVisibleRealmEntries).toList(); } /** @@ -673,10 +667,6 @@ private List worldEntries() { return List.copyOf(entries); } - private List discoverableWorlds() { - return discoverableWorlds(readCatalogState()); - } - private List discoverableWorlds(CatalogState catalogState) { List catalogWorlds = catalogState.worlds(); List visibleWorlds = @@ -695,7 +685,8 @@ private boolean hasPublicDiscoveryRealm(WorldView world, CatalogState catalogSta List publicProductionRealms = visibleRealms(world).stream().filter(RealmView::publicProductionRealm).toList(); return publicProductionRealms.size() == 1 - && hasValidPublicProductionRealm(catalogState, publicProductionRealms.getFirst().tenantId()); + && hasValidPublicProductionRealm( + catalogState, publicProductionRealms.getFirst().tenantId()); } private List realmEntries(WorldView world) { @@ -729,8 +720,7 @@ private boolean isPlayerAddressable(RealmView realm) { } private boolean hasValidPublicProductionRealm(CatalogState catalogState, long tenantId) { - return tenantId > 0L - && catalogState.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L; + return tenantId > 0L && catalogState.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L; } private CatalogState readCatalogState() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java index 21a2240dd6..60f2cb4e39 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java @@ -275,13 +275,11 @@ private TextCommandInterpretationResult interpretLogoutWithoutNormalization( .findDefinition(command.commandId()) .orElseGet( () -> - TextCommandDefinition.extensionDefinition( - command.type(), command.commandId())); + TextCommandDefinition.extensionDefinition(command.type(), command.commandId())); TextCommandInterpretationResult result = dispatcher.dispatch( TextCommandDispatchGroup.SESSION, - new TextCommandDispatchRequest( - sessionId, command, requiresSoloTick, Optional.empty())); + new TextCommandDispatchRequest(sessionId, command, requiresSoloTick, Optional.empty())); return withResolvedCommand(result, command, definition); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index d52163ecad..f53246bcbf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -249,8 +249,7 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) outputs, resolveLocaleTag(session, sessionId), effectivePresentation); - maybeRenderFreshReconnectLook( - session, sessionId, command, interpretation, maybeContext); + maybeRenderFreshReconnectLook(session, sessionId, command, interpretation, maybeContext); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 53a1889ace..540c2977ab 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -74,7 +74,6 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketHttpHeaders; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java index 8abe810ecd..8a629b6b61 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java @@ -51,10 +51,13 @@ void unauthenticatedContextStillReturnsNotLoggedInWithoutMutation() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); assertThat(result.commandResult().errorMessage()).isEqualTo("You are not logged in."); - assertThat(result.outputs()).singleElement().satisfies(output -> { - assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); - assertThat(output.text()).isEqualTo("ERROR NOT_LOGGED_IN You are not logged in."); - }); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); + assertThat(output.text()).isEqualTo("ERROR NOT_LOGGED_IN You are not logged in."); + }); verify(sessionContextService).findBySessionId(41L); verifyNoMoreInteractions(sessionContextService); } @@ -97,11 +100,15 @@ private static void assertUnavailable(LogoutCommandHandlingResult result) { assertThat(result.commandResult().errorCode()).isEqualTo("LOGOUT_UNAVAILABLE"); assertThat(result.commandResult().errorMessage()) .isEqualTo("Logout is temporarily unavailable. Please try again."); - assertThat(result.outputs()).singleElement().satisfies(output -> { - assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); - assertThat(output.text()) - .isEqualTo("ERROR LOGOUT_UNAVAILABLE Logout is temporarily unavailable. Please try again."); - }); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); + assertThat(output.text()) + .isEqualTo( + "ERROR LOGOUT_UNAVAILABLE Logout is temporarily unavailable. Please try again."); + }); } private static TextCommand logoutCommand() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 900ae6cdcf..49754f637e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -437,8 +437,7 @@ void logoutFailsClosedWithoutChangingSessionOrPresence() { Mockito.verify(scriptEventPublisher, Mockito.never()) .publishCommandEvent(Mockito.any(), Mockito.any()); Mockito.verify(scriptEventPublisher, Mockito.never()) - .publishRegionExitEvent( - Mockito.any(), Mockito.anyString(), Mockito.anyString()); + .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); Mockito.verify(firstPartyConnectContextRegistry, Mockito.never()).unregister(1L); Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 3aefb0cdfe..c8d7f88288 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1413,8 +1413,7 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "other")) - .isEqualTo( - WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java index 8b2911c920..1bad11ccc0 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java @@ -329,7 +329,8 @@ private WebFilterChain chain(AtomicBoolean chainCalled) { } private void assertBlockedPost(String path) { - MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post(path).build()); + MockServerWebExchange exchange = + MockServerWebExchange.from(MockServerHttpRequest.post(path).build()); AtomicBoolean chainCalled = new AtomicBoolean(false); filter.filter(exchange, chain(chainCalled)).block(); From cb8fb959bbdd5127b4e259f2112f9d34cfcb08f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:02:00 +1300 Subject: [PATCH 013/105] Fence stale discovery authority and document lobby reset --- .../game-session-service/runtime-and-data.md | 2 + ...m-architecture-redis-reset-and-recovery.md | 1 + .../command/text/WorldsCommandHandler.java | 22 +--- .../text/SessionResumptionFlowTest.java | 4 +- .../text/TextCommandInterpreterTest.java | 2 +- .../text/WorldsCommandHandlerTest.java | 102 +++++++++++++++++- .../WorldsTextCommandDispatchHandlerTest.java | 8 +- ...irectTextConnectScopeSessionStoreTest.java | 27 +++++ 8 files changed, 140 insertions(+), 28 deletions(-) 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 d6cb5b132e..eba8a29cad 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -143,6 +143,8 @@ Unauthenticated `sessionctx:*` entries may exist before `LOGIN`; they are bootst Game Session owns the live `sessionctx:*` family and applies only its local reset consequence: reset invalidates or rebuilds this bootstrap/lookup context and never preserves it. The canonical reset lifecycle and session-policy choice remain in [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model). Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections; Game Session does not reset or repair them, and gameplay session policy does not change their Account-owned behavior. +The direct-text lobby additionally uses the current `gamesession:lobby:` Redis family for short-lived world/realm snapshots, Account-issued scopes, and stable JOIN request IDs. Game Session owns it as non-preservable pre-auth context: any affected reset must invalidate and read back the exact keys before a new JOIN may rely on that transport session. The key is not tenant- or region-tagged, so a scoped reset cannot infer the affected set from its name; it requires authoritative session inventory or conservative full-family invalidation. The local store implements exact-key `clearSession` and focused tests check its readback; live Redis execution, the canonical reset executor, and scoped readback remain separate gates. This family is not session-preservation authority or a reason to bypass the current fail-closed operator fallback. + Target-state Game Session maintains the bounded active-binding index families owned by [Session Behavior](../../system-architecture-session-behavior.md#session-and-identity-management). The local Redis key shapes are: - `session:game:index:character:{tenantGameplayTag}::` -> `{sessionId, gameInstanceId, bindingGeneration}`; `playableStateScope` is binding evidence and is not part of the controller-uniqueness index key. diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index d6f50986e5..3dc08ecc43 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -238,6 +238,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Coordination | **Reset-sensitive with mandatory issuer-coverage rebuild** | Issuer cutoff and issuer-wide lookup remain fenced until the complete owner-defined issuer recovery result qualifies; region and tenant resets never flush a whole issuer partition. | Global per issuer across tenants and partitioned by the immutable issuer layout, not tenant-tagged. The inventory, capacity, acknowledgement, and coverage contract is owned by the linked Game Session evidence documents. | | `session:game:{tenantGameplayTag}::` | Coordination | **Reset-sensitive** | Region and tenant resets retain or invalidate this record only under their explicit session policy. Cluster scope requires `--invalidate-sessions`; preserved-session rebind is not a cluster option. | Authoritative for connection identity and reconnect/session CAS state, but not a substitute for the owner-defined rebind/admission contract. | | `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | +| `gamesession:lobby:` | Coordination (current direct-text lobby context) | **Reset-sensitive, not preservable** | A region, tenant, or cluster reset must invalidate every affected lobby record, including Account-issued connect scopes and bound JOIN request IDs, and read back their absence before admitting a fresh direct-text JOIN. Because the current key has no tenant or region component, a scoped reset needs authoritative affected-session inventory or conservative full-family invalidation; the key name alone cannot prove scope. | Game Session owns this expiring Redis family. Its local `clearSession` deletes one exact transport key and readers require matching session/account identity and expiry, but target reset execution and affected-scope readback remain unimplemented. Current operators follow the fail-closed fallback rather than deleting keys ad hoc or claiming reset convergence. | | `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | These current live-presence value/index families are unavailable when missing, partial, stale, or ambiguous; `WHO` and account-presence reads must fail private-by-failure rather than expose stale or cross-scope presence. Game Session must fence the affected scope, rebuild an exact-scoped owner projection, and complete exact readback before presence is exposed again. | The current writer uses untagged keys and separate value/set mutations; it is implementation drift, not target authority. The target must choose and prove the Redis role, exact scope, atomic owner mutation, reset inventory, and readback contract. | | `accountrecentpresence::` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | Loss, partial state, stale state, or ambiguous routing evidence makes recent/offline presence unavailable/private; it must not be presented as a verified location or routing fact. Game Session must fence or suppress the affected projection and rebuild/read back the exact target owner projection before exposing it. | The current account recent-presence record is a direct untagged value with an implementation TTL; its storage role, exact retention, reset behavior, and owner readback are unproved. It remains a disposable current shape, not durable authority or target cache semantics. | | `gamesession:notifydisconnect:dedup:` | **Coordination (current legacy drift; target sequencing contract unproved)** | **Reset-sensitive, fail-closed until the target contract is proven** | Dropping or losing the latest sequence must not permit an old duplicate `NotifyDisconnect` to remove presence, emit region exit, or suspend runtime state. Until exact connection/generation binding and durable sequencing are proven, the affected scope remains fenced and Redis loss/error cannot authorize fail-open stale effects. | Game Session owns the current sequence-dedup writer; the current one-hour key and Redis failure behavior are implementation drift. The target owner contract must define durable sequencing, binding validation before side effects, reset inventory, and exact readback. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index eebfd4e616..09a7144bcb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -447,10 +447,10 @@ private boolean isValidEntitlement( return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) && response.getEntitlementVersion() > 0L && response.getTenantBillingSequence() > 0L - && isFreshEntitlementEvaluation(response.getEvaluatedAt()); + && isFreshAuthorityEvaluation(response.getEvaluatedAt()); } - private boolean isFreshEntitlementEvaluation(String evaluatedAt) { + private boolean isFreshAuthorityEvaluation(String evaluatedAt) { if (!StringUtils.hasText(evaluatedAt)) { return false; } @@ -483,7 +483,7 @@ && hasMatchingAuthorityIdentity( response.getTenantId(), sessionContext.accountId(), realm.tenantId()) - && isInstant(response.getEvaluatedAt()); + && isFreshAuthorityEvaluation(response.getEvaluatedAt()); } private boolean isValidGrant( @@ -499,7 +499,7 @@ && hasMatchingAuthorityIdentity( realm.tenantId()) && world.slug().equals(response.getWorldSlug()) && realm.slug().equals(response.getRealmSlug()) - && isInstant(response.getEvaluatedAt()); + && isFreshAuthorityEvaluation(response.getEvaluatedAt()); } private boolean hasMatchingAuthorityIdentity( @@ -512,18 +512,6 @@ private boolean hasMatchingAuthorityIdentity( } } - private boolean isInstant(String value) { - if (!StringUtils.hasText(value)) { - return false; - } - try { - Instant.parse(value); - return true; - } catch (DateTimeParseException ex) { - return false; - } - } - private boolean isAuthorityUnavailable(String code) { return AuthenticationErrorCodes.UNAVAILABLE.equalsIgnoreCase(code) || "UNAVAILABLE".equalsIgnoreCase(code); @@ -892,7 +880,7 @@ private boolean isValidMembershipAuthoritySnapshot( response.getTenantId(), sessionContext.accountId(), realm.tenantId()) - || !isInstant(response.getEvaluatedAt())) { + || !isFreshAuthorityEvaluation(response.getEvaluatedAt())) { return false; } if (!response.getMembershipExists()) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 49754f637e..21808a89c3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -176,7 +176,7 @@ void setUp() { .setMembershipVersion(1L) .setMembershipLifecycleState("ACTIVE") .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -483,7 +483,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:01:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); TextCommandInterpretationResult secondLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index e8ae6b0dcd..1846046736 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -186,7 +186,7 @@ void setUp() { .setMembershipVersion(1L) .setMembershipLifecycleState("ACTIVE") .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index c8d7f88288..ebeb9fdc84 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -525,7 +525,7 @@ void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEnt .setMembershipVersion(0L) .setMembershipAuthorityGeneration(0L) .setMembershipLifecycleState("MISSING") - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); Mockito.when( accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) @@ -560,7 +560,7 @@ void browseCharactersReturnsUnavailableEntitlementBeforeReadingPublicEntityRoste .setMembershipVersion(0L) .setMembershipAuthorityGeneration(0L) .setMembershipLifecycleState("MISSING") - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); Mockito.when( accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) @@ -787,6 +787,93 @@ void browseCharactersRejectsIncompleteOrStaleEntitlementBeforeReadingRoster() { Mockito.verifyNoInteractions(entityManagementClient); } + @Test + void browseCharactersRejectsInvalidPublicMembershipBeforeReadingRoster() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + WorldsCommandHandler localHandler = + authenticatedHandler(publicProductionProperties(), accountClient); + + for (String evaluatedAt : invalidEvaluationTimes()) { + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership().toBuilder().setEvaluatedAt(evaluatedAt).build()); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + } + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void browseRealmsAndCharactersRejectInvalidPrivateMembership() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + for (String evaluatedAt : invalidEvaluationTimes()) { + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership().toBuilder().setEvaluatedAt(evaluatedAt).build()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + } + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + @Test + void browseRealmsAndCharactersRejectInvalidPrivateGrant() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + for (String evaluatedAt : invalidEvaluationTimes()) { + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(true).toBuilder().setEvaluatedAt(evaluatedAt).build()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + } + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(accountClient, Mockito.never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + } + @Test void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRoster() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -1510,7 +1597,7 @@ private GetTenantMembershipForRuntimeResponse publicMembership( .setMembershipVersion(membershipVersion) .setMembershipLifecycleState(lifecycleState) .setMembershipAuthorityGeneration(membershipAuthorityGeneration) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build(); } @@ -1537,7 +1624,7 @@ private GetRealmAccessGrantForRuntimeResponse grant(String worldSlug, boolean gr .setRealmSlug("production") .setGranted(granted) .setGrantVersion(granted ? 1L : 0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build(); } @@ -1566,6 +1653,13 @@ private void stubActivePrivateAuthorization(AccountClient accountClient, String .build()); } + private List invalidEvaluationTimes() { + return List.of( + Instant.now().minusSeconds(16).toString(), + Instant.now().plusSeconds(30).toString(), + "not-an-instant"); + } + private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index b95a3d2da9..b0091335ef 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -96,7 +96,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { .setMembershipVersion(1L) .setMembershipLifecycleState("ACTIVE") .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -112,7 +112,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { .setRealmSlug("production") .setGranted(true) .setGrantVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -178,7 +178,7 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .setMembershipVersion(1L) .setMembershipLifecycleState("ACTIVE") .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -258,7 +258,7 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( .setMembershipVersion(0L) .setMembershipAuthorityGeneration(0L) .setMembershipLifecycleState("MISSING") - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 2901800c48..432e82b3e7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -100,6 +100,33 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { assertThat(newAttempt.requestId()).isNotEqualTo(firstAttempt.requestId()); } + @Test + void clearingTransportLobbyRemovesScopeAndBoundJoinIdentityBeforeReuse() { + SessionContext caller = session(7L, 41L); + Instant now = Instant.now(); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of(scopedRealm(caller, "production", "old-scope", now.plusSeconds(600)))); + String oldRequestId = + store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow().requestId(); + + store.clearSession(caller.sessionId()); + + assertThat(store.publicProductionScopeForJoin(caller, "demo-world", now)).isEmpty(); + assertThat(store.publicProductionScope(caller, "demo-world", now)).isEmpty(); + store.replaceWorldScopes( + caller, + "demo-world", + "demo-world", + List.of(scopedRealm(caller, "production", "new-scope", now.plusSeconds(600)))); + DirectTextConnectScopeSessionStore.JoinScope newAttempt = + store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); + assertThat(newAttempt.scope().connectScopeId()).isEqualTo("new-scope"); + assertThat(newAttempt.requestId()).isNotEqualTo(oldRequestId); + } + @Test void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { SessionContext caller = session(41L, 7L); From 941f6af1993f312b13bb7601aa2f17407a804ee9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:23:21 +1300 Subject: [PATCH 014/105] Require fresh Account evidence for PLAY admission --- .../game-session-service/protocols.md | 6 +- ...ystem-architecture-player-command-model.md | 2 +- .../command/text/PlayCommandHandler.java | 92 ++++++++-- .../command/text/PlayCommandHandlerTest.java | 173 ++++++++++++++++-- .../text/SessionResumptionFlowTest.java | 2 + 5 files changed, 248 insertions(+), 27 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index ddf7a4ad3a..5577aee07c 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` may return `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the current `PLAY` consumer does not classify the latter specifically as `INACTIVE`, and direct-text clients can then issue `JOIN` without creating or restoring membership implicitly. Current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration` in the runtime membership response, but the current text `PLAY` consumer still decides from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; it does not yet consume the lifecycle or authority-generation fields, so an `ACTIVE` or `INACTIVE` classification remains target-only in `PLAY`. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`, while a well-formed fresh `MISSING` or non-admitting `INACTIVE` membership still maps to `JOIN_REQUIRED` for eligible public-production entry or `WORLD_ACCESS_DENIED` for non-public entry. Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. The membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. For logout and retained private semantic context, [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) owns the binding termination fence and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) owns namespace-scoped `resumeContextGeneration` and replay eligibility. Current player text handling rejects `LOGOUT` before side effects, and first-party private semantic transcript replay is gated when durable episode/binding termination proof is unavailable; fresh authoritative `LOOK` remains available. This fail-closed child behavior does not establish the durable successor protocol or complete either ADR. @@ -41,7 +41,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, direct-text `JOIN` is available through Account's explicit membership writer, while first-party `Join & Play` remains unavailable; Account exposes lifecycle and authority-generation fields, but `PLAY` still applies only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus existing grant checks and does not yet consume those new fields to classify `ACTIVE` or `INACTIVE`. An eligible public-production denial may return `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification, and direct-text clients can complete `JOIN`; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, direct-text `JOIN` is available through Account's explicit membership writer, while first-party `Join & Play` remains unavailable. `PLAY` requires fresh, identity-matched membership evidence with positive membership version and authority generation for an existing member; positive admission requires lifecycle `ACTIVE`. A well-formed fresh `MISSING` or non-admitting `INACTIVE` membership can still return `JOIN_REQUIRED` for eligible public-production entry or `WORLD_ACCESS_DENIED` for non-public entry. Positive grant and entitlement snapshots require their exact scope identifiers, positive versions and billing sequence, and evaluation time within 15 seconds and not in the future. Invalid positive evidence returns retryable authority or entitlement unavailable without changing the binding. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -116,7 +116,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current `PLAY` consumer still validates the four fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and does not consume the lifecycle or authority-generation fields to classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; direct-text clients can then use the implemented `JOIN`, while the latter case remains unclassified by `PLAY`. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` now validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; valid fresh missing or non-admitting membership maps to `JOIN_REQUIRED` for eligible public-production entry or `WORLD_ACCESS_DENIED` for non-public entry. Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. The membership-authority-generation reread and connect-token grant validation remain gaps. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. diff --git a/design/architecture/system-architecture-player-command-model.md b/design/architecture/system-architecture-player-command-model.md index e314715dc1..3ccf1b6d73 100644 --- a/design/architecture/system-architecture-player-command-model.md +++ b/design/architecture/system-architecture-player-command-model.md @@ -92,7 +92,7 @@ The standard catalog is grouped by command family. Detailed domain behavior rema | Family | Canonical commands | Stage | Availability | Semantic owner | | --- | --- | --- | --- | --- | | Session lifecycle | `LOGIN` (`LOGON` alias), `PLAY`, `LOGOUT` (`LOGOFF` and `QUIT` aliases) | `LOGIN` pre-login, `PLAY` lobby, `LOGOUT` any stage | Mandatory platform | Account Service and Game Session | -| Discovery and help | `WORLDS`; `REALMS`; `CHARS`; `HELP` | `WORLDS` and `HELP` any; `REALMS` and `CHARS` lobby or gameplay | Mandatory platform | Account Service, Game Session, and Game Design for authored help | +| Discovery and help | `WORLDS`; `REALMS`; `JOIN`; `CHARS`; `HELP` | `WORLDS` and `HELP` any; `REALMS`, `JOIN`, and `CHARS` lobby or gameplay | Mandatory platform | Account Service, Game Session, and Game Design for authored help | | Gameplay foundation | `LOOK` (`L`); `QUICKLOOK` (`QLOOK`); `MOVE` (`GO`, cardinal direction names, and `N`/`S`/`E`/`W`/`U`/`D`) | Gameplay | Mandatory for a tenant/game using the playable text-MUD profile | Game Logic, World Management, and Game Session rendering | | Platform utilities | `STATUS` (`STAT`); `AFK` (`BRB`) | Gameplay | Universal platform utilities | Game Session | | Social and presence | `SAY`, `WHISPER`, `TELL`, `WHO`, `FRIENDS` | Gameplay | Optional tenant/game capabilities | Game Logic, Social & Groups, and Game Session | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 68f0ef2f0b..cb70b2f125 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -851,6 +851,11 @@ private Optional validateMembershipResponse( worldAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } + if (!isValidGrant(grantResponse, context, selectedWorld, selectedRealm)) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } return Optional.empty(); } return Optional.empty(); @@ -905,6 +910,11 @@ private Optional validateEntitlementsResponse( tenantBillingBlockedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } + if (!isValidEntitlement(response, selectedRealm)) { + return Optional.of( + entitlementUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } if (!response.getGameplayAvailable()) { return Optional.of( tenantBillingBlockedFailure( @@ -1015,23 +1025,81 @@ private boolean isSafeMembershipAuthorityResponse( GetTenantMembershipForRuntimeResponse response, SessionContext context, GameplayWorldCatalog.RealmView selectedRealm) { - if (!StringUtils.hasText(response.getAccountId()) - || !StringUtils.hasText(response.getTenantId()) - || !StringUtils.hasText(response.getEvaluatedAt())) { + if (!hasMatchingAuthorityIdentity( + response.getAccountId(), + response.getTenantId(), + context.accountId(), + selectedRealm.tenantId()) + || !isFreshAuthorityEvaluation(response.getEvaluatedAt())) { + return false; + } + if (!response.getMembershipExists()) { + return "MISSING".equalsIgnoreCase(response.getMembershipLifecycleState()) + && !response.getGameplayAdmissionAllowed() + && response.getMembershipVersion() == 0L + && response.getMembershipAuthorityGeneration() == 0L; + } + if (response.getMembershipVersion() <= 0L + || response.getMembershipAuthorityGeneration() <= 0L) { + return false; + } + if (response.getGameplayAdmissionAllowed()) { + return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); + } + return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) + || "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); + } + + private boolean isValidGrant( + GetRealmAccessGrantForRuntimeResponse response, + SessionContext context, + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmView realm) { + return response.getGrantVersion() > 0L + && hasMatchingAuthorityIdentity( + response.getAccountId(), response.getTenantId(), context.accountId(), realm.tenantId()) + && world.slug().equals(response.getWorldSlug()) + && realm.slug().equals(response.getRealmSlug()) + && isFreshAuthorityEvaluation(response.getEvaluatedAt()); + } + + private boolean isValidEntitlement( + GetTenantEntitlementsForRuntimeResponse response, GameplayWorldCatalog.RealmView realm) { + return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) + && response.getEntitlementVersion() > 0L + && response.getTenantBillingSequence() > 0L + && isFreshAuthorityEvaluation(response.getEvaluatedAt()); + } + + private boolean isFreshAuthorityEvaluation(String evaluatedAt) { + if (!StringUtils.hasText(evaluatedAt)) { return false; } try { - Instant.parse(response.getEvaluatedAt()); - if (Long.parseLong(response.getAccountId()) != context.accountId() - || Long.parseLong(response.getTenantId()) != selectedRealm.tenantId()) { - return false; - } - } catch (DateTimeParseException | NumberFormatException ex) { + Instant evaluated = Instant.parse(evaluatedAt); + Instant now = Instant.now(); + return !evaluated.isAfter(now) && !evaluated.isBefore(now.minusSeconds(15)); + } catch (DateTimeParseException ex) { + return false; + } + } + + private boolean hasMatchingAuthorityIdentity( + String accountId, String tenantId, long expectedAccountId, long expectedTenantId) { + try { + return Long.parseLong(accountId) == expectedAccountId + && Long.parseLong(tenantId) == expectedTenantId; + } catch (NumberFormatException ex) { + return false; + } + } + + private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { + try { + return Long.parseLong(tenantId) == expectedTenantId; + } catch (NumberFormatException ex) { return false; } - return response.getMembershipExists() - ? response.getMembershipVersion() > 0L - : response.getMembershipVersion() == 0L; } private boolean maybeRecordFreshEntryFallback( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 662186ffdb..069c74471f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.util.List; import java.util.Optional; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -119,8 +120,10 @@ void setUp() { .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -129,7 +132,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(evaluatedAtNow()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -137,7 +140,13 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenAnswer( + invocation -> + validGrant( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3))); when(sessionRoutingNormalizationService.normalizeProjectedContext( Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -1140,8 +1149,10 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("INACTIVE") .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) .build()); PlayCommandHandlingResult result = @@ -1168,8 +1179,11 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) .build()); PlayCommandHandlingResult result = @@ -1203,7 +1217,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenReturn(validGrant()); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1357,9 +1371,11 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .setAccountId("123") .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) .build()); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1387,8 +1403,10 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("INACTIVE") .setMembershipVersion(4L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) .build()); PlayCommandHandlingResult result = @@ -1416,6 +1434,8 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt("not-a-timestamp") .build()); @@ -1434,6 +1454,116 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @ParameterizedTest + @ValueSource(strings = {"stale", "future", "wrong-account", "missing-generation"}) + void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + GetTenantMembershipForRuntimeResponse.Builder response = + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()); + switch (invalidEvidence) { + case "stale" -> response.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); + case "future" -> response.setEvaluatedAt(Instant.now().plusSeconds(1).toString()); + case "wrong-account" -> response.setAccountId("999"); + case "missing-generation" -> response.setMembershipAuthorityGeneration(0L); + default -> throw new IllegalArgumentException(invalidEvidence); + } + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(response.build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + + @ParameterizedTest + @ValueSource(strings = {"stale", "future", "wrong-tenant", "missing-version", "missing-sequence"}) + void playRejectsInvalidEntitlementAuthority(String invalidEvidence) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + GetTenantEntitlementsForRuntimeResponse.Builder response = + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()); + switch (invalidEvidence) { + case "stale" -> response.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); + case "future" -> response.setEvaluatedAt(Instant.now().plusSeconds(1).toString()); + case "wrong-tenant" -> response.setTenantId("23"); + case "missing-version" -> response.setEntitlementVersion(0L); + case "missing-sequence" -> response.setTenantBillingSequence(0L); + default -> throw new IllegalArgumentException(invalidEvidence); + } + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(response.build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + + @ParameterizedTest + @ValueSource(strings = {"stale", "future", "wrong-account", "wrong-realm"}) + void playRejectsInvalidPositiveGrantAuthority(String invalidEvidence) { + markPreviewRealmInvisible(); + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GetRealmAccessGrantForRuntimeResponse.Builder grant = + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setWorldSlug("sandbox") + .setRealmSlug("preview") + .setGranted(true) + .setGrantVersion(1L) + .setEvaluatedAt(evaluatedAtNow()); + switch (invalidEvidence) { + case "stale" -> grant.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); + case "future" -> grant.setEvaluatedAt(Instant.now().plusSeconds(1).toString()); + case "wrong-account" -> grant.setAccountId("999"); + case "wrong-realm" -> grant.setRealmSlug("production"); + default -> throw new IllegalArgumentException(invalidEvidence); + } + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant.build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = @@ -1446,7 +1576,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { .setGameplayAvailable(false) .setEntitlementVersion(5L) .setTenantBillingSequence(5L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(evaluatedAtNow()) .build()); PlayCommandHandlingResult result = @@ -1643,6 +1773,27 @@ private static String joinedOutputText(List outputs) { .orElse(null); } + private static String evaluatedAtNow() { + return Instant.now().toString(); + } + + private static GetRealmAccessGrantForRuntimeResponse validGrant() { + return validGrant("123", "22", "sandbox", "preview"); + } + + private static GetRealmAccessGrantForRuntimeResponse validGrant( + String accountId, String tenantId, String worldSlug, String realmSlug) { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(accountId) + .setTenantId(tenantId) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .setGranted(true) + .setGrantVersion(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build(); + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 21808a89c3..29f8713c4e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -482,7 +482,9 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("INACTIVE") .setMembershipVersion(2L) + .setMembershipAuthorityGeneration(1L) .setEvaluatedAt(Instant.now().toString()) .build()); From 721180eebdbeb12ffd62458e1ad00caea017c20e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:53:06 +1300 Subject: [PATCH 015/105] Gate public PLAY join guidance on fresh entitlement --- .../realm-routing-and-playable-state.md | 14 +-- .../text/GameplayStageCommandConstants.java | 2 +- .../command/text/PlayCommandHandler.java | 49 +++++++++ .../presentation-messages.properties | 3 +- .../presentation-messages_fr.properties | 3 +- .../command/text/PlayCommandHandlerTest.java | 100 ++++++++++++++++++ .../TextPlayerOutputRendererTest.java | 27 +++++ 7 files changed, 188 insertions(+), 10 deletions(-) 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 7be2a7c287..546a8ec6d4 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and stable slugs re-resolve against current catalog authority. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Full direct-text/Telnet end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, catalog and route revisions are combined, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. Account now exposes lifecycle-aware membership evidence (`membershipLifecycleState`, `membershipVersion`, and `membershipAuthorityGeneration`), and the explicit `JoinPublicProductionMembership` writer is implemented locally. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and stable slugs re-resolve against current catalog authority. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Game Session now invokes the Account writer from this retained scope, but full direct-text/Telnet and first-party `Join & Play` end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, separate stored catalog and pointer revisions have not converged through every consumer, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. ## Packet 4 Status and Proof Gaps @@ -21,7 +21,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The baseline unique index is still `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`, so cross-tenant duplicate selectors are not schema-safe. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Internal sequential expected-version and prepared-cutover seams exist but are nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, catalog revision separation, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Stored `catalogRevision` is separate from routing `pointerVersion`, and durable realm/namespace IDs exist, but older audit rows retain unknown revision/identity and some consumers lack the complete separated tuple. Internal sequential expected-version and prepared-cutover seams remain nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -35,7 +35,7 @@ These links add decision provenance only; they do not upgrade routing or playabl ### Authority and Pointer Contract -Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. It combines runtime target, visibility/public-production classification, display metadata, `stateScope`, character-selection requirements, and character-creation policy under one `pointerVersion`; the target separates catalog revision from runtime routing. +Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. It stores routing `pointerVersion` separately from `catalogRevision` for visibility/public-production classification, display metadata, `stateScope`, character-selection requirements, and character-creation policy; complete separation across consumers and retained audit history remains unproved. Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. Current pointer writes use a tenant-qualified slug lookup and may compare `expectedPointerVersion` after that read, but the repository then updates by row ID without a version predicate. This is not an atomic CAS under concurrent writers. The baseline migration also defines the unique pointer index as `(world_slug, realm_slug)` without `tenant_id`, so persistence has not converged with the target `{tenantId, realmId}` key. @@ -55,11 +55,11 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with four admission-evidence fields, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. Explicit `JOIN` / `Join & Play` remains unimplemented, and the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed; the canonical `JoinPublicProductionMembership` writer is implemented locally, including lifecycle-aware membership fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; `PLAY` admits only an exact safe active snapshot, while an eligible public-production request with missing or non-admitting membership may return non-actionable `JOIN_REQUIRED`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. Game Session's direct-text `JOIN` path now retrieves the retained REALMS scope/request state and invokes that Account writer; this local invocation and writer do not establish the complete first-party `Join & Play` or direct-text/Telnet flow. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. -The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; stable slug selection re-resolves current authority. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path and terminal-outcome recovery remain unproved. This is distinct from the browser/WebSocket bootstrap snapshot. +The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; stable slug selection re-resolves current authority. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, and terminal-outcome recovery remain unproved. This is distinct from the browser/WebSocket bootstrap snapshot. Gateway and Game Session preserve and validate `worldSlug`, `realmSlug`, `connectScopeId`, `connectRequestId`, `pointerVersion`, and resolved target in first-party connect context. The durable bootstrap shell stores the selector identity and is the reconnect/login/`PLAY` fallback when transient registry state is absent. Generic websocket bootstrap preserves an incoming complete bundle, repairs a runtime-only shell only from one complete current pointer, and collapses ambiguous or incomplete authority to no bundle. If a reused shell had a bundle and the repaired incoming shell does not, it is a real route change: the `BOOTSTRAP_ROUTE_CHANGED` path clears authenticated/gameplay state instead of preserving the older route. @@ -95,13 +95,13 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. +The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet end-to-end proved. The evidence records focused proof for the local Account JOIN writer and direct-text scope/request handoff in addition to sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove the full `WORLDS`, `REALMS`, `JOIN`, `CHARS`, and `PLAY` sequence, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, complete separated-revision consumer convergence, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. ## Active Gaps - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- Explicit `JOIN`/`Join & Play` remains unimplemented. Current connect-token issuance and `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and never create membership; an eligible public-production response with `membershipExists=false` may return `JOIN_REQUIRED`. For non-public membership, connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED`. An existing non-admitting response cannot be classified as `INACTIVE` because the live adapter does not expose lifecycle state. The target membership-authority-generation reread at issuance remains a gap. +- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Full end-to-end proof, PostgreSQL runtime proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index 516147c63f..687b6f5d98 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -23,7 +23,7 @@ public final class GameplayStageCommandConstants { "You are not allowed to enter that world."; public static final String JOIN_REQUIRED_CODE = "JOIN_REQUIRED"; public static final String JOIN_REQUIRED_MESSAGE = - "Membership is required before PLAY; joining this world is not available yet."; + "Membership is required before PLAY. Use JOIN ."; public static final String TENANT_BILLING_BLOCKED_CODE = "TENANT_BILLING_BLOCKED"; public static final String TENANT_BILLING_BLOCKED_MESSAGE = "That world is temporarily unavailable for gameplay."; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index cb70b2f125..b9e253b8e7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -55,6 +55,10 @@ public class PlayCommandHandler { private static final String RESUME_DENIED_METRIC = "gamesession.session.resume_denied"; private static final String FRESH_ENTRY_FALLBACK_METRIC = "gamesession.session.fresh_entry_fallback"; + private static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE = + "PUBLIC_PRODUCTION_ADMISSION_DENIED"; + private static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE = + "Public joining is not available for this world."; private final SessionAuthenticationService sessionAuthenticationService; private final SessionContextService sessionContextService; @@ -808,6 +812,25 @@ private Optional validateMembershipResponse( } if (!response.getMembershipExists() || !response.getGameplayAdmissionAllowed()) { if (isPublicProductionRealm(selectedRealm)) { + GetTenantEntitlementsForRuntimeResponse entitlementResponse = + accountClient.getTenantEntitlementsForRuntime( + Long.toString(selectedRealm.tenantId()), requestId); + Optional entitlementFailure = + validateEntitlementsResponse( + entitlementResponse, + context, + tenantTag, + selectedWorld, + selectedRealm, + requestedCharacterId); + if (entitlementFailure.isPresent()) { + return entitlementFailure; + } + if (!entitlementResponse.getAllowPublicJoin()) { + return Optional.of( + publicProductionAdmissionDeniedFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } recordResumeDeniedIfApplicable( context, selectedWorld.slug(), @@ -887,6 +910,32 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( null); } + private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId) { + recordResumeDeniedIfApplicable( + context, + selectedWorld.slug(), + selectedRealm.slug(), + selectedRealm.pointerVersion(), + selectedRealm.gameInstanceId(), + requestedCharacterId, + tenantTag, + "public_admission_denied"); + return failure( + PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE, + PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE, + "error.play.public-production-admission-denied", + Map.of(), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(requestedCharacterId), + null); + } + private Optional validateEntitlementsResponse( GetTenantEntitlementsForRuntimeResponse response, SessionContext context, diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index f076ab4f29..016d634978 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -20,7 +20,8 @@ error.play.character-selection-required=Selection required. Use {playUsage} or b error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. -error.play.join-required=Membership is required before PLAY; joining this world is not available yet. +error.play.join-required=Membership is required before PLAY. Use JOIN . +error.play.public-production-admission-denied=Public joining is not available for this world. error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. error.play.entitlement-unavailable=Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. error.play.billing-blocked=That world is temporarily unavailable for gameplay. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 0aa662b68b..d87355bdc4 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -20,7 +20,8 @@ error.play.character-selection-required=Selection requise. Utilisez {playUsage} error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. -error.play.join-required=Une adhésion est requise avant PLAY ; rejoindre ce monde n’est pas encore disponible. +error.play.join-required=Une adhésion est requise avant PLAY. Utilisez JOIN . +error.play.public-production-admission-denied=L’adhésion publique n’est pas disponible pour ce monde. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.entitlement-unavailable=L’autorité d’abonnement est temporairement indisponible. Réessayez PLAY sous peu. error.play.billing-blocked=Ce monde est temporairement indisponible pour le jeu. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 069c74471f..bdadbcee96 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1377,6 +1377,8 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(evaluatedAtNow()) .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1408,6 +1410,8 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .setMembershipAuthorityGeneration(1L) .setEvaluatedAt(evaluatedAtNow()) .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1420,6 +1424,90 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); } + @Test + void playPublicAdmissionDeniedWhenFreshEntitlementsDisallowJoin() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 0L, null, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Public joining is not available for this world."); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.public-production-admission-denied"); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + } + + @ParameterizedTest + @ValueSource(strings = {"outage", "malformed", "stale"}) + void playPublicJoinRequiresFreshEntitlementEvidence(String evidence) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 0L, null, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + GetTenantEntitlementsForRuntimeResponse entitlementResponse; + if ("outage".equals(evidence)) { + entitlementResponse = + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE) + .setMessage(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_MESSAGE)) + .build(); + } else { + GetTenantEntitlementsForRuntimeResponse.Builder builder = publicEntitlement(true).toBuilder(); + if ("malformed".equals(evidence)) { + builder.clearTenantId(); + } else { + builder.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); + } + entitlementResponse = builder.build(); + } + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(entitlementResponse); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + } + @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = @@ -1794,6 +1882,18 @@ private static GetRealmAccessGrantForRuntimeResponse validGrant( .build(); } + private static GetTenantEntitlementsForRuntimeResponse publicEntitlement( + boolean allowPublicJoin) { + return GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(allowPublicJoin) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build(); + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index bdae4a8cdc..23118f28bb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -862,6 +862,33 @@ void localizedErrorUsesConfiguredLocaleTemplate() { .isEqualTo("ERROR LOGIN_REQUIRED You must LOGIN first. Use LOGIN [secret]."); } + @Test + void publicJoinOutcomesRenderCurrentGuidanceAndPolicyDenial() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L))); + + assertThat( + renderer.render( + PlayerOutput.error( + "JOIN_REQUIRED", "fallback", "error.play.join-required", java.util.Map.of()))) + .isEqualTo("ERROR JOIN_REQUIRED Membership is required before PLAY. Use JOIN ."); + assertThat( + renderer.render( + PlayerOutput.error( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "fallback", + "error.play.public-production-admission-denied", + java.util.Map.of()))) + .isEqualTo( + "ERROR PUBLIC_PRODUCTION_ADMISSION_DENIED Public joining is not available for this" + + " world."); + } + @Test void localizedUnknownHelpTopicUsesConfiguredLocaleTemplate() { TextPlayerOutputRenderer renderer = From 20e31f9774e6414acf4d9994584a762201f438c1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:11:00 +1300 Subject: [PATCH 016/105] Align direct-text join status with current admission proof --- .../game-session-service/protocols.md | 6 +++--- .../microservices/tcp-proxy-service/README.md | 2 +- .../tcp-proxy-service/protocols.md | 16 ++++++++-------- .../system-architecture-frontend.md | 18 +++++++++--------- .../system-architecture-overview.md | 2 +- .../system-architecture-protocol-bridging.md | 14 +++++++------- .../system-architecture-reconnection.md | 12 ++++++------ 7 files changed, 35 insertions(+), 35 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 5577aee07c..f857a8f28d 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`, while a well-formed fresh `MISSING` or non-admitting `INACTIVE` membership still maps to `JOIN_REQUIRED` for eligible public-production entry or `WORLD_ACCESS_DENIED` for non-public entry. Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. The membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`. For a public-production target with fresh `MISSING` or non-admitting `INACTIVE` membership, it evaluates fresh tenant entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public-policy denial takes precedence. Non-public missing or non-admitting membership maps to `WORLD_ACCESS_DENIED`. Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. Its fresh membership response now carries lifecycle, authority-generation, version, and evaluation-time fields, but the target independent issuance-time generation/version baseline reread and durable replay revalidation remain gaps. For logout and retained private semantic context, [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) owns the binding termination fence and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) owns namespace-scoped `resumeContextGeneration` and replay eligibility. Current player text handling rejects `LOGOUT` before side effects, and first-party private semantic transcript replay is gated when durable episode/binding termination proof is unavailable; fresh authoritative `LOOK` remains available. This fail-closed child behavior does not establish the durable successor protocol or complete either ADR. @@ -116,7 +116,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` now validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; valid fresh missing or non-admitting membership maps to `JOIN_REQUIRED` for eligible public-production entry or `WORLD_ACCESS_DENIED` for non-public entry. Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. The membership-authority-generation reread and connect-token grant validation remain gaps. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` now validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; for a public-production missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`, while valid non-public missing or non-admitting membership maps to `WORLD_ACCESS_DENIED`. Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. The target independent membership-authority-generation/version reread at connect-token issuance and connect-token grant validation remain gaps. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -166,7 +166,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – bootstrap-backed `LOGIN` resolved to an account different from the validated connect-context subject. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. Direct-text clients can issue the implemented `JOIN`; first-party `Join & Play` remains unavailable. Account exposes lifecycle state, but current `PLAY` does not consume it, so the existing non-admitting case is not classified as `INACTIVE` there. +- `JOIN_REQUIRED` – after routing, authority, fresh entitlement, and public-policy checks pass, the selected public-production target has missing membership (`membershipExists=false`/`membershipLifecycleState=MISSING`) or an existing non-admitting `INACTIVE` membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. Direct-text clients can issue the implemented `JOIN`; first-party `Join & Play` remains unavailable. Current `PLAY` consumes Account's lifecycle, membership version, and authority-generation fields and does not infer `INACTIVE` from a boolean alone. - `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. diff --git a/design/architecture/microservices/tcp-proxy-service/README.md b/design/architecture/microservices/tcp-proxy-service/README.md index 0990b364a8..f98582d8ce 100644 --- a/design/architecture/microservices/tcp-proxy-service/README.md +++ b/design/architecture/microservices/tcp-proxy-service/README.md @@ -24,7 +24,7 @@ When code, tests, and docs diverge, align implementation to this doc set and the | Area | Target behaviour | Current status | Tracked in | | --- | --- | --- | --- | -| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | `LOGIN [secret]` and `PLAY` are implemented with focused proof for currently supported, already-authorized admission. The current proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`; that is an implementation gap. For a publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED` without invoking the membership writer; other targets retain their own visibility and grant checks. Explicit `JOIN` remains unimplemented, and the connect-token membership-authority-generation reread remains a gap. Manual end-to-end QA also remains. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | +| Telnet login-first flow | All Telnet clients must issue anonymous `WORLDS` before credential-bearing `LOGIN [secret]`; `LOGIN ` starts the email challenge. For public production, missing or `INACTIVE` membership must issue `JOIN` before `PLAY`; only an existing `ACTIVE` public-production member skips `JOIN`. Telnet shares the same admission pipeline as WebSocket clients. Any future classic-client semantic adapter is optional and cannot replace the plain-text flow or carry authority. `LOGIN` / `LOGON` semantics remain canonical in the Authentication & Authorization doc; this row only describes how Telnet traffic is forwarded into that flow. | Direct-text `LOGIN`, `PLAY`, and the Account-backed `JOIN` command are implemented with focused local proof. The current proxy still bootstraps a hidden default and does not enforce `WORLDS` before `LOGIN`; that is an implementation gap. For a publicly visible public-production target, Game Session `PLAY` validates fresh membership lifecycle/version/generation evidence and evaluates fresh entitlement/public policy before returning `JOIN_REQUIRED`; a text client can then invoke the implemented `JOIN` writer. Full Telnet discovery/bridge and PostgreSQL/recovery proof, manual end-to-end QA, first-party `Join & Play`, and the target connect-token issuance baseline/generation reread remain open. | [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) | | Proxy -> Gateway WebSocket mTLS | TCP Proxy is the WebSocket mTLS client: it presents the dedicated `FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH` and `FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH` identity to the Gateway server, with `FIREMUD_GATEWAY_WS_CA_CERT_PATH` for trust, while Gateway verifies the exclusive environment-bound identity required by [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). This client identity is distinct from TCP Proxy's internal gRPC server mTLS identity and from the separate Telnet server-TLS identity. | TCP Proxy now loads and rotates the dedicated PEM client identity and Gateway CA into one hostname-verifying client shared by gameplay bridges and Gateway readiness, rejects plaintext unless an explicit local/dev/test profile is active, and fails new admission closed after an invalid reload. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the dedicated authenticated Gateway listener, separate Gateway-server/TCP-Proxy-client Secret mounts, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned certificate issuance/projection and live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | | Optional classic-client semantic extensions | Plain text remains universal. MCP/GMCP/Telnet semantic negotiation and package support are deferred, unadvertised, and unsupported in shared, player-facing, and prod-like profiles; an explicit local/development/test profile may enable only the legacy marker/greeting seam for bounded development use. If a future adapter is selected, Game Session owns semantics while TCP Proxy remains a generic bounded bridge. | The current `TCP_PROXY_MCP_ENABLED` marker/greeting seam is implementation drift, not semantic support. Target startup rejects it in shared, player-facing, and prod-like profiles; only explicit local/development/test profiles may enable the marker, and the profile rejection is not yet proved. No interoperability or end-to-end extension proof exists. | [MCP-01](../../decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | | Connection limits and abuse protection | Connection caps, idle timeouts, input size limits, buffering, and generic opaque-marker safety protect the DMZ boundary. TCP Proxy does not parse or maintain classic-client semantic state. Accepted input that exceeds a generic limit or cannot be forwarded under backpressure receives an explicit error/close rather than a keep-open silent discard. | Core limit handling is implemented; tuning and additional metrics may evolve as production behaviour is observed. | [Platform Operations and Delivery](../../../project-management/implementation-tracking/platform-operations-and-delivery.md) | diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index fc71097ddc..fbf7fca997 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -8,29 +8,29 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance requires fresh Account membership evidence (`membershipExists=true` and `gameplayAdmissionAllowed=true`); a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof. Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check and, for private/playtest targets, its applicable current realm-grant check. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. +The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof, and the target independent issuance baseline/generation/version reread remains unproved. Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for public-production missing or non-admitting membership it evaluates fresh entitlement/public policy before `JOIN_REQUIRED`, and for private/playtest targets it performs the applicable current realm-grant check. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` always performs fresh membership and applicable private/playtest grant checks, regardless of any connect-token replay-cache state. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). The Telnet credential form is `LOGIN [secret]`. `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. -The current text `PLAY` path checks the fresh Account response's `membershipExists` and `gameplayAdmissionAllowed` fields plus the realm grant where applicable; the current connect-token path uses the same membership fields but the private/playtest grant check remains an implementation and proof gap. These local gaps do not change the Authentication-owned admission outcomes. -The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients currently use the abbreviated fail-closed `LOGIN` -> `PLAY` -> `LOOK` path for otherwise admitting existing members; missing or existing non-admitting eligible public-production membership returns non-actionable `JOIN_REQUIRED`, and missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately and is not current behavior. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. +The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but the target independent issuance baseline/reread and private/playtest grant check remain implementation and proof gaps. For an eligible public-production target with missing or non-admitting membership, text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or policy denial wins. These local gaps do not change the Authentication-owned admission outcomes. +The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients have a local `LOGIN` -> `PLAY` -> `LOOK` path for existing admitting members; when `PLAY` returns `JOIN_REQUIRED`, the client can issue `JOIN` and retry `PLAY` before `LOOK`. Focused local JOIN proof exists, while full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Missing or existing non-admitting eligible public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement/public policy permits joining, and direct text can invoke the Account-backed writer. Missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. ## Cross-Path Connectivity Contract The following are canonical contracts across Telnet and WebSocket paths: -- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. In the current runtime, explicit `JOIN` is unavailable, hidden default routing is bootstrapped, and missing public-production membership does not create membership. Direct text does not use a first-party WebSocket discovery snapshot. +- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. In the current runtime, direct-text `JOIN` is implemented through the Account-owned writer, but hidden default routing is bootstrapped and `WORLDS` is not enforced as a prerequisite; complete Telnet discovery/bridge proof remains open. Direct text does not use a first-party WebSocket discovery snapshot. - Proxy -> Gateway WebSocket hop is mTLS-authenticated in player-facing environments under [Security](../../system-architecture-security.md#tls-termination--internal-encryption). - Proxy bridge-availability circuit breaker uses deterministic open/half-open/closed admission behavior during sustained upstream unreachability. ## Recommended Telnet Client Flows -These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. The target flow includes explicit `JOIN`; current Telnet clients cannot perform `JOIN` and fail closed with non-actionable `JOIN_REQUIRED` when an otherwise eligible public-production response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE`. In target behavior, an `INACTIVE` existing public-production membership also follows `JOIN_REQUIRED`; only an existing `ACTIVE` member skips `JOIN`. The missing connect-token membership-authority-generation reread is a separate gap. +These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. Direct-text `JOIN` is implemented and focused locally, but full Telnet discovery/bridge proof remains open. Current text `PLAY` validates the lifecycle/version/generation membership evidence and evaluates fresh public entitlement/policy before returning `JOIN_REQUIRED` for an otherwise eligible missing or `INACTIVE` public-production membership; only an existing `ACTIVE` member skips `JOIN`. The target connect-token membership-authority-generation/version baseline reread remains a separate gap. - **Target canonical player flow** - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the target-only conditional `JOIN`; current text reconnect stops with non-actionable `JOIN_REQUIRED` when the current response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false` for an eligible public-production request; the latter cannot be classified as `INACTIVE` and performs no membership mutation. Target behavior also returns `JOIN_REQUIRED` for `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, while target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; current text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED` for missing or `INACTIVE` membership, after which direct text can invoke the implemented Account-backed writer. Target behavior also returns `JOIN_REQUIRED` for `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, while target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. Full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -103,14 +103,14 @@ Typed `SESSION` gameplay lines are no longer part of the Telnet contract. TCP Pr Current rules: -- current Telnet runtime uses hidden default routing and the abbreviated `LOGIN` -> `PLAY` -> `LOOK` path for existing members. It fails closed with non-actionable `JOIN_REQUIRED` when an otherwise eligible public-production response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE`. Target behavior requires `JOIN_REQUIRED` for `INACTIVE` and skips `JOIN` only for an existing `ACTIVE` public-production member. Current private/playtest text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED` and checks the current realm grant; the full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remains target-only; +- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`, but its local text flow supports `LOGIN` -> `PLAY` -> `LOOK` for existing admitting members or `LOGIN` -> `PLAY` (`JOIN_REQUIRED`) -> `JOIN` -> `PLAY` -> `LOOK` when joining is required. It validates Account membership lifecycle/version/generation evidence and, for an otherwise eligible public-production missing or `INACTIVE` membership, fresh entitlement/public policy before returning `JOIN_REQUIRED`; direct text can then invoke the implemented Account-backed writer. Current private/playtest text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED` and checks the current realm grant; the complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remains unproved end to end; - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; - any future adapter-carried attach hint must remain advisory and must not bypass either the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` fail-closed path or the target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow; only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because explicit `JOIN` is unavailable, hidden default routing is bootstrapped instead, and otherwise admitting existing members may use the abbreviated current `LOGIN` -> `PLAY` -> `LOOK` path; the target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime supports the local Account-backed `JOIN` command and fresh public entitlement/policy gating in Game Session `PLAY`, but still bootstraps hidden default routing and does not enforce `WORLDS`; full target Telnet discovery/bridge and PostgreSQL/recovery proof remain open. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 1c61352bf7..eea3577924 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -20,9 +20,9 @@ The first-party browser consumes the existing Account/Gateway APIs and the versi The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output, but the independently released static host, public-site routing and delivery (including the target `/auth/**` rewrite), health/security/cache behavior, rollback, and bounded end-to-end browser proof are not implemented or proved. Those gaps remain target implementation obligations rather than evidence that the supported frontend boundary is live. -Explicit `JOIN`/`Join & Play` is target behavior, not a complete current runtime flow. In the target, `JoinPublicProductionMembership` is the sole membership writer for explicit public-production join, creating missing membership or restoring `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current membership response exposes only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; current connect-token issuance and text `PLAY` proceed only when the two admission fields are true, and an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed. Explicit `JOIN`/`Join & Play` and the required connect-token `membershipVersion` plus `membershipAuthorityGeneration` reread remain unimplemented/proof gaps, so the current fail-closed result must not be read as an actionable join flow or as proof that the complete target sequence is implemented. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. The frontend availability gate applies to the otherwise eligible current `membershipExists=false` or existing `gameplayAdmissionAllowed=false` cases; the latter cannot be classified as `INACTIVE`, and target lifecycle-specific handling of missing or `INACTIVE` membership remains target-only. Returning members and grant-backed private/playtest flows remain eligible only when the live membership response fields, grant, entitlement, and routing checks pass; target generation/version rereads remain unimplemented. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. +Direct-text `JOIN` is implemented locally through the Account-owned `JoinPublicProductionMembership` writer; first-party `Join & Play` remains target-only and the complete browser/Telnet flow is not proved. In the target, the writer creates missing membership or restores `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current Account membership response exposes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. Current text `PLAY` validates the fresh lifecycle/version/generation evidence; for an otherwise eligible public-production missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`, while entitlement outage or public policy denial wins. Current connect-token issuance receives the lifecycle/version/generation fields on its fresh path, but replay-cache hits can bypass fresh reads and the target independent issuance baseline/generation reread remains a proof gap. Direct-text JOIN has focused local coverage, while complete Telnet discovery/bridge, PostgreSQL/recovery, and first-party `Join & Play` proof remain open. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership/grant/entitlement/routing checks pass; current connect-token private/playtest grant validation remains incomplete. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. -The explicit `JOIN`/`Join & Play` action and the independent `membershipVersion` plus `membershipAuthorityGeneration` reread at connect-token issuance are both unimplemented/proof gaps. Until both are implemented and proven, the frontend must keep first public-production entry with a missing or non-admitting current membership response fail-closed and unavailable rather than exposing a retry path that can create membership implicitly or issue a token from stale authority. Returning members and private/playtest callers with existing membership remain eligible when the live response fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and the other current admission checks pass; the exact `membershipAuthorityGeneration` and independent issuance-time `membershipVersion` rereads remain target/proof gaps. Target lifecycle-specific handling of missing or `INACTIVE` membership remains unavailable until that target response exists. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). +The direct-text `JOIN` action is implemented, but first-party `Join & Play` and the independent issuance-time membership baseline/generation reread remain unimplemented or unproved. The frontend must keep the complete first-party browser join flow unavailable until that route, its post-join snapshot, and its token-issuance proof are complete; direct-text clients may use the implemented join writer. Current text `PLAY` and the fresh connect-token path receive lifecycle, version, generation, and evaluation-time fields; existing-member admission requires `ACTIVE`, while an eligible public-production missing or non-admitting response reaches `JOIN_REQUIRED` only after fresh entitlement permits public joining. Returning members and private/playtest callers remain eligible only when the other current membership, grant, entitlement, and routing checks pass. Complete Telnet/browser end-to-end, PostgreSQL/recovery, replay-cache revalidation, and issuance-baseline proof remain open. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). ### Persisted actor entry UX boundary (PLAYER-01) @@ -41,7 +41,7 @@ The frontend keeps the target `PLAY` gate separate from the target `Join & Play` - **`PLAY` gate:** enable only after fresh selected-target routing/pointer evidence, entitlement, caller-bound `membershipLifecycleState=ACTIVE`, any required realm grant, and a valid current character all pass. `PLAY` never creates or restores membership. - **`Join & Play` gate:** enable only for the selected public-production realm when the fresh public-joining policy is `allowPublicJoin=true` and caller-bound membership is missing or `INACTIVE`; it invokes the explicit Account join route and waits for the post-join snapshot before character discovery, creation, connect-token issuance, or `PLAY`. -These are target-only gates. The current frontend must keep missing or non-admitting membership unavailable and must not expose an actionable Join route while the explicit join endpoint and required issuance reread remain unimplemented. A private/playtest target never uses the public `Join & Play` gate; it requires existing `ACTIVE` membership plus the current realm grant. +These are target-only frontend gates. The current frontend has no complete first-party `Join & Play` route; it must not expose that browser action until the explicit endpoint and issuance reread are implemented and proved. Direct-text `JOIN` is a separate implemented Game Session/Account path. A private/playtest target never uses the public `Join & Play` gate; it requires existing `ACTIVE` membership plus the current realm grant. ## Implementation Notes @@ -98,7 +98,7 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - Target first-party clients use one of two explicit gameplay flows: - **Returning member:** `POST /auth/player-bootstrap` -> bootstrap discovery -> bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with the discovery-provided `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This flow requires the selected existing caller-bound membership and does not call `/auth/bootstrap/join`. - **First join:** `POST /auth/player-bootstrap` -> public-production discovery -> `POST /auth/bootstrap/join` -> rerun public-production realm discovery -> use the new complete `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` snapshot for bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with that new snapshot's `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This public-production, non-grant snapshot intentionally omits both `playtestLifecycleId` and `playtestStateGeneration`; private/playtest snapshots include both fields. `/auth/bootstrap/join` may create missing membership or restore `INACTIVE` membership and must commit it against the exact `{catalogRevision, pointerVersion}` pair before the post-join discovery, character discovery, character creation, or connect-token issuance; no later step may create membership implicitly. The join transition emits one audit/outbox event for create or restore; an `ACTIVE` retry is event-free. - - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not confirmed current supported behavior. Current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they proceed only when the two admission fields are true and may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. That current `JOIN_REQUIRED` result is non-actionable while explicit `JOIN` / `Join & Play` is unimplemented; the frontend must not expose it as an available repair action. The obsolete implicit membership-writer surface has been removed; the required `membershipAuthorityGeneration` plus `membershipVersion` reread at connect-token issuance remains an unimplemented/proof gap. Current returning-member behavior may proceed when the existing live membership/character checks pass, but it does not prove the target exact generation/version reread; the target requires both independent values from one fresh membership snapshot. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Returning members and private/playtest callers with existing membership plus the current grant remain eligible only when their current runtime checks pass. The target descriptions remain the behavior to implement. + - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not confirmed complete current supported behavior. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` and fresh connect-token issuance receive `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; text `PLAY` requires fresh lifecycle/version/generation evidence and, for eligible public-production missing or non-admitting membership, fresh entitlement with `allowPublicJoin=true` before `JOIN_REQUIRED`. Current returning-member behavior may proceed when the existing live membership/character checks pass, but the target exact issuance baseline/generation/version reread and durable replay revalidation remain unproved. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Returning members and private/playtest callers with existing membership plus the current grant remain eligible only when their current runtime checks pass. Complete first-party browser, Telnet, PostgreSQL/recovery, and downstream proof remain open. The target descriptions remain the behavior to implement. - For every `POST /auth/connect-token` issuance, including the first issuance immediately after explicit join and both returning-member and grant-backed private/playtest flows, the service must independently validate the scalar `membershipVersion` returned by `GetTenantMembershipForRuntime` for the selected `{accountId, tenantId}` and the `membershipAuthorityGeneration` from that same authoritative membership snapshot. It must compare both values independently with the selected admission baseline, bind the scalar `membershipVersion` and generation into the connect-token issuance/binding evidence, and fail closed when either value is missing, stale, mismatched, unavailable, or assembled from another snapshot; a current grant never substitutes for the membership-version validation. - Browser and mobile-browser clients receive the short-lived `Firemud-Connect-Token` HttpOnly cookie used by the `/ws/game/**` handshake; first-party native-mobile clients using a cookie jar remain cookie-only. This protected-cookie path is the current supported path to bare `LOGIN`. Explicitly classified non-first-party/public non-browser clients are target-only and unavailable until their dedicated issuance route is fully registered and proven; the conditional target carrier is protected secure storage plus `X-Firemud-Connect-Token`, not a fallback for the current cookie path. The client then opens `/ws/game/**` and completes gameplay authentication by issuing `LOGIN` over the WebSocket channel using the already-verified bootstrap/connect context; Game Session must validate the complete context, including the direct `realmId`, before using any field for `LOGIN`, `PLAY`, or scope comparison. The browser never prompts for or replays Telnet-style `LOGIN [secret]` credentials, as described in [Authentication & Authorization](./system-architecture-authentication.md#login-and-session-flow). - Browser transport constraints matter: a browser WebSocket cannot set arbitrary custom handshake headers the way Telnet smart clients, Mudlet integrations, or server-side clients can. The first-party browser flow therefore uses the `Firemud-Connect-Token` cookie set by `POST /auth/connect-token` with `HttpOnly`, `Secure`, `SameSite=Strict`, `Path=/ws/game`, and `Max-Age` no longer than the connect-token TTL. The React client must not read or persist the connect token itself; it only consumes non-secret response metadata such as `expiresAt`, `tenantId`, `realmId`, `realmSlug`, and `gameInstanceId`. Query parameters must never carry connect tokens or other authentication credentials; non-secret bootstrap discovery selectors such as `connectScopeId` may be sent as query parameters. Clients must obtain a fresh token after any failed attempt that may have consumed it. After Account has durably committed an issuance result or Gateway has consumed its token, any new token issuance requires a new `requestId`; the old `requestId` may only reconcile that same request while its outcome is `PENDING` or otherwise indeterminate and never mints a replacement token. @@ -108,10 +108,10 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - The target canonical player logout order is: stop reconnect attempts, capture the current `player-bootstrap` token into the pending-revocation slot, ask Account to durably commit the exact-token `PENDING` intent and immediately advance the exact-token issuance fence to `PENDING_LOGOUT` in that same durable step, then send gameplay `LOGOUT` and close the gameplay socket, ask Gateway to deny the gameplay-connect `jti` and clear the HttpOnly cookie, and finally ask Account to invalidate the underlying token and commit the `COMMITTED` tombstone. Account must establish the durable issuance fence before socket closure or any racing `/auth/connect-token` issuance can succeed; every issuance path rejects the fenced lineage rather than returning a usable late credential. Once `PENDING` is durable, Account must reject racing issuance, refresh, rebind, installation, and every unrelated reconciliation for that token lineage; only the exact matching Account lifecycle reconciliation may complete or abort that pending logout operation. `PENDING` is never success and remains resumable through that exact Account operation until terminal completion. If Gateway revoke is unavailable, Account must not report the edge deny/clear outcome as confirmed; clear only local reconnect/client state and rely on the bounded token lifetime; Gateway mitigation must not be reported as full logout when Account is unavailable or its fence is unconfirmed. The browser never directly clears the HttpOnly gameplay cookie; only a server response can clear that cookie. The target Gateway revoke call uses a two-second per-attempt timeout, at most two retries, and 250 ms then 500 ms backoff where time remains, but every request timeout and backoff is capped by the remaining five-second total deadline. This Gateway controller budget is independent and non-nested: it is not shared with or added to Account's revocation budget. Account revocation retains its separate policy of at most five attempts, a five-second timeout per attempt capped by a 30-second overall deadline, and full-jitter exponential backoff starting at 250 ms and capped at four seconds. The controller tracks Account PENDING, Gateway denial/clearing, and Account COMMITTED finalization as separate outcomes. It enters terminal `LOGGED_OUT_REVOKED` only after Account confirms the exact-token fence/Bootstrap-token revocation and Gateway confirms denial/clearing of the gameplay-connect token. Because Gateway gameplay-connect denial and cookie clearing are not currently routable, the current runtime cannot reach `LOGGED_OUT_REVOKED`; current logout flows terminate as `LOGGED_OUT_REVOCATION_UNCONFIRMED`. Account-only confirmation remains `LOGGED_OUT_REVOCATION_UNCONFIRMED` with edge revocation explicitly unconfirmed until Gateway confirms or the known gameplay-connect acceptance window ends; expiry closes that bounded edge risk but is reported as token-window expiry, not confirmed server revocation. Retry exhaustion, an unconfirmed Account result, or bootstrap-token expiry likewise remains `LOGGED_OUT_REVOCATION_UNCONFIRMED`, stays locally logged out, and requires a fresh `POST /auth/player-bootstrap` before any later gameplay flow. The frontend may retry only while the captured credential remains valid and its local retry deadline remains open. At the earlier of signed token expiry or that deadline, it wipes the raw credential and stops frontend retries while retaining only the opaque server-side logout handle and non-secret operation state needed to observe Account's durable reconciliation. Browser or process loss likewise destroys the memory-only credential and ends frontend retries, but neither local expiry nor frontend loss cancels the durable Account `PENDING` operation: Account's persisted operation and opaque logout handle are the authoritative revocation proof, and Account's reconciler continues exact-token revocation without the raw token. A raw credential may never be reused for gameplay/bootstrap calls, and retaining it in memory never extends its signed lifetime. Local clearing or process termination is not confirmed server revocation. - Logout invalidates the local bootstrap/connect-token request epoch and aborts every in-flight bootstrap, discovery, join, character, and connect-token request owned by that epoch. A late response is ignored for all client state transitions, but abort and epoch invalidation cannot guarantee that a late `Set-Cookie` was not already committed by the browser. The server-side logout issuance fence is therefore authoritative: Account rejects bootstrap or connect-token issuance that races a durable `PENDING` or `COMMITTED` logout for the same account/token lineage, and Gateway rejects a connect token whose deny/revocation fence wins before consumption. Where a logout response reaches the browser after the old issuance, the server must also return an explicit clearing or deny response so the late cookie cannot remain usable. The client must never treat ignored local state or local cookie clearing alone as proof of server revocation. - A server must reject an expired `Firemud-Connect-Token` cookie as `CONNECT_TOKEN_EXPIRED`, never fall back to a stale cookie, query parameter, or unapproved header, and return a clearing `Set-Cookie` response where the HTTP surface can do so. The browser cannot inspect the HttpOnly value; it discards the failed handshake attempt and obtains a fresh connect token only from a still-valid bootstrap session. If the bootstrap token is expired or revoked, the client restarts `POST /auth/player-bootstrap` and discovery instead of treating the expired cookie as a recoverable gameplay credential. - - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and the explicit join/connect-token APIs, but it does not itself carry or grant gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, a first public-production join presents an explicit `Join & Play` action that may create missing durable Account-owned membership or restore `INACTIVE` membership, before character creation and `POST /auth/connect-token`; connect-token issuance never creates membership implicitly. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed, while explicit `JOIN` / `Join & Play` and the membership-authority-generation reread at issuance remain unimplemented/proof gaps. The frontend must mark the current otherwise eligible missing or existing non-admitting membership predicate unavailable/unsafe rather than treating a stale-generation path as a target fallback; existing-member and grant-backed flows remain separately gated by their own current checks. The selected target must come from canonical discovery and may be the public production realm or an explicitly authorized alternate realm such as a playtest fork. + - Tenant membership, non-public realm-access-grant checks, and runtime entitlement checks occur after account bootstrap. The `player-bootstrap` token is still a tenant-free, non-gameplay bootstrap credential: it authorizes caller-bound discovery and the explicit join/connect-token APIs, but it does not itself carry or grant gameplay scope. The bounded `gameplay-connect` token is the only edge-admission credential carrying the selected target snapshot. In target behavior, a first public-production join presents an explicit `Join & Play` action that may create missing durable Account-owned membership or restore `INACTIVE` membership, before character creation and `POST /auth/connect-token`; connect-token issuance never creates membership implicitly. Direct-text `JOIN` is already implemented locally through the same Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` validates lifecycle/version/generation evidence and, for eligible public-production missing or non-admitting membership, requires fresh entitlement with `allowPublicJoin=true` before `JOIN_REQUIRED`; current connect-token issuance receives the same membership fields but still has replay-cache and issuance-baseline proof gaps. The frontend must not advertise the unavailable first-party browser repair path or treat stale token authority as a fallback; existing-member and grant-backed flows remain separately gated by their own current checks. The selected target must come from canonical discovery and may be the public production realm or an explicitly authorized alternate realm such as a playtest fork. - Gameplay admission has three separate applicability modes. For public-production onboarding, discovery may precede membership, but only explicit `JOIN`/`Join & Play` creates missing membership or restores `INACTIVE` membership; `gameplay-connect`, trusted TCP Proxy admission, and `PLAY` are applicable only after that commit. For returning membership, those transports and `PLAY` require the existing caller-bound membership and current authority checks and do not perform onboarding. For a grant-backed private or playtest realm, missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`; those targets require the applicable grant and the existing caller-bound `ACTIVE` membership plus its current membership authority generation, never use public `JOIN`, and never create membership or treat the grant as a substitute for membership. The trusted TCP Proxy is only a transport trust path and does not replace the mode-specific downstream checks; a `gameplay-connect` token and `PLAY` command likewise do not establish membership or grant eligibility. - The client must treat `connectScopeId` as an opaque short-lived selector, not as a stable saved identifier. For non-grant public production, the discovery snapshot bundle is `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}`; private/playtest snapshots contain the same fields plus the applicable `playtestLifecycleId` and `playtestStateGeneration`. If reconnect or retry reports `CONNECT_SCOPE_MISMATCH`, it must discard the entire bundle and all derived connect-token metadata, rerun bootstrap discovery, complete target-only `Join & Play` and required character discovery/creation when applicable, and obtain a new selector and connect token rather than reusing any old bundle field or guessing a replacement target from cached `tenantId` or `realmSlug`. `ADMISSION_POINTER_UNAVAILABLE` likewise requires fresh discovery before retry rather than substitution from cached target fields. - - Returning players with an existing Account-owned membership use browser bootstrap, bootstrap discovery, and `POST /auth/connect-token` before taking the normal `PLAY [realm] [character]` path; the target skips the membership-creation action only after a fresh authoritative check confirms `ACTIVE` membership and its exact authority/version evidence. A valid current character is additionally required only before connect-token issuance or direct `PLAY`; otherwise the player proceeds through realm-scoped character discovery or creation. Target behavior requires an account with missing or `INACTIVE` membership for the selected game, including an otherwise returning account whose membership is no longer active, to take the explicit `Join & Play` path before character creation/connect, and forbids a connect-token or `PLAY` path from creating or restoring that membership implicitly. Current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may fail closed with non-actionable `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE` because lifecycle state is target-only, and explicit `JOIN` remains unavailable. The obsolete implicit membership-writer surface has been removed; explicit `Join & Play` remains unimplemented, as does the required membership-authority-generation and independent membership-version reread proof at issuance. Current returning-member success therefore reflects the live existing-membership path, not proof of the target reread contract. The resulting membership powers subsequent “my games” and return flows. Game Session resolves world/realm/character identifiers, rechecks membership, routing, and caller-bound entitlements, returns bundle metadata, and binds the socket in Redis. + - Returning players with an existing Account-owned membership use browser bootstrap, bootstrap discovery, and `POST /auth/connect-token` before taking the normal `PLAY [realm] [character]` path; the target skips the membership-creation action only after a fresh authoritative check confirms `ACTIVE` membership and its exact authority/version evidence. A valid current character is additionally required only before connect-token issuance or direct `PLAY`; otherwise the player proceeds through realm-scoped character discovery or creation. Target behavior requires an account with missing or `INACTIVE` membership for the selected game, including an otherwise returning account whose membership is no longer active, to take the explicit `Join & Play` path before character creation/connect, and forbids a connect-token or `PLAY` path from creating or restoring that membership implicitly. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` and fresh connect-token issuance receive `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; text `PLAY` validates lifecycle/version/generation and evaluates fresh public entitlement/policy before returning `JOIN_REQUIRED` for an otherwise eligible missing or `INACTIVE` public-production membership. Current returning-member success therefore reflects the live existing-membership path, not proof of the target issuance baseline/generation reread or replay revalidation. The resulting membership powers subsequent “my games” and return flows. Game Session resolves world/realm/character identifiers, rechecks membership, routing, and caller-bound entitlements, returns bundle metadata, and binds the socket in Redis. - After connectivity loss while the in-memory `player-bootstrap` token survives, the client may request a fresh connect token, reconnect the WebSocket, then replay `LOGIN` and `PLAY` without prompting for credentials again only when the complete discovery snapshot is present and unexpired, and a fresh authoritative read confirms `membershipLifecycleState=ACTIVE`, the exact current `membershipAuthorityGeneration`, the independently current `membershipVersion`, and a valid current character for the selected target. A full page reload loses that memory-only token and must restart at `POST /auth/player-bootstrap`, then rerun discovery before requesting a connect token; the architecture defines no hidden refresh credential. `WORLDS`, `REALMS `, and `CHARS [realm]` remain optional discovery helpers only while the complete snapshot remains unexpired and those current membership, generation, version, and character checks pass; otherwise the client must rerun the full discovery/join/character path. Shared state restores session context only. Game Session must revalidate continuation authorization, the active binding and its fence, revocation state, and the current server-resolved target authority before resuming; Redis key presence or fresh backend-token rebinding is not authorization. First-party reconnects must not prompt the browser to replay Telnet-style `LOGIN [secret]` credentials after bootstrap has been re-established. - **Admin and creator UIs** @@ -127,14 +127,14 @@ All new frontend features that interact with protected APIs should reuse the sha - `AUTH_TOKEN_EXPIRED` – Clear in-memory auth state, redirect to login, and show a “Session expired” message. - `AUTH_SESSION_REVOKED` – Clear in-memory auth state, redirect to login, and show a security-focused message (for example, “You were signed out because your account security changed.”). - - `JOIN_REQUIRED` – Preserve in-memory authentication when an otherwise eligible public-production request does not admit because `membershipExists=false` or existing `gameplayAdmissionAllowed=false`, mark the affected admission unavailable, and do not expose an actionable `Join & Play` retry while explicit `JOIN` and the required membership reread are unimplemented. The latter response cannot be classified specifically as `INACTIVE` or used as a lifecycle-state result. Keep character discovery/creation, connect-token issuance, and `PLAY` blocked; do not retry those operations automatically or create membership implicitly. When implemented, explicit `JOIN`/`Join & Play` creates missing membership or restores target-only `INACTIVE`; private/playtest text `PLAY` currently returns `WORLD_ACCESS_DENIED` for missing or non-admitting membership, while the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Target `PLAY` behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED`, remains separately gated by the current grant, and never uses public `JOIN` as a fallback; keep the current endpoint outcomes distinct in the UI. + - `JOIN_REQUIRED` – Preserve in-memory authentication when fresh routing, authority, entitlement, and public policy permit an otherwise eligible public-production request but membership is `MISSING` or non-admitting `INACTIVE`; keep character discovery/creation, connect-token issuance, and `PLAY` blocked until the direct-text or first-party owner flow completes. The frontend must not expose the unavailable first-party browser `Join & Play` action, but the implemented direct-text `JOIN` path is distinct and may be used by text clients. Do not retry admission automatically or create membership implicitly. Private/playtest text `PLAY` currently returns `WORLD_ACCESS_DENIED` for missing or non-admitting membership, while the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Target `PLAY` behavior uses `NON_PUBLIC_ENROLLMENT_REQUIRED`, remains separately gated by the current grant, and never uses public `JOIN` as a fallback; keep the current endpoint outcomes distinct in the UI. - `AUTH_UNAVAILABLE` – Keep in-memory auth state and show a retriable authentication-service availability message for ordinary API calls when authority availability is `UNAVAILABLE` for live membership, registry, or another required non-routing, non-entitlement authority. Reachable invalid pointer evidence uses `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out pointer authority uses `AUTH_UNAVAILABLE`; entitlement authority outage uses `ENTITLEMENT_UNAVAILABLE`. None may be relabeled as a billing block. An unavailable authority is not equivalent to missing or non-admitting membership and must not produce `JOIN_REQUIRED`. Block only the affected authority-dependent or billing-unsafe mutation, including gameplay-admission mutations, until authority recovers; billing-safe operations that remain permitted under `TENANT_BILLING_BLOCKED` remain available unless they independently require the unavailable authority. Retry only idempotent reads, or mutations carrying the same stable request idempotency key that the service durably deduplicates, with at most one automatic retry inside a five-second total deadline and bounded backoff. The dedicated logout controller uses its separate bounded logout/revocation budget and is excluded from this generic retry rule. Never replay an unkeyed or non-idempotent mutation, and do not convert this infrastructure failure into logout. - `ENTITLEMENT_UNAVAILABLE` – Preserve authentication state and show a retriable entitlement-availability message when entitlement authority is `UNAVAILABLE` or the required fresh Account entitlement evaluation cannot be established. Block only the affected admission, capacity, or other entitlement-dependent operation; retry under the same idempotency and bounded-backoff rules as `AUTH_UNAVAILABLE`. Do not relabel the outage as `TENANT_BILLING_BLOCKED`, `AUTH_UNAVAILABLE`, or `JOIN_REQUIRED`, and do not use stale entitlement state unless the exact bounded same-binding continuity contract applies. - `TENANT_BILLING_BLOCKED` – Keep the user logged in, mark the denied admission, capacity, or mutation operation as billing-blocked in UI state, and show a prominent billing banner. This is not a blanket tenant gameplay shutdown: preserve connected sessions, eligible same-session resume, permitted `past_due` gameplay, and billing-safe operations such as viewing invoices or updating payment details; `grace` preserves connected sessions and same-session resume but denies first-time public join, first/new gameplay bindings, new instances, scale-out, and quota growth. Apply this code only when authoritative Account evidence explicitly denies that operation; `ENTITLEMENT_UNAVAILABLE` takes precedence when entitlement authority cannot be obtained, while `AUTH_UNAVAILABLE` remains the corresponding non-entitlement authority outage. Neither unavailable result may be converted into a billing block. - `ADMISSION_POINTER_UNAVAILABLE` – Keep the current auth state for reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid catalog/pointer evidence, show a retriable gameplay-admission unavailable message, rerun bootstrap discovery or reconciliation, and only then retry lobby admission with bounded backoff; never substitute a cached tenant or runtime target. Unreachable or timed-out pointer authority is `AUTH_UNAVAILABLE` instead. - Target-state `REALM_UNAVAILABLE` – Keep the current auth state when the resolved realm pointer is complete and `CLOSED`, create no gameplay binding, and wait for fresh discovery or an authoritative availability change rather than fast-looping retries. This is distinct from reachable invalid pointer evidence (`ADMISSION_POINTER_UNAVAILABLE`) and unreachable or timed-out pointer authority (`AUTH_UNAVAILABLE`). - `CONNECT_CONTEXT_INVALID` – Keep the current auth state, force gameplay reconnect flow (`connect-token` refresh + new socket + `LOGIN`), and block `PLAY` retries on the current socket. -- `CONNECT_SCOPE_MISMATCH` – Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, rerun bootstrap discovery, and do not expose an actionable current repair because explicit join is unimplemented. Target behavior additionally completes `Join & Play` when the newly selected public target requires membership, performs required character discovery/creation, requests a fresh connect token only from the newly returned bundle, and retries on a new socket. + - `CONNECT_SCOPE_MISMATCH` – Keep the current auth state, discard the entire discovery snapshot bundle and all connect-token metadata derived from it, including `realmId` and `catalogRevision`, and rerun bootstrap discovery. The current frontend still has no actionable first-party browser join repair because `Join & Play` is unavailable; target behavior additionally completes `Join & Play` when the newly selected public target requires membership, performs required character discovery/creation, requests a fresh connect token only from the newly returned bundle, and retries on a new socket. Client rule for discovery-issued selectors: @@ -156,7 +156,7 @@ These handshake classes are edge-handshake outcomes, not gameplay text-protocol ### Current Implemented Browser Reconnect Behavior -Current first-party reconnect proof is limited to the protected-cookie path. When an unexpired in-memory `player-bootstrap` token remains, the client may request a fresh connect token for the current discovery scope, open a new `/ws/game/**` socket with the HttpOnly cookie, send bare `LOGIN`, and issue `PLAY` only when the current Account membership/admission fields and the other implemented checks pass. A page reload or expired bootstrap token restarts `POST /auth/player-bootstrap` and discovery. Current `CONNECT_SCOPE_MISMATCH` handling discards the stale bundle and reruns discovery, but missing or non-admitting membership remains unavailable/non-actionable because explicit `JOIN`/`Join & Play` and the target issuance reread are not implemented. A fresh edge reconnect never replays client input, raw bytes, WebSocket frames, unsent Telnet output, or a prior prompt; it may receive bounded semantic recent context, then a fresh authoritative `LOOK`. Target behavior emits exactly one current prompt only when both effective `firemud.presentation.prompt.enabled` and `firemud.presentation.prompt.emit-after-reconnect-restore` are enabled, or zero reconnect prompts if either is disabled. Current handler composition gates only `firemud.presentation.prompt.emit-after-reconnect-restore`, not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one. This structured-prompt discrepancy is a target-blocking implementation/proof gap: the frontend must not claim the complete two-setting behavior is implemented or proven. This behavior does not prove the target lifecycle, grant, generation, or independent membership-version reconnect contract. +Current first-party reconnect proof is limited to the protected-cookie path. When an unexpired in-memory `player-bootstrap` token remains, the client may request a fresh connect token for the current discovery scope, open a new `/ws/game/**` socket with the HttpOnly cookie, send bare `LOGIN`, and issue `PLAY` only when the current Account membership/admission fields and the other implemented checks pass. A page reload or expired bootstrap token restarts `POST /auth/player-bootstrap` and discovery. Current `CONNECT_SCOPE_MISMATCH` handling discards the stale bundle and reruns discovery, but first-party missing or non-admitting membership remains unavailable/non-actionable because `Join & Play` and the target issuance reread are not implemented; this does not describe the separate implemented direct-text `JOIN` path. A fresh edge reconnect never replays client input, raw bytes, WebSocket frames, unsent Telnet output, or a prior prompt; it may receive bounded semantic recent context, then a fresh authoritative `LOOK`. Target behavior emits exactly one current prompt only when both effective `firemud.presentation.prompt.enabled` and `firemud.presentation.prompt.emit-after-reconnect-restore` are enabled, or zero reconnect prompts if either is disabled. Current handler composition gates only `firemud.presentation.prompt.emit-after-reconnect-restore`, not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one. This structured-prompt discrepancy is a target-blocking implementation/proof gap: the frontend must not claim the complete two-setting behavior is implemented or proven. This behavior does not prove the target lifecycle, grant, generation, or independent membership-version reconnect contract. ### Target-Only First-Party Browser Reconnect Sequence diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index 24d7824cf3..22dc520091 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -529,7 +529,7 @@ Gameplay authentication is transport-specific. Credential-bearing Telnet and oth The receiver token is the exact `game-session-account-delegation` JWT profile with audience `account-service`; it is an Account-issued private backend credential, never a client gameplay credential. Its registry and rotation rules do not define the active gameplay-session lifetime or the bounded continuity/reconnect cache lifetime. If the Account response is lost during credential-bearing text login, Game Session retries with the same `requestId` and exact request digest. Account resumes matching pending work or returns the stored committed result/terminal outcome; it must not mint a second token merely because the first response was not observed. A confirmed binding-CAS conflict or superseded binding causes Game Session to keep the candidate unusable and issue Account's idempotent retire request for that exact operation and token identity. An ambiguous timeout instead remains fail-closed and provisional while Game Session reconciles the expected binding generation plus operation identity against the authoritative binding: it retires the candidate only after proving that the CAS did not commit, and completes installation or the canonical superseded outcome when the committed operation is found. Account performs bounded orphan cleanup after the operation's lease/expiry horizon; an orphan registry record is never sufficient to make a gameplay binding admissible. Proof must cover Account success followed by response loss, confirmed binding-CAS conflict, ambiguous CAS reconciliation for both committed and uncommitted outcomes, retry with the same request ID, retry with a conflicting digest, and cleanup/reconciliation after each cross-service failure window. The protocol uses ordered durable evidence, idempotent owner-side operations, and fail-closed provisional state; it does not claim a cross-store transaction. -After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Current eligible public missing or existing non-admitting membership instead returns non-actionable `JOIN_REQUIRED` because explicit `JOIN` is unimplemented, while the target additionally requires the exact fresh membership generation/version reread. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). +After an actual client-visible edge disconnect, clients repeat their transport-specific authentication path before re-binding gameplay scope with `PLAY [realm] [character]`. Credential-bearing text clients issue the applicable `LOGIN` form (`PASSWORD` or verified-email `EMAIL_OTP`) defined by [Authentication](./system-architecture-authentication.md#login-and-session-flow); first-party WebSocket clients complete a fresh bootstrap/connect-token handshake and then use bare `LOGIN` backed by the verified connect context. This requirement does not apply while the edge connection is retained during an internal Game Session bridge or lease-owner rebind; the bounded non-edge recovery path keeps the existing `LOGIN`/`PLAY` state in that case. For either transport, target `JOIN` is required when first-time public-production membership is needed, followed by conditional realm-scoped `CHARS` or character creation unless fresh transport-local resolution supplies exactly one valid current character, and finally `PLAY`; returning members skip `JOIN` only after current `ACTIVE` membership and authority checks pass. Direct-text `JOIN` is implemented through the Account-owned writer, and current text `PLAY` validates fresh membership lifecycle/version/generation plus public entitlement/policy before returning `JOIN_REQUIRED`; full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. First-party `Join & Play` remains target-only and unavailable. Session resumption does not bypass the fresh WebSocket bootstrap/connect-token handshake. Game Session uses Coordination Redis to resolve the existing gameplay session by controller key `{tenantId, playableStateNamespaceId, characterId}`, separately validates server-derived `playableStateScope` as binding/routing evidence, and resumes it only when gameplay state permits; otherwise it starts a fresh session. A same-character target takeover fences further source commands, reconciles already-admitted source effects, and switches the binding by CAS with the next `bindingGeneration` before admitting target commands; other source sessions remain under the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). The current per-instance uniqueness implementation is a gap, and this owner rule is defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Session recovery/takeover is authorized by the gameplay binding plus current Account identity, membership, entitlement, and revocation authority; it does not require the previous backend token registry record to remain valid. When transport-specific reauthentication is required, the client must complete the applicable fresh credential/bootstrap and connect-context steps before backend calls resume. A missing or expired prior token therefore causes replacement or reauthentication, not acceptance of stale token state. > 🔗 See [Authentication & Authorization](./system-architecture-authentication.md) and [Reconnection Strategy](./system-architecture-reconnection.md) for detailed JWT format and session flow. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index aa68c015bb..198925059e 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or `JOIN`. Explicit `JOIN`/`Join & Play` and the required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance remain unimplemented/proof gaps in the current runtime. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. +The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence remains unproved end to end: current focused smoke proof is still limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path, with focused local JOIN coverage but no complete Telnet discovery/bridge, PostgreSQL/recovery, or first-party `Join & Play` proof. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unavailable as a distinct browser action. The Account membership response now exposes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. Current text `PLAY` validates the fresh identity, lifecycle, version, authority-generation, and evaluation-time evidence; for an otherwise eligible public-production target whose membership is missing or non-admitting, it obtains fresh tenant entitlement and requires `allowPublicJoin=true` before returning `JOIN_REQUIRED`, while entitlement outage or public policy denial takes precedence. Current private/playtest text `PLAY` uses `WORLD_ACCESS_DENIED` for missing or non-admitting membership and also checks the current realm grant. Current connect-token issuance has the same Account fields available on its fresh path, but a replay/result-cache hit can bypass fresh entitlement, membership, and pointer reads, and the target's independent issuance-time generation/version baseline reread and durable replay revalidation remain gaps. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; its private/playtest grant check also remains incomplete. A connect token or returning shortcut must not be treated as authorization proof. Target fresh admission still requires applicable entitlement, exact routing, and the target lifecycle/generation/version snapshot; the bounded last-known-good exception remains limited to unchanged public-production binding continuity during an entitlement-only outage after the other resume predicates pass. These implementation and proof gaps do not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. --- @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The current implementation caveat remains: explicit join is unimplemented, current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Direct-text `JOIN` is implemented locally through Account's explicit membership writer, while first-party `Join & Play` remains target-only. Current text `PLAY` validates the fresh Account membership lifecycle/version/generation evidence; for an otherwise eligible public-production target with missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`, with outage or policy denial winning. The complete browser sequence and full Telnet discovery/bridge proof remain incomplete. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current runtime has no lifecycle-state predicate: its current admission fields are `membershipExists` and `gameplayAdmissionAllowed`; `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current runtime validates pointer/visibility for this flow but not the private/playtest realm grant, so current shortcut and token behavior do not prove authorization. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current direct-text runtime has a lifecycle-state predicate and validates membership version/generation; `CHARS` and character creation use the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current connect-token issuance still does not prove the target independent issuance baseline/generation reread or private/playtest grant check, and a replay-cache hit can bypass fresh authority reads. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable while explicit `JOIN` is unimplemented. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. +The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: text `PLAY` validates fresh membership lifecycle/version/generation evidence, and for an otherwise eligible public-production target with missing or non-admitting membership it evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public policy denial takes precedence. Direct-text `JOIN` is implemented locally through the Account-owned writer, but full Telnet discovery/bridge proof remains open; first-party `Join & Play` remains unavailable. Current text `PLAY` uses `WORLD_ACCESS_DENIED` for missing or non-admitting membership on a non-public target (private/playtest) and checks its current realm grant. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - Current public-production membership is missing or `INACTIVE` in the target-only Authentication flow. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action; current text reconnect instead stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation because explicit `JOIN` is unavailable. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - Current public-production membership is missing or `INACTIVE` after the applicable routing, authority, fresh-entitlement, and public-policy gates pass. Preserve authentication and use the implemented direct-text `JOIN` writer or the target first-party `Join & Play` action; first-party `Join & Play` remains unavailable and full direct-text/Telnet completion is unproved. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The explicit `JOIN` step is target-only while current text reconnect stops with non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production target because membership repair is unavailable; private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. Direct-text `JOIN` is implemented locally through the Account-owned writer; the full Telnet discovery/bridge reconnect proof remains open. First-party `Join & Play` remains target-only. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces and explicit `Join & Play` remains unavailable, so an eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE`; an existing non-admitting response cannot be classified as `INACTIVE` by the live adapter. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients stop with the same non-actionable `JOIN_REQUIRED` fallback when repair is required. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces and first-party `Join & Play` remains unavailable, so their complete first-join/reconnect proof is not established. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; direct-text `JOIN` is implemented locally and current `PLAY` applies fresh membership lifecycle/version/generation plus fresh public entitlement/policy before `JOIN_REQUIRED`, while full Telnet bridge proof remains open. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 1b1125c071..7fd59edf9f 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,7 +10,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current first-party connect-token issuance and text `PLAY` use the fresh current Account fields `membershipExists` and `gameplayAdmissionAllowed` and admit only when both are true; an otherwise eligible public-production request with `membershipExists=false` fails closed with non-actionable `JOIN_REQUIRED`, while an existing response with `gameplayAdmissionAllowed=false` remains the established denial. The current response has no lifecycle state, so current admission is not classified as `ACTIVE` or `INACTIVE`; this boolean predicate is not proof of the target `ACTIVE` lifecycle requirement. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. Explicit `JOIN`/`Join & Play` and the required connect-token membership-authority/version rereads remain unimplemented/proof gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current text `PLAY` uses the fresh Account fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; positive admission requires `ACTIVE`, and an otherwise eligible public-production missing or non-admitting membership is classified as `JOIN_REQUIRED` only after fresh entitlement permits public joining. Entitlement outage or public policy denial takes precedence. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable and full Telnet/browser reconnect proof remains open. Current connect-token issuance receives the lifecycle/version/generation fields on its fresh path, but replay-cache hits can bypass fresh reads and the target independent issuance baseline/reread remains unproved. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current text `PLAY` behavior. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. - **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -78,8 +78,8 @@ A retained-edge upstream rebind, including a qualifying hidden Game Session rest Reconnection uses two distinct client flows: -- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its target-only `JOIN` procedure; ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Current text reconnect instead stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation because explicit `JOIN` is unavailable. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. -- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the explicit join endpoint remains unimplemented in the current runtime. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. +- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its conditional `JOIN` procedure; ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Direct-text `JOIN` is implemented locally through the Account-owned writer; full Telnet discovery/bridge reconnect proof, including PostgreSQL/recovery evidence, remains open. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. +- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the first-party join endpoint remains unavailable in the current runtime. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. @@ -89,7 +89,7 @@ A client must not infer current membership or target identity from a stale Redis ### Public membership repair during reconnect (normative) -Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. Current text reconnect stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation; first-party browser/mobile bootstrap/connect-token surfaces remain partial and the complete flow is target-only. +Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. Direct-text `JOIN` is implemented locally, but complete Telnet discovery/bridge and PostgreSQL/recovery proof remain open; first-party browser/mobile bootstrap/connect-token and `Join & Play` surfaces remain partial and target-only. Redis-backed session state allows resumable recovery when the gameplay binding is still logically valid, or a fresh login when it is not. The canonical continuity anchor, resume episode, physical TTL rules, token refresh, and transcript authority are defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Reconnection retains only this transport consequence: Redis key presence alone never authorizes resume, and a new transport never replays prior bytes. @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text clients stop with non-actionable `JOIN_REQUIRED` and no membership mutation when an otherwise eligible public-production request reports `membershipExists=false` and target-only public repair would be required. An existing response with `gameplayAdmissionAllowed=false` remains the established denial. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. +- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Direct-text `JOIN` is implemented when an otherwise eligible public-production request requires membership; current `PLAY` gates `JOIN_REQUIRED` on fresh entitlement/public policy and current lifecycle evidence. Full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. - Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. Current first-party browser/mobile bootstrap/connect-token surfaces are partial and the complete flow, including `Join & Play`, remains target-only. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/target-only conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text stops with non-actionable `JOIN_REQUIRED` and no membership mutation only when an otherwise eligible public-production request reports `membershipExists=false` and explicit `JOIN` is required. An existing response with `gameplayAdmissionAllowed=false` remains the established denial. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Direct-text `JOIN` is implemented locally, and current `PLAY` applies fresh membership lifecycle/version/generation plus fresh public entitlement/policy before `JOIN_REQUIRED`; complete Telnet bridge and recovery proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: From dfbca09785b8d13c73ede408d2cab9b09d799600 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:42:01 +1300 Subject: [PATCH 017/105] Keep denied active PLAY outside JOIN recovery --- .../game-session-service/protocols.md | 4 +- .../system-architecture-authz-route-matrix.md | 2 +- ...ystem-architecture-authz-route-matrix.yaml | 2 +- .../realm-routing-and-playable-state.md | 6 +-- .../command/text/PlayCommandHandler.java | 5 ++- .../command/text/PlayCommandHandlerTest.java | 42 +++++++++++++++++++ 6 files changed, 53 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index f857a8f28d..501de34498 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -66,7 +66,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Implemented for direct text; proof incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | +| `JOIN ` | **Direct-text command implemented; target selector form remains unavailable.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. The target `` uses the same tenant-scoped selector rules as `REALMS`; the current command accepts a bound WORLDS index or the bare world slug of a uniquely resolved current catalog world, not `tenantSlug/worldSlug`. | `JOIN demo/demo` (target) | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. Current Game Session pointer snapshots carry numeric `tenantId` and `worldSlug` but no `tenantSlug`; local `WORLDS` renders only the bare world slug, and REALMS/JOIN/PLAY resolve that slug only when the current catalog does not contain the same world slug for multiple tenants. Bound menu indices remain available from their exact browse snapshot. This bare-slug shortcut is implementation drift, not proof of the target tenant-scoped stable selector or complete Telnet flow; `REALMS demo/demo` and `JOIN demo/demo` are target examples, not current accepted command forms. ### JOIN Translation and Status diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 3c65ac600f..4129a0d2ae 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -25,7 +25,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status -- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the Account runtime response reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current Game Session `PLAY` consumer does not yet consume those fields, so the latter response is not classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Direct-text `JOIN` is implemented locally through Account's explicit writer; first-party `Join & Play`, durable unknown-outcome recovery, and end-to-end proof remain incomplete. +- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` validates fresh Account membership identity, lifecycle, version, authority generation, and evaluation time. Missing or `INACTIVE` public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` but non-admitting member is denied without JOIN advice because Account's explicit JOIN writer cannot repair that state. Policy denial and unavailable/invalid authority remain distinct outcomes. Direct-text `JOIN` is implemented locally through Account's explicit writer; first-party `Join & Play`, durable unknown-outcome recovery, and end-to-end proof remain incomplete. - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index d258bbf6ef..3225c862b4 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -393,7 +393,7 @@ required_live_check_vocabulary: - security_lock_export_action_family implementation_status: known_drift: - - direct_text_explicit_public_production_JOIN_is_implemented_locally; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_but_current_PLAY_consumer_still_uses_membershipExists_gameplayAdmissionAllowed_membershipVersion_and_evaluatedAt_without_consuming_the_new_fields; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented + - direct_text_explicit_public_production_JOIN_is_implemented_locally; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_and_current_PLAY_consumer_validates_membershipLifecycleState_membershipAuthorityGeneration_membershipVersion_and_evaluatedAt; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_INACTIVE_public_production_membership_only_after_fresh_entitlement_and_allowPublicJoin_checks; ACTIVE_non_admitting_membership_is_denied_without_JOIN_advice; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented - protected_cookie_ws_game_and_bootstrap_bare_LOGIN_are_implemented_but_non_promotable_until_Gateway_carrier_requirements_replay_marker_durability_replay_quarantine_continuity_and_Account_planned_rotation_compromise_cutover_evidence_are_complete - privileged_control_is_target_only_and_unavailable_in_current_runtime; platformAdmin_and_cross_tenant_billingAdmin_branches_requiring_it_fail_closed_while_the_support_branch_does_not_require_it - operator_mutation_rows_are_normative_target_contracts_not_current_availability; action_schema_mutationDigest_v1_vectors_and_account_issued_authorization_reference_flow_are_required_before_external_support 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 546a8ec6d4..abb3fc6e94 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. Account now exposes lifecycle-aware membership evidence (`membershipLifecycleState`, `membershipVersion`, and `membershipAuthorityGeneration`), and the explicit `JoinPublicProductionMembership` writer is implemented locally. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and stable slugs re-resolve against current catalog authority. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Game Session now invokes the Account writer from this retained scope, but full direct-text/Telnet and first-party `Join & Play` end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, separate stored catalog and pointer revisions have not converged through every consumer, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. Account now exposes lifecycle-aware membership evidence (`membershipLifecycleState`, `membershipVersion`, and `membershipAuthorityGeneration`), and the explicit `JoinPublicProductionMembership` writer is implemented locally. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and current bare world slugs re-resolve against current catalog authority. The pointer projection carries no `tenantSlug`, so WORLDS cannot yet emit the canonical `tenantSlug/worldSlug` selector and REALMS/JOIN/PLAY do not accept that stable pair; cross-tenant duplicate bare slugs are filtered rather than resolved. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Game Session now invokes the Account writer from this retained scope, but full direct-text/Telnet and first-party `Join & Play` end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, separate stored catalog and pointer revisions have not converged through every consumer, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. ## Packet 4 Status and Proof Gaps @@ -19,7 +19,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The baseline unique index is still `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`, so cross-tenant duplicate selectors are not schema-safe. | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The current pointer carries no `tenantSlug`, so the stable `tenantSlug/worldSlug` selector is not implemented; current bare world slugs are usable only when the catalog resolves them uniquely, while exact browse ordinals are snapshot-bound. The baseline unique index is still `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`, so cross-tenant duplicate selectors are not schema-safe. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Stored `catalogRevision` is separate from routing `pointerVersion`, and durable realm/namespace IDs exist, but older audit rows retain unknown revision/identity and some consumers lack the complete separated tuple. Internal sequential expected-version and prepared-cutover seams remain nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | @@ -59,7 +59,7 @@ Account-to-tenant membership is an explicit runtime substrate rather than an `ac First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. -The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; stable slug selection re-resolves current authority. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, and terminal-outcome recovery remain unproved. This is distinct from the browser/WebSocket bootstrap snapshot. +The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; the current bare-world-slug selection re-resolves current authority only when unique in the catalog. Canonical tenant-scoped stable selector resolution remains a separate gap. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, and terminal-outcome recovery remain unproved. This is distinct from the browser/WebSocket bootstrap snapshot. Gateway and Game Session preserve and validate `worldSlug`, `realmSlug`, `connectScopeId`, `connectRequestId`, `pointerVersion`, and resolved target in first-party connect context. The durable bootstrap shell stores the selector identity and is the reconnect/login/`PLAY` fallback when transient registry state is absent. Generic websocket bootstrap preserves an incoming complete bundle, repairs a runtime-only shell only from one complete current pointer, and collapses ambiguous or incomplete authority to no bundle. If a reused shell had a bundle and the repaired incoming shell does not, it is a real route change: the `BOOTSTRAP_ROUTE_CHANGED` path clears authenticated/gameplay state instead of preserving the older route. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index b9e253b8e7..2799fed925 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -811,7 +811,10 @@ private Optional validateMembershipResponse( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } if (!response.getMembershipExists() || !response.getGameplayAdmissionAllowed()) { - if (isPublicProductionRealm(selectedRealm)) { + boolean membershipRequiresExplicitJoin = + !response.getMembershipExists() + || "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); + if (isPublicProductionRealm(selectedRealm) && membershipRequiresExplicitJoin) { GetTenantEntitlementsForRuntimeResponse entitlementResponse = accountClient.getTenantEntitlementsForRuntime( Long.toString(selectedRealm.tenantId()), requestId); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index bdadbcee96..ab8b95076f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1167,6 +1167,48 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); } + @Test + void playActiveNonAdmittingMembershipDoesNotSuggestJoinOrBind() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.findCharacterByName( + context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "demo")) + .thenReturn( + Optional.of( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("7001") + .setName("demo") + .build())); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("ACTIVE") + .setMembershipVersion(2L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.world-access-denied"); + Mockito.verify(accountClient, never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); + } + @Test void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = From b16631bef09e1e9bfa4c07d1079e793908da0acc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:46:54 +1300 Subject: [PATCH 018/105] Fence stale player targets and classify membership denial --- .../system-architecture-protocol-bridging.md | 2 +- .../system-architecture-reconnection.md | 2 +- .../player-access-and-session.md | 10 +- .../command/text/GameplayWorldCatalog.java | 58 ++++++++++ .../command/text/PlayCommandHandler.java | 2 +- .../text/PlayerCommandHistoryRecorder.java | 3 +- .../command/text/WorldsCommandHandler.java | 21 +++- .../command/text/PlayCommandHandlerTest.java | 72 ++++++++++++ .../text/WorldsCommandHandlerTest.java | 104 +++++++++++++++++- 9 files changed, 254 insertions(+), 20 deletions(-) diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 198925059e..7a0bac0995 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. Direct-text `JOIN` is implemented locally through the Account-owned writer; the full Telnet discovery/bridge reconnect proof remains open. First-party `Join & Play` remains target-only. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. Direct-text `JOIN` is implemented locally through the Account-owned writer; the full Telnet discovery/bridge reconnect proof remains open. First-party `Join & Play` remains target-only. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session currently suppresses private retained-context replay and renders a fresh authoritative `LOOK` and configured prompt on the reconnect path; it does not treat a connect context alone as replay authorization. Current deliberate `LOGOUT` fails closed with `LOGOUT_UNAVAILABLE` without terminating the binding until the durable episode fence exists. The target permits private context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Generation/termination enforcement, live Telnet proof, and a safe private replay path remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 7fd59edf9f..74996ce42b 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -224,7 +224,7 @@ Clients must also treat pre-disconnect input and output as non-resumable transpo The close reason never establishes that command outcome. The current gameplay-command status surfaces are restricted to authorized operator or internal-service clients; an authorized client holding `{tenantId, gameInstanceId, commandId}` may reconcile that tuple, but ordinary players cannot use knowledge of `commandId` to query it. A future caller-bound first-party status route may expose the same authoritative record only after it binds the requested tuple to the immutable ingress account, character, or session identity required by the owning [command-outcome contract](./system-architecture-tick-execution-flows.md#command-outcome-status-surface-required). Until that route exists, ordinary browser and classic line clients receive later state reconstruction, must not treat any retryable close as proof that the last command failed, and must not recreate the input automatically. -- current implementation persists ordered `resume_transcript_entry` rows and can best-effort freshly render available retained context after a binding-checked eligible reconnect. Current first-party post-logout suppression is not enforced, so retained context can still replay after `LOGOUT`. Target replay eligibility requires the exact current `resumeContextGeneration` and a non-terminated semantic-context episode; under that target, explicit gameplay `LOGOUT` durably terminates the episode before acknowledgement and prevents later replay of its private context. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) records the entry, cache, presentation, and current proof consequences; +- current implementation persists ordered `resume_transcript_entry` rows but suppresses private retained-context replay on reconnect and after attempted `LOGOUT`; it can render a fresh authoritative `LOOK` and prompt after successful `PLAY`. The current deliberate `LOGOUT` command returns `LOGOUT_UNAVAILABLE` without terminating the binding because the durable episode fence is absent. Target replay eligibility requires the exact current `resumeContextGeneration` and a non-terminated semantic-context episode; under that target, explicit gameplay `LOGOUT` durably terminates the episode before acknowledgement and prevents later replay of its private context. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) records the entry, cache, presentation, and current proof consequences; - the context may repeat output the client already displayed or omit output that was not retained or available. It is not a delivery acknowledgement, exact missed-message list, command history, or transcript archive; Redis may cache it but is not authoritative, and physical deletion may complete asynchronously; - then current reconnect flow obtains a fresh authoritative `LOOK` and applies the owner-defined prompt behavior. The local consequence is exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero when either is disabled; prompt restoration and duplicate-prevention proof remain current gaps recorded in [Input, Output and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status). This reconstruction defines current state; retained context is narrative orientation only. 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 1b304176ba..b7222dd9b9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,7 +34,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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. Generic payment scaffolds still retain provider-mutating drift. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. Explicit JOIN exists locally through Account's public-production writer, but this does not prove the direct text-client path; the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Missing or `INACTIVE` public membership receives `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` non-admitting member is denied without JOIN advice, and unavailable evidence remains retryable. Explicit JOIN exists locally through Account's public-production writer, but this does not prove the direct text-client path; the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025. | | `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, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. 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. | | `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 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 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.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) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | @@ -103,9 +103,9 @@ The lifecycle classes are deliberately distinct: - Unexpected disconnect may mark the session suspended/reconnect-eligible, preserve bounded replay state, and allow later `PLAY` to request recovery. - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. -- Deliberate `LOGOUT` is termination, not suspension. It deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Logout before login is a bounded in-band failure. +- Target deliberate `LOGOUT` is termination, not suspension. Once its durable episode fence exists, it deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Current `LOGOUT_UNAVAILABLE` performs none of those terminal mutations; logout before login is a bounded in-band failure. -Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. The current first-party connect-context path still reads and replays retained context after a post-logout `LOGIN` plus `PLAY`, which has not yet converged with the target rule that deliberate logout is not a recovery replay path. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. +Replay projection is separate from retained transcript storage. Current Game Session suppresses private retained-context reads on reconnect and renders fresh `LOOK` after accepted `PLAY`; unexpected transport loss remains reconnect-eligible for fresh authority checks, not private replay. Deliberate `LOGOUT` currently fails closed with `LOGOUT_UNAVAILABLE` and does not clear an active binding because durable terminal `resumeContextGeneration` evidence is absent. Target successful logout terminates that episode before acknowledgement; retaining transcript rows never makes them replay-eligible. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Current private replay suppression does not read retained output from partial shells. ### Reconnect and Continuity @@ -113,7 +113,7 @@ For generic Telnet and WebSocket, reconnect uses current identity and current Ac Current durable reconnect rows remain game-instance-keyed, so namespace-key migration is partial. Redis may cache them but is not authoritative gameplay state. The connection-local TCP Proxy input buffer is distinct from durable context and supports only a still-established edge rebind; it is never durable replay of input, transport bytes, frames, or unsent transient output. Current implementation/proof of the bounded reconnect context and prompt behavior remains partial; the canonical continuity contract is [Reconnection](../../architecture/system-architecture-reconnection.md). -First-party `/ws/game/**` has a separate but partial authority path. Account exposes player bootstrap and connect-token issuance; Gateway validates and forwards signed connect context; Game Session consumes verified identity at bare first-party `LOGIN` and keeps `PLAY` as the binding step. The current screen-buffer projection restores retained context and fresh redraw, but resume-window enforcement, prompt proof, and post-logout suppression remain incomplete. The authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +First-party `/ws/game/**` has a separate but partial authority path. Account exposes player bootstrap and connect-token issuance; Gateway validates and forwards signed connect context; Game Session consumes verified identity at bare first-party `LOGIN` and keeps `PLAY` as the binding step. The current reconnect path suppresses private screen-buffer/transcript replay and renders fresh `LOOK` after accepted `PLAY`; resume-window enforcement, durable generation/terminal-episode proof, and live prompt/reconnect proof remain incomplete. The authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Gateway owns the downstream `/ws/game/**` socket and a stable edge transport session id. Its custom bridge can rebind an upstream Game Session socket after bounded loss without immediately dropping the player socket, reusing that edge id. Focused proofs cover abrupt upstream loss, a Game Session-like process bounce with isolated Reactor resources, and post-restart Game Logic commands (`LOOK`, movement-derived room context, and communication inputs) against shared state. Edge-visible retry taxonomy is reserved for actual edge-route loss or exhausted rebind windows; this does not guarantee in-flight command or byte replay. @@ -155,7 +155,7 @@ Account authority proof covers account-first tenantless bootstrap authentication - The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; `past_due` is currently gameplay-available and public-join-eligible. Durable `purchase_entitlement` fulfillment/revocation is also absent. - Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam currently accept parameterized credentials, while public non-proxy `/ws/game/**` requires a verified connect-token context and bare `LOGIN`. - Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. -- The first-party post-logout path still replays retained transcript context even though generic fresh login does not; that replay-projection mismatch must converge without treating durable transcript retention as reconnect eligibility. +- Private first-party replay is currently suppressed even if retained transcript rows remain. A safe eligible replay path and terminal `resumeContextGeneration` fence are not implemented; `LOGOUT_UNAVAILABLE` must not be mistaken for a completed logout. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index e8c6fdc7f8..e95a1d6751 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -650,6 +650,64 @@ public void requireUniqueVisiblePublicProductionRealm( } } + /** + * Re-reads the current routing authority and requires the selected realm to remain the exact + * target that was resolved from the earlier catalog snapshot. + * + *

This is intentionally a read-before-admission fence, not an atomic read/bind operation. The + * caller must invoke it immediately before any Account or Entity admission read. + */ + public boolean matchesCurrentAdmissionPointer(WorldView expectedWorld, RealmView expectedRealm) { + if (expectedWorld == null || expectedRealm == null) { + return false; + } + if (authorityPointerSupplier != null) { + List pointers = authorityPointerSupplier.get(); + if (pointers == null + || pointers.stream().anyMatch(pointer -> !hasCompleteAuthorityPointer(pointer))) { + return false; + } + if (pointers.stream() + .filter(pointer -> pointer.tenantId() == expectedRealm.tenantId()) + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .count() + != 1L) { + return false; + } + return pointers.stream() + .filter(pointer -> matchesExpectedTarget(expectedWorld, expectedRealm, pointer)) + .count() + == 1L; + } + + CatalogState currentState = readCatalogState(); + if (currentState.publicProductionCounts().getOrDefault(expectedRealm.tenantId(), 0L) != 1L) { + return false; + } + List currentWorlds = currentState.worlds(); + return currentWorlds.stream() + .filter(world -> sameWorld(expectedWorld, world)) + .flatMap(world -> world.realms().stream()) + .filter(realm -> realm.equals(expectedRealm)) + .count() + == 1L; + } + + private static boolean matchesExpectedTarget( + WorldView expectedWorld, + RealmView expectedRealm, + GameplayAdmissionPointerSnapshot currentPointer) { + return Objects.equals(expectedWorld.slug(), currentPointer.worldSlug()) + && Objects.equals(expectedWorld.displayName(), currentPointer.worldDisplayName()) + && toRealmView(currentPointer).equals(expectedRealm); + } + + private static boolean sameWorld(WorldView expectedWorld, WorldView currentWorld) { + return Objects.equals(expectedWorld.slug(), currentWorld.slug()) + && Objects.equals(expectedWorld.displayName(), currentWorld.displayName()); + } + private List worldEntries() { CatalogState catalogState = readCatalogState(); List worlds = discoverableWorlds(catalogState); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 2799fed925..f52bf56374 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -316,7 +316,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); String selectedTenantTag = Long.toString(selectedRealm.tenantId()); - if (!gameplayWorldCatalog.hasValidPublicProductionRealm(selectedRealm.tenantId())) { + if (!gameplayWorldCatalog.matchesCurrentAdmissionPointer(selectedWorld, selectedRealm)) { return admissionPointerUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java index 418b3c43dd..b3931ba3e0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java @@ -50,7 +50,8 @@ public void record( return; } - // PLAY establishes its character identity during dispatch; LOGOUT clears it there. + // PLAY establishes its character identity during dispatch. Successful LOGOUT would clear it, + // but the current command fails closed before changing the binding. Optional historyContext = contextAfter .filter(this::hasHistoryScope) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 09a7144bcb..a4294c5913 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -383,11 +383,16 @@ private NonPublicRealmAuthorization authorizeNonPublicRealm( ? NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE : NonPublicRealmAuthorization.DENIED; } + if (!isValidMembershipAuthoritySnapshot(membershipResponse, sessionContext, realm)) { + return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; + } if (!membershipResponse.getMembershipExists() - || !membershipResponse.getGameplayAdmissionAllowed() || "INACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { return NonPublicRealmAuthorization.ENROLLMENT_REQUIRED; } + if (!membershipResponse.getGameplayAdmissionAllowed()) { + return NonPublicRealmAuthorization.MEMBERSHIP_DENIED; + } if (!isValidActiveMembership(membershipResponse, sessionContext, realm)) { return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; } @@ -520,6 +525,7 @@ private boolean isAuthorityUnavailable(String code) { private enum NonPublicRealmAuthorization { AUTHORIZED, DENIED, + MEMBERSHIP_DENIED, ENROLLMENT_REQUIRED, AUTHORITY_UNAVAILABLE, ENTITLEMENT_UNAVAILABLE @@ -729,7 +735,8 @@ public CharacterBrowseResult browseCharacters( GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); if (!worldCatalog.hasValidPublicProductionRealm(catalogSnapshot, world) - || !hasCompleteSelectedRealmPointerEvidence(realm)) { + || !hasCompleteSelectedRealmPointerEvidence(realm) + || !worldCatalog.matchesCurrentAdmissionPointer(world, realm)) { return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } @@ -808,12 +815,14 @@ private CharacterBrowseAuthorization authorizePublicCharacterBrowse( return entitlementAuthorization.authorization(); } if (!membershipResponse.getMembershipExists() - || !membershipResponse.getGameplayAdmissionAllowed() - || !"ACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { + || "INACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { return entitlementAuthorization.allowPublicJoin() ? CharacterBrowseAuthorization.JOIN_REQUIRED : CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; } + if (!membershipResponse.getGameplayAdmissionAllowed()) { + return CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; + } if (!isValidActiveMembership(membershipResponse, sessionContext, realm)) { return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; } @@ -864,7 +873,7 @@ private CharacterBrowseAuthorization mapNonPublicCharacterAuthorization( NonPublicRealmAuthorization authorization) { return switch (authorization) { case AUTHORIZED -> CharacterBrowseAuthorization.AUTHORIZED; - case DENIED -> CharacterBrowseAuthorization.DENIED; + case DENIED, MEMBERSHIP_DENIED -> CharacterBrowseAuthorization.DENIED; case ENROLLMENT_REQUIRED -> CharacterBrowseAuthorization.NON_PUBLIC_ENROLLMENT_REQUIRED; case AUTHORITY_UNAVAILABLE -> CharacterBrowseAuthorization.AUTH_UNAVAILABLE; case ENTITLEMENT_UNAVAILABLE -> CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE; @@ -894,7 +903,7 @@ private boolean isValidMembershipAuthoritySnapshot( return false; } if ("ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState())) { - return response.getGameplayAdmissionAllowed(); + return true; } return "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) && !response.getGameplayAdmissionAllowed(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index ab8b95076f..c9217b4310 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -8,6 +8,8 @@ import java.time.Instant; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; @@ -43,6 +45,10 @@ class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; + private static final UUID ADMISSION_REALM_ID = + UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final UUID ADMISSION_NAMESPACE_ID = + UUID.fromString("00000000-0000-0000-0000-000000000002"); private final SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); private final SessionContextService sessionContextService = @@ -420,6 +426,53 @@ void playFailsClosedWhenTenantHasNoPublicProductionRealm() { Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); } + @Test + void playRejectsPointerRevisionCutoverBeforeAdmissionReads() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot pointerA = admissionPointer(1L); + GameplayAdmissionPointerSnapshot pointerB = admissionPointer(2L); + AtomicInteger pointerReads = new AtomicInteger(); + when(authorityService.listPointers()) + .thenAnswer( + invocation -> + pointerReads.getAndIncrement() == 0 ? List.of(pointerA) : List.of(pointerB)); + GameplayWorldCatalog authorityBackedCatalog = new GameplayWorldCatalog(authorityService); + PlayCommandHandler authorityBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + authorityBackedCatalog, + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + connectScopeSessionStore); + SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + authorityBackedHandler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(pointerReads).hasValue(2); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = @@ -1975,6 +2028,25 @@ private static GameplayCatalogProperties.World world( return world; } + private static GameplayAdmissionPointerSnapshot admissionPointer(long pointerVersion) { + return new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 22L, + 1L, + pointerVersion, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + ADMISSION_REALM_ID, + ADMISSION_NAMESPACE_ID); + } + private static GameplayCatalogProperties.Realm realm( String slug, String displayName, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index ebeb9fdc84..97c3c7a84f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; @@ -32,6 +33,10 @@ import org.mockito.Mockito; class WorldsCommandHandlerTest { + private static final UUID ADMISSION_REALM_ID = + UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final UUID ADMISSION_NAMESPACE_ID = + UUID.fromString("00000000-0000-0000-0000-000000000002"); private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = @@ -490,9 +495,23 @@ void browseCharactersFailsClosedForUnknownPublicMembershipLifecycleWithoutReadin } @Test - void - browseCharactersFailsClosedForActivePublicMembershipWithoutAdmissionWithoutReadingEntityRoster() { - assertPublicMembershipFailsClosed(publicMembership(true, false, 1L, 1L, "ACTIVE")); + void browseCharactersDeniesActivePublicMembershipWithoutAdmissionWithoutReadingEntityRoster() { + GameplayCatalogProperties properties = publicProductionProperties(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicMembership(true, false, 1L, 1L, "ACTIVE")); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.failure( + "PUBLIC_PRODUCTION_ADMISSION_DENIED")); + Mockito.verifyNoInteractions(entityManagementClient); } @Test @@ -617,6 +636,35 @@ void browseCharactersDeniesRevokedPrivateMembershipBeforeReadingEntityRoster() { Mockito.anyString()); } + @Test + void browseRealmsOmitsActivePrivateMembershipWithoutAdmissionWhileCharactersDeny() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicMembership(true, false, 1L, 1L, "ACTIVE")); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().realms()).isEmpty()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("WORLD_ACCESS_DENIED")); + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + @Test void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoster() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -681,6 +729,34 @@ void browseCharactersRejectsMultiplePublicProductionCardinalityWithExplicitRealm Mockito.verifyNoInteractions(accountClient, entityManagementClient); } + @Test + void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot pointerA = admissionPointer(1L); + GameplayAdmissionPointerSnapshot pointerB = admissionPointer(2L); + AtomicInteger pointerReads = new AtomicInteger(); + Mockito.when(authorityService.listPointers()) + .thenAnswer( + invocation -> + pointerReads.getAndIncrement() == 0 ? List.of(pointerA) : List.of(pointerB)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + new GameplayWorldCatalog(authorityService), + entityManagementClient, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + assertThat(pointerReads).hasValue(2); + Mockito.verifyNoInteractions(entityManagementClient); + } + @Test void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() { UUID realmId = UUID.randomUUID(); @@ -919,8 +995,7 @@ void authenticatedBrowseOmitsPrivateRealmForNonMember() { Mockito.when( accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder().setMembershipExists(false).build()); + .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING")); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.RealmBrowseResult result = @@ -1543,6 +1618,25 @@ private GameplayAdmissionPointerSnapshot authorityPointer( UUID.randomUUID()); } + private GameplayAdmissionPointerSnapshot admissionPointer(long gameInstanceId) { + return new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 22L, + gameInstanceId, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + ADMISSION_REALM_ID, + ADMISSION_NAMESPACE_ID); + } + private GameplayCatalogProperties publicProductionProperties() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("demo", 22L, 1L, false))); From a6964b99bd8fd4114c2c1f1b72dd6f96884ced96 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 05:45:09 +1300 Subject: [PATCH 019/105] Fail closed on player authority outages and ambiguous realms --- .../command/text/GameplayWorldCatalog.java | 74 ++++++++++++++----- .../command/text/PlayCommandHandler.java | 26 ++++++- .../command/text/WorldsCommandHandler.java | 38 ++++++++-- .../WorldsTextCommandDispatchHandler.java | 2 + .../GameSessionWebSocketHandler.java | 12 +-- .../text/GameplayWorldCatalogTest.java | 29 ++++++++ .../command/text/PlayCommandHandlerTest.java | 40 ++++++++++ .../text/WorldsCommandHandlerTest.java | 46 ++++++++++++ .../GameSessionWebSocketHandlerTest.java | 17 +++++ 9 files changed, 251 insertions(+), 33 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index e95a1d6751..266a8b4e19 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -249,9 +249,9 @@ public Optional resolveWorldFromAuthoritySnapshot(String selector) { return resolveWorld(selector, visibleWorlds, visibleWorlds) .filter(world -> hasValidPublicProductionRealm(world, catalogState)); } - List pointers = authorityPointerSupplier.get(); + List pointers = readAuthorityPointers(); if (pointers == null) { - throw new AuthorityPointerUnavailableException( + throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); } for (GameplayAdmissionPointerSnapshot pointer : pointers) { @@ -288,9 +288,11 @@ public Optional resolveRealm(WorldView world, String selector) { return Optional.empty(); } String normalized = selector.trim().toLowerCase(Locale.ROOT); - return visibleRealms(world).stream() - .filter(realm -> normalized.equals(realm.slug().toLowerCase(Locale.ROOT))) - .findFirst(); + List matches = + visibleRealms(world).stream() + .filter(realm -> normalized.equals(realm.slug().toLowerCase(Locale.ROOT))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } // Admission may resolve hidden realms, but callers must still perform membership and grant @@ -300,10 +302,12 @@ Optional resolveRealmForAdmission(WorldView world, String selector) { return Optional.empty(); } String normalized = selector.trim().toLowerCase(Locale.ROOT); - return world.realms().stream() - .filter(realm -> realm != null && realm.slug() != null && !realm.slug().isBlank()) - .filter(realm -> normalized.equals(realm.slug().toLowerCase(Locale.ROOT))) - .findFirst(); + List matches = + world.realms().stream() + .filter(realm -> realm != null && realm.slug() != null && !realm.slug().isBlank()) + .filter(realm -> normalized.equals(realm.slug().toLowerCase(Locale.ROOT))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } boolean hasRealmForAdmission(WorldView world, String selector) { @@ -594,9 +598,9 @@ public List visibleWorldsFromAuthoritySnapshot() { if (authorityPointerSupplier == null) { return visibleWorlds(); } - List pointers = authorityPointerSupplier.get(); + List pointers = readAuthorityPointers(); if (pointers == null) { - throw new AuthorityPointerUnavailableException( + throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); } for (GameplayAdmissionPointerSnapshot pointer : pointers) { @@ -623,9 +627,9 @@ public void requireUniqueVisiblePublicProductionRealm( throw new AuthorityPointerUnavailableException( "Authoritative public-production realm identity is unavailable"); } - List pointers = authorityPointerSupplier.get(); + List pointers = readAuthorityPointers(); if (pointers == null) { - throw new AuthorityPointerUnavailableException( + throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); } for (GameplayAdmissionPointerSnapshot pointer : pointers) { @@ -662,7 +666,7 @@ public boolean matchesCurrentAdmissionPointer(WorldView expectedWorld, RealmView return false; } if (authorityPointerSupplier != null) { - List pointers = authorityPointerSupplier.get(); + List pointers = readAuthorityPointers(); if (pointers == null || pointers.stream().anyMatch(pointer -> !hasCompleteAuthorityPointer(pointer))) { return false; @@ -786,9 +790,9 @@ private CatalogState readCatalogState() { List worlds = normalizeWorlds(worldSupplier.get()); return new CatalogState(worlds, publicProductionCounts(worlds)); } - List pointers = authorityPointerSupplier.get(); + List pointers = readAuthorityPointers(); if (pointers == null) { - throw new AuthorityPointerUnavailableException( + throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); } return catalogStateFromPointers(pointers); @@ -799,6 +803,26 @@ private static CatalogState catalogStateFromPointers( return new CatalogState(toWorlds(pointers), publicProductionCountsFromPointers(pointers)); } + private List readAuthorityPointers() { + if (authorityPointerSupplier == null) { + throw new AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + try { + List pointers = authorityPointerSupplier.get(); + if (pointers == null) { + throw new AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + return pointers; + } catch (AuthorityPointerReadUnavailableException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable", ex); + } + } + private Map publicProductionCounts(List worlds) { Map counts = new LinkedHashMap<>(); for (WorldView world : worlds) { @@ -865,7 +889,8 @@ private static List toWorlds(List p world.tenantIds.add(pointer.tenantId()); world .realmsBySlug - .computeIfAbsent(pointer.realmSlug(), ignored -> new ArrayList<>()) + .computeIfAbsent( + pointer.realmSlug().toLowerCase(Locale.ROOT), ignored -> new ArrayList<>()) .add(pointer); } return normalizeWorlds( @@ -913,12 +938,25 @@ private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnaps && !pointer.characterCreationPolicy().isBlank(); } - public static final class AuthorityPointerUnavailableException extends RuntimeException { + public static class AuthorityPointerUnavailableException extends RuntimeException { public AuthorityPointerUnavailableException(String message) { super(message); } } + /** Indicates the authority read itself failed, distinct from malformed or ambiguous data. */ + public static final class AuthorityPointerReadUnavailableException + extends AuthorityPointerUnavailableException { + public AuthorityPointerReadUnavailableException(String message) { + super(message); + } + + public AuthorityPointerReadUnavailableException(String message, RuntimeException cause) { + super(message); + initCause(cause); + } + } + private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { return new RealmView( pointer.realmSlug(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index f52bf56374..93cc6116b8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -178,8 +178,20 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } ResolvedPlaySelection requestedSelection = maybeSelection.orElseThrow(); - GameplayWorldCatalog.DiscoverySnapshot currentCatalog = - gameplayWorldCatalog.readDiscoverySnapshot(); + GameplayWorldCatalog.DiscoverySnapshot currentCatalog; + try { + currentCatalog = gameplayWorldCatalog.readDiscoverySnapshot(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return failure( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE, + "error.play.authority-unavailable", + Map.of(), + tenantTag, + null, + null, + ex); + } WorldSelectorResolution worldSelection = resolvePlayWorld(context, requestedSelection.worldSelector(), currentCatalog); if (worldSelection instanceof WorldSelectorResolution.Unavailable) { @@ -316,7 +328,15 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); String selectedTenantTag = Long.toString(selectedRealm.tenantId()); - if (!gameplayWorldCatalog.matchesCurrentAdmissionPointer(selectedWorld, selectedRealm)) { + boolean currentPointerMatches; + try { + currentPointerMatches = + gameplayWorldCatalog.matchesCurrentAdmissionPointer(selectedWorld, selectedRealm); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return admissionPointerUnavailableFailure( + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); + } + if (!currentPointerMatches) { return admissionPointerUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index a4294c5913..c3b7648663 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -112,7 +112,12 @@ public RealmBrowseResult browseRealms( if (parsedSessionId.getAsLong() != sessionContext.sessionId()) { return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } - GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot = worldCatalog.readDiscoverySnapshot(); + GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot; + try { + catalogSnapshot = worldCatalog.readDiscoverySnapshot(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); if (selection instanceof WorldSelectorResolution.Invalid) { @@ -571,7 +576,13 @@ public JoinMembershipResult joinPublicProductionMembership( } catch (NumberFormatException ex) { return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - if (!worldCatalog.hasValidPublicProductionRealm(tenantId)) { + boolean hasPublicProductionRealm; + try { + hasPublicProductionRealm = worldCatalog.hasValidPublicProductionRealm(tenantId); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + if (!hasPublicProductionRealm) { return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } String requestId = joinScope.requestId(); @@ -695,7 +706,13 @@ public CharacterBrowseResult browseCharacters( if (parsedSessionId.getAsLong() != sessionContext.sessionId()) { return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } - GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot = worldCatalog.readDiscoverySnapshot(); + GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot; + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; + try { + catalogSnapshot = worldCatalog.readDiscoverySnapshot(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); if (selection instanceof WorldSelectorResolution.Invalid) { @@ -708,8 +725,11 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = - worldCatalog.readRealmDiscoverySnapshot(world); + try { + currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } RealmSelectorResolution realmSelection = resolveLobbyRealm(sessionContext, world, realmSelector, currentRealmCatalog); if (realmSelection instanceof RealmSelectorResolution.Unavailable) { @@ -734,9 +754,15 @@ public CharacterBrowseResult browseCharacters( } GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); + boolean currentPointerMatches; + try { + currentPointerMatches = worldCatalog.matchesCurrentAdmissionPointer(world, realm); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } if (!worldCatalog.hasValidPublicProductionRealm(catalogSnapshot, world) || !hasCompleteSelectedRealmPointerEvidence(realm) - || !worldCatalog.matchesCurrentAdmissionPointer(world, realm)) { + || !currentPointerMatches) { return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index 00b73d1308..c38a33afa0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -59,6 +59,8 @@ private TextCommandInterpretationResult handleWorlds(TextCommandDispatchRequest } catch (IllegalArgumentException ex) { return errorResult( "INVALID_ARGUMENT", "Transport session is unavailable. Reconnect and try again."); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return errorResult("AUTH_UNAVAILABLE", "World list is temporarily unavailable."); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return errorResult("AUTH_UNAVAILABLE", "World list is temporarily unavailable."); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index f53246bcbf..a56d0f7104 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -180,17 +180,17 @@ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { + String sessionId = resolveTransportSessionId(session); + if (!StringUtils.hasText(sessionId)) { + session.sendMessage(new TextMessage("ERROR INVALID_ARGUMENT sessionId header required")); + session.close(CloseStatus.BAD_DATA); + return; + } TextCommand command = parser.parse(message.getPayload()); try (CombinedLoggingContext ignored = command.type() == TextCommandType.LOGOUT ? openRuntimeLoggingContext(session) : openLoggingContext(session)) { - String sessionId = resolveTransportSessionId(session); - if (!StringUtils.hasText(sessionId)) { - session.sendMessage(new TextMessage("ERROR INVALID_ARGUMENT sessionId header required")); - session.close(CloseStatus.BAD_DATA); - return; - } boolean requiresSoloTick = parseSoloTick(session); if (command.type() == TextCommandType.NOOP) { return; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 09f209d14c..22dfc0abe8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -67,6 +67,35 @@ void visibleWorldsGroupsMultipleRealmsForTheSameTenantWorldSlug() { .containsExactly("production", "event"); } + @Test + void visibleWorldsTreatsRealmSlugCaseCollisionsAsAmbiguous() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), + pointer("demo", "Demo World", "PRODUCTION", "Other Live Realm", 1L, 12L, 8L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); + assertThat(catalog.publicProductionRealmCardinality(1L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + } + + @Test + void pointerReadFailureIsDistinctFromMalformedOrAmbiguousAuthority() { + when(authorityService.listPointers()) + .thenThrow(new IllegalStateException("authority down")) + .thenReturn(null); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::readDiscoverySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); + assertThatThrownBy(catalog::readDiscoverySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); + } + @Test void reverseRuntimeLookupFailsClosedWhenMultipleVisibleRealmsShareRuntimeTarget() { when(authorityService.listPointers()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index c9217b4310..4d851651ee 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -473,6 +473,46 @@ void playRejectsPointerRevisionCutoverBeforeAdmissionReads() { scriptEventPublisher); } + @Test + void playMapsPointerAuthorityReadFailureBeforeAccountOrEntityAdmissionReads() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + when(authorityService.listPointers()).thenThrow(new IllegalStateException("authority down")); + PlayCommandHandler authorityBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authorityService), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + connectScopeSessionStore); + SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + authorityBackedHandler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 97c3c7a84f..bb68cfe598 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1585,6 +1585,52 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { Mockito.verifyNoInteractions(entityManagementClient); } + @Test + void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEntityCalls() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + AtomicReference unavailable = new AtomicReference<>(false); + Mockito.when(authorityService.listPointers()) + .thenAnswer( + invocation -> { + if (unavailable.get()) { + throw new IllegalStateException("pointer authority unavailable"); + } + return List.of(authorityPointer("demo", "production", 22L, 1L, true)); + }); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-a") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + new GameplayWorldCatalog(authorityService), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + Mockito.clearInvocations(accountClient, entityManagementClient); + unavailable.set(true); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + + Mockito.doReturn(null).when(authorityService).listPointers(); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + private WorldsCommandHandler authenticatedHandler( GameplayCatalogProperties properties, AccountClient accountClient) { return new WorldsCommandHandler( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index d5f2dfb33c..e1113fffd1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -731,6 +731,23 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority && context.pointerVersion() == 0L)); } + @Test + void missingTransportSessionIdRejectsMalformedCommandBeforeParsing() throws Exception { + when(session.getAttributes()).thenReturn(Map.of()); + when(parser.parse("GET 2147483648 Torch")).thenThrow(new NumberFormatException("overflow")); + + handler.handleMessage(session, new TextMessage("GET 2147483648 Torch")); + + verify(session) + .sendMessage( + argThat( + message -> + "ERROR INVALID_ARGUMENT sessionId header required" + .equals(message.getPayload()))); + verify(session).close(CloseStatus.BAD_DATA); + verify(parser, never()).parse(any()); + } + @Test void handleMessageDoesNotAppendScreenBufferForNormalizedLoggedInShell() throws Exception { TextCommand command = new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"); From 5d31622651329fcf45c4aa5e5d811c293af63088 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:13:37 +1300 Subject: [PATCH 020/105] Keep direct-text world selections tenant-qualified --- .../realm-routing-and-playable-state.md | 4 +- .../command/text/GameplayWorldCatalog.java | 73 ++-- .../command/text/PlayCommandHandler.java | 13 +- .../command/text/WorldsCommandHandler.java | 62 +++- .../DirectTextConnectScopeSessionStore.java | 317 +++++++++++++++--- ...irectTextConnectScopeSessionStoreTest.java | 50 ++- .../text/GameplayWorldCatalogTest.java | 25 +- .../command/text/PlayCommandHandlerTest.java | 176 ++++++++++ .../text/WorldsCommandHandlerTest.java | 129 ++++++- ...irectTextConnectScopeSessionStoreTest.java | 116 +++++-- 10 files changed, 828 insertions(+), 137 deletions(-) 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 abb3fc6e94..dee494b6a1 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. Account now exposes lifecycle-aware membership evidence (`membershipLifecycleState`, `membershipVersion`, and `membershipAuthorityGeneration`), and the explicit `JoinPublicProductionMembership` writer is implemented locally. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and current bare world slugs re-resolve against current catalog authority. The pointer projection carries no `tenantSlug`, so WORLDS cannot yet emit the canonical `tenantSlug/worldSlug` selector and REALMS/JOIN/PLAY do not accept that stable pair; cross-tenant duplicate bare slugs are filtered rather than resolved. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Game Session now invokes the Account writer from this retained scope, but full direct-text/Telnet and first-party `Join & Play` end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, separate stored catalog and pointer revisions have not converged through every consumer, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. Account now exposes lifecycle-aware membership evidence (`membershipLifecycleState`, `membershipVersion`, and `membershipAuthorityGeneration`), and the explicit `JoinPublicProductionMembership` writer is implemented locally. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and current bare world slugs re-resolve against current catalog authority. The pointer projection carries no `tenantSlug`, so WORLDS cannot yet emit the canonical `tenantSlug/worldSlug` selector and REALMS/JOIN/PLAY do not accept that stable pair; cross-tenant duplicate world slugs remain visible as distinct tenant-bound ordinal choices, while ambiguous bare slugs fail closed. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Game Session now invokes the Account writer from this retained scope, but full direct-text/Telnet and first-party `Join & Play` end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, separate stored catalog and pointer revisions have not converged through every consumer, the durable routing key has not converged to `{tenantId, realmId}`, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. ## Packet 4 Status and Proof Gaps @@ -19,7 +19,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The current pointer carries no `tenantSlug`, so the stable `tenantSlug/worldSlug` selector is not implemented; current bare world slugs are usable only when the catalog resolves them uniquely, while exact browse ordinals are snapshot-bound. The baseline unique index is still `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`, so cross-tenant duplicate selectors are not schema-safe. | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The current pointer carries no `tenantSlug`, so the stable `tenantSlug/worldSlug` selector is not implemented; current bare world slugs are usable only when the catalog resolves them uniquely, while exact browse ordinals are snapshot-bound. The V2 pointer selector index is tenant-qualified, while durable `{tenantId, realmId}` identity and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Stored `catalogRevision` is separate from routing `pointerVersion`, and durable realm/namespace IDs exist, but older audit rows retain unknown revision/identity and some consumers lack the complete separated tuple. Internal sequential expected-version and prepared-cutover seams remain nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 266a8b4e19..2d2a91bcc1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -115,9 +115,11 @@ public Optional resolveStableWorld(DiscoverySnapshot snapshot, String return Optional.empty(); } String normalized = selector.trim().toLowerCase(Locale.ROOT); - return snapshot.visibleWorlds().stream() - .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) - .findFirst(); + List matches = + snapshot.visibleWorlds().stream() + .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } public Optional resolveSnapshotOrdinal( @@ -132,14 +134,12 @@ public Optional resolveSnapshotOrdinal( if (matches.size() != 1) { return Optional.empty(); } - return current.visibleWorlds().stream() - .filter(world -> world.slug().equalsIgnoreCase(originatingTarget.worldSlug())) - .filter( - world -> - world.realms().stream() - .filter(RealmView::visible) - .anyMatch(realm -> realm.tenantId() == originatingTarget.tenantId())) - .findFirst(); + List worldMatches = + current.visibleWorlds().stream() + .filter(world -> world.slug().equalsIgnoreCase(originatingTarget.worldSlug())) + .filter(world -> worldTenantId(world) == originatingTarget.tenantId()) + .toList(); + return worldMatches.size() == 1 ? Optional.of(worldMatches.getFirst()) : Optional.empty(); } public static boolean isOrdinalSelector(String selector) { @@ -278,9 +278,11 @@ private Optional resolveWorld( // Fall back to slug matching. } String normalized = selector.trim().toLowerCase(Locale.ROOT); - return visibleWorlds.stream() - .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) - .findFirst(); + List matches = + visibleWorlds.stream() + .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } public Optional resolveRealm(WorldView world, String selector) { @@ -559,20 +561,23 @@ public Optional resolveRealmTarget(String worldSlug, String } String normalizedWorld = worldSlug.trim().toLowerCase(Locale.ROOT); String normalizedRealm = realmSlug.trim().toLowerCase(Locale.ROOT); - return visibleWorlds().stream() - .filter(world -> normalizedWorld.equals(world.slug().toLowerCase(Locale.ROOT))) - .flatMap( - world -> - visibleRealms(world).stream() - .filter(realm -> normalizedRealm.equals(realm.slug().toLowerCase(Locale.ROOT))) - .map( - realm -> - new RuntimeRealmTarget( - world.slug(), - world.displayName(), - realm.slug(), - realm.displayName()))) - .findFirst(); + List matches = + visibleWorlds().stream() + .filter(world -> normalizedWorld.equals(world.slug().toLowerCase(Locale.ROOT))) + .flatMap( + world -> + visibleRealms(world).stream() + .filter( + realm -> normalizedRealm.equals(realm.slug().toLowerCase(Locale.ROOT))) + .map( + realm -> + new RuntimeRealmTarget( + world.slug(), + world.displayName(), + realm.slug(), + realm.displayName()))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } public List visibleRealms(WorldView world) { @@ -876,14 +881,15 @@ private record CatalogState(List worlds, Map publicProduc } private static List toWorlds(List pointers) { - Map worlds = new LinkedHashMap<>(); + Map worlds = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { if (!hasCompleteAuthorityPointer(pointer)) { continue; } MutableWorldAccumulator world = worlds.computeIfAbsent( - pointer.worldSlug().toLowerCase(Locale.ROOT), + new WorldIdentity( + pointer.tenantId(), pointer.worldSlug().trim().toLowerCase(Locale.ROOT)), ignored -> new MutableWorldAccumulator(pointer.worldSlug(), pointer.worldDisplayName())); world.tenantIds.add(pointer.tenantId()); @@ -908,6 +914,11 @@ private static List toWorlds(List p .toList()); } + private static long worldTenantId(WorldView world) { + List tenantIds = world.realms().stream().map(RealmView::tenantId).distinct().toList(); + return tenantIds.size() == 1 ? tenantIds.getFirst() : -1L; + } + private static void requireExactlyOneVisiblePublicProductionRealmPerTenant( List pointers) { Set tenantIds = @@ -1101,4 +1112,6 @@ private MutableWorldAccumulator(String slug, String displayName) { this.displayName = displayName; } } + + private record WorldIdentity(long tenantId, String normalizedWorldSlug) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 93cc6116b8..ffda0ec3d9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1259,9 +1259,14 @@ private RealmSelectorResolution resolvePlayRealm( .map(RealmSelectorResolution.Selected::new) .orElseGet(RealmSelectorResolution.Invalid::new); } + long tenantId = worldTenantId(world); + if (tenantId <= 0L) { + return new RealmSelectorResolution.Invalid(); + } Optional maybeSnapshot; try { - maybeSnapshot = connectScopeSessionStore.realmsSnapshot(context, world.slug(), Instant.now()); + maybeSnapshot = + connectScopeSessionStore.realmsSnapshot(context, tenantId, world.slug(), Instant.now()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new RealmSelectorResolution.Unavailable(); @@ -1294,6 +1299,12 @@ private RealmSelectorResolution resolvePlayRealm( .orElseGet(RealmSelectorResolution.Stale::new); } + private static long worldTenantId(GameplayWorldCatalog.WorldView world) { + List tenantIds = + world.realms().stream().map(GameplayWorldCatalog.RealmView::tenantId).distinct().toList(); + return tenantIds.size() == 1 ? tenantIds.getFirst() : -1L; + } + private sealed interface WorldSelectorResolution permits WorldSelectorResolution.Selected, WorldSelectorResolution.Invalid, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index c3b7648663..c25f742b9a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -135,7 +135,7 @@ public RealmBrowseResult browseRealms( return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); } try { - connectScopeSessionStore.clearWorldScopes(sessionContext, worldSelector); + connectScopeSessionStore.clearWorldScopes(sessionContext, worldTenantId(world), world.slug()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); @@ -205,6 +205,7 @@ public RealmBrowseResult browseRealms( connectScopeSessionStore.replaceRealmSnapshot( sessionContext, worldSelector, + worldTenantId(world), world.slug(), realmSnapshot.catalogFingerprint(), realmSnapshot.ordinalTargets(), @@ -308,7 +309,9 @@ private RealmSelectorResolution resolveLobbyRealm( } Optional maybeSnapshot; try { - maybeSnapshot = connectScopeSessionStore.realmsSnapshot(caller, world.slug(), Instant.now()); + maybeSnapshot = + connectScopeSessionStore.realmsSnapshot( + caller, worldTenantId(world), world.slug(), Instant.now()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new RealmSelectorResolution.Unavailable(); @@ -556,11 +559,51 @@ public JoinMembershipResult joinPublicProductionMembership( if (accountClient == null || connectScopeSessionStore == null) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } + GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot; + try { + catalogSnapshot = worldCatalog.readDiscoverySnapshot(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + WorldSelectorResolution selection = + resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); + if (selection instanceof WorldSelectorResolution.Invalid + || selection instanceof WorldSelectorResolution.Stale) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + if (selection instanceof WorldSelectorResolution.Unavailable) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; + try { + currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + Optional maybeRealmSnapshot; + try { + maybeRealmSnapshot = + connectScopeSessionStore.realmsSnapshot( + sessionContext, worldTenantId(world), world.slug(), Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + if (maybeRealmSnapshot.isEmpty() + || !maybeRealmSnapshot + .orElseThrow() + .catalogFingerprint() + .equals(currentRealmCatalog.catalogFingerprint()) + || !normalizeSelector(worldSelector) + .equals(maybeRealmSnapshot.orElseThrow().requestedWorldSelector())) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } Optional maybeJoinScope; try { maybeJoinScope = connectScopeSessionStore.publicProductionScopeForJoin( - sessionContext, worldSelector, Instant.now()); + sessionContext, worldSelector, worldTenantId(world), world.slug(), Instant.now()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); @@ -576,6 +619,9 @@ public JoinMembershipResult joinPublicProductionMembership( } catch (NumberFormatException ex) { return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } + if (tenantId != worldTenantId(world)) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } boolean hasPublicProductionRealm; try { hasPublicProductionRealm = worldCatalog.hasValidPublicProductionRealm(tenantId); @@ -593,6 +639,16 @@ public JoinMembershipResult joinPublicProductionMembership( playerContext, scope.connectScopeId(), requestId)); } + private static long worldTenantId(GameplayWorldCatalog.WorldView world) { + List tenantIds = + world.realms().stream().map(GameplayWorldCatalog.RealmView::tenantId).distinct().toList(); + return tenantIds.size() == 1 ? tenantIds.getFirst() : -1L; + } + + private static String normalizeSelector(String selector) { + return selector == null ? "" : selector.trim().toLowerCase(java.util.Locale.ROOT); + } + private DirectTextConnectScopeTarget connectScopeTarget( GameplayWorldCatalog.WorldView world, GameplayWorldCatalog.RealmView realm) { if (realm.tenantId() <= 0 diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index f367c3b180..82713cd64e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.Base64; @@ -134,19 +135,76 @@ private Optional asWorldsSnapshot(LobbyRecord record, Instant no record.ordinalTargets())); } + public void replaceWorldScopes( + SessionContext caller, + String requestedWorldSelector, + long tenantId, + String canonicalWorldSlug, + List scopes) { + Objects.requireNonNull(caller, "caller must not be null"); + requireCallerIdentity(caller); + String requestedSelector = normalizeSelector(requestedWorldSelector); + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (requestedSelector == null || worldSlug == null || tenantId <= 0L) { + throw new IllegalArgumentException("world selection identity must be complete"); + } + Instant now = Instant.now(); + List safeScopes = + List.copyOf(Objects.requireNonNull(scopes, "scopes must not be null")); + safeScopes.forEach(scope -> validateScopeIdentity(caller, tenantId, scope)); + long nowMillis = now.toEpochMilli(); + List storedScopes = + safeScopes.stream() + .filter(scope -> scope.expiresAt().toEpochMilli() > nowMillis) + .map(scope -> storeScope(scope, nowMillis)) + .toList(); + long expiresAt = + storedScopes.stream() + .mapToLong(StoredScopedRealm::expiresAtEpochMs) + .max() + .orElse(now.plus(WORLDS_SNAPSHOT_TTL).toEpochMilli()); + String key = worldIdentityKey(tenantId, worldSlug); + mutate( + caller.sessionId(), + nowMillis, + current -> { + LobbyRecord record = current == null ? LobbyRecord.empty(caller.sessionId()) : current; + Map> byWorld = new HashMap<>(record.scopesByWorld()); + byWorld.remove(key); + if (!storedScopes.isEmpty()) { + byWorld.put(key, storedScopes); + } + Map realmsByWorld = new HashMap<>(record.realmsByWorld()); + realmsByWorld.put( + key, + new StoredRealmsSnapshot( + tenantId, worldSlug, requestedSelector, "", expiresAt, List.of())); + return new LobbyRecord( + caller.sessionId(), + caller.accountId(), + record.worldsExpiresAtEpochMs(), + record.catalogFingerprint(), + record.ordinalTargets(), + byWorld, + record.worldBySelector(), + realmsByWorld); + }); + } + public void replaceWorldScopes( SessionContext caller, String requestedWorldSelector, String canonicalWorldSlug, List scopes) { - replaceRealmSnapshot( - caller, requestedWorldSelector, canonicalWorldSlug, null, List.of(), scopes, Instant.now()); + long tenantId = uniqueTenantId(scopes); + replaceWorldScopes(caller, requestedWorldSelector, tenantId, canonicalWorldSlug, scopes); } /** Atomically stores the exact REALMS response and any Account scopes it produced. */ public void replaceRealmSnapshot( SessionContext caller, String requestedWorldSelector, + long tenantId, String canonicalWorldSlug, String catalogFingerprint, List ordinalTargets, @@ -156,7 +214,7 @@ public void replaceRealmSnapshot( requireCallerIdentity(caller); String requestedSelector = normalizeSelector(requestedWorldSelector); String worldSlug = normalizeSelector(canonicalWorldSlug); - if (requestedSelector == null || worldSlug == null) { + if (requestedSelector == null || worldSlug == null || tenantId <= 0L) { throw new IllegalArgumentException("world selectors must not be blank"); } Objects.requireNonNull(now, "now must not be null"); @@ -172,7 +230,7 @@ public void replaceRealmSnapshot( validateRealmOrdinalTargets(safeTargets); List safeScopes = List.copyOf(Objects.requireNonNull(scopes, "scopes must not be null")); - safeScopes.forEach(scope -> validateScopeIdentity(caller, scope)); + safeScopes.forEach(scope -> validateScopeIdentity(caller, tenantId, scope)); long nowMillis = now.toEpochMilli(); List storedScopes = safeScopes.stream() @@ -180,6 +238,7 @@ public void replaceRealmSnapshot( .map(scope -> storeScope(scope, nowMillis)) .toList(); long snapshotExpiresAtMillis = now.plus(WORLDS_SNAPSHOT_TTL).toEpochMilli(); + String worldKey = worldIdentityKey(tenantId, worldSlug); mutate( caller.sessionId(), @@ -195,21 +254,22 @@ record = LobbyRecord.empty(caller.sessionId()); Map> byWorld = new HashMap<>(record.scopesByWorld()); Map worldBySelector = new HashMap<>(record.worldBySelector()); Map realmsByWorld = new HashMap<>(record.realmsByWorld()); - byWorld.remove(worldSlug); - realmsByWorld.remove(worldSlug); - worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); + byWorld.remove(worldKey); + realmsByWorld.remove(worldKey); + worldBySelector.entrySet().removeIf(entry -> worldKey.equals(entry.getValue())); if (!storedScopes.isEmpty()) { - byWorld.put(worldSlug, storedScopes); - worldBySelector.put(worldSlug, worldSlug); - worldBySelector.put(requestedSelector, worldSlug); + byWorld.put(worldKey, storedScopes); } if (catalogFingerprint != null) { - worldBySelector.put(worldSlug, worldSlug); - worldBySelector.put(requestedSelector, worldSlug); realmsByWorld.put( - worldSlug, + worldKey, new StoredRealmsSnapshot( - worldSlug, catalogFingerprint, snapshotExpiresAtMillis, safeTargets)); + tenantId, + worldSlug, + requestedSelector, + catalogFingerprint, + snapshotExpiresAtMillis, + safeTargets)); } return new LobbyRecord( caller.sessionId(), @@ -223,6 +283,35 @@ record = LobbyRecord.empty(caller.sessionId()); }); } + public Optional realmsSnapshot( + SessionContext caller, long tenantId, String canonicalWorldSlug, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); + requireCallerIdentity(caller); + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (worldSlug == null || tenantId <= 0L) { + return Optional.empty(); + } + LobbyRecord record = readRecord(caller.sessionId()); + if (!matchesCaller(record, caller)) { + return Optional.empty(); + } + StoredRealmsSnapshot snapshot = + record.realmsByWorld().get(worldIdentityKey(tenantId, worldSlug)); + if (snapshot == null || snapshot.expiresAtEpochMs() <= now.toEpochMilli()) { + return Optional.empty(); + } + return Optional.of( + new RealmsSnapshot( + snapshot.worldSlug(), + snapshot.tenantId(), + snapshot.requestedWorldSelector(), + snapshot.catalogFingerprint(), + Instant.ofEpochMilli(snapshot.expiresAtEpochMs()), + snapshot.ordinalTargets())); + } + + /** Resolves a legacy bare world selector only when this session has one matching tenant. */ public Optional realmsSnapshot( SessionContext caller, String canonicalWorldSlug, Instant now) { Objects.requireNonNull(caller, "caller must not be null"); @@ -236,25 +325,33 @@ public Optional realmsSnapshot( if (!matchesCaller(record, caller)) { return Optional.empty(); } - StoredRealmsSnapshot snapshot = record.realmsByWorld().get(worldSlug); - if (snapshot == null || snapshot.expiresAtEpochMs() <= now.toEpochMilli()) { + List matches = + record.realmsByWorld().values().stream() + .filter(snapshot -> snapshot.worldSlug().equals(worldSlug)) + .filter(snapshot -> snapshot.expiresAtEpochMs() > now.toEpochMilli()) + .toList(); + if (matches.size() != 1) { return Optional.empty(); } + StoredRealmsSnapshot snapshot = matches.getFirst(); return Optional.of( new RealmsSnapshot( snapshot.worldSlug(), + snapshot.tenantId(), + snapshot.requestedWorldSelector(), snapshot.catalogFingerprint(), Instant.ofEpochMilli(snapshot.expiresAtEpochMs()), snapshot.ordinalTargets())); } - public void clearWorldScopes(SessionContext caller, String worldSelector) { + public void clearWorldScopes(SessionContext caller, long tenantId, String canonicalWorldSlug) { Objects.requireNonNull(caller, "caller must not be null"); requireCallerIdentity(caller); - String selector = normalizeSelector(worldSelector); - if (selector == null) { + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (worldSlug == null || tenantId <= 0L) { return; } + String worldKey = worldIdentityKey(tenantId, worldSlug); long nowMillis = Instant.now().toEpochMilli(); mutate( caller.sessionId(), @@ -270,16 +367,12 @@ public void clearWorldScopes(SessionContext caller, String worldSelector) { if (record.accountId() > 0L && record.accountId() != caller.accountId()) { record = LobbyRecord.empty(caller.sessionId()); } - String worldSlug = record.worldBySelector().get(selector); - if (worldSlug == null) { - return record.withAccountId(caller.accountId()); - } Map> byWorld = new HashMap<>(record.scopesByWorld()); Map realmsByWorld = new HashMap<>(record.realmsByWorld()); - byWorld.remove(worldSlug); - realmsByWorld.remove(worldSlug); + byWorld.remove(worldKey); + realmsByWorld.remove(worldKey); Map worldBySelector = new HashMap<>(record.worldBySelector()); - worldBySelector.entrySet().removeIf(entry -> worldSlug.equals(entry.getValue())); + worldBySelector.entrySet().removeIf(entry -> worldKey.equals(entry.getValue())); return new LobbyRecord( caller.sessionId(), caller.accountId(), @@ -292,25 +385,42 @@ record = LobbyRecord.empty(caller.sessionId()); }); } + public void clearWorldScopes(SessionContext caller, String canonicalWorldSlug) { + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (worldSlug == null) { + return; + } + LobbyRecord record = readRecord(caller.sessionId()); + if (record == null) { + return; + } + List matches = + record.realmsByWorld().values().stream() + .filter(snapshot -> snapshot.worldSlug().equals(worldSlug)) + .map(snapshot -> new StoredWorldIdentity(snapshot.tenantId(), snapshot.worldSlug())) + .distinct() + .toList(); + if (matches.size() == 1) { + clearWorldScopes(caller, matches.getFirst().tenantId(), matches.getFirst().worldSlug()); + } + } + public Optional publicProductionScope( - SessionContext caller, String worldSelector, Instant now) { + SessionContext caller, long tenantId, String canonicalWorldSlug, Instant now) { Objects.requireNonNull(caller, "caller must not be null"); Objects.requireNonNull(now, "now must not be null"); requireCallerIdentity(caller); - String selector = normalizeSelector(worldSelector); - if (selector == null) { + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (worldSlug == null || tenantId <= 0L) { return Optional.empty(); } LobbyRecord record = readRecord(caller.sessionId()); if (!matchesCaller(record, caller)) { return Optional.empty(); } - String worldSlug = record.worldBySelector().get(selector); - if (worldSlug == null) { - return Optional.empty(); - } + String worldKey = worldIdentityKey(tenantId, worldSlug); List publicScopes = - record.scopesByWorld().getOrDefault(worldSlug, List.of()).stream() + record.scopesByWorld().getOrDefault(worldKey, List.of()).stream() .map(DirectTextConnectScopeSessionStore::fromStoredScope) .filter(scope -> scope.expiresAt().isAfter(now)) .filter(ScopedRealm::publicProductionRealm) @@ -318,16 +428,30 @@ public Optional publicProductionScope( return publicScopes.size() == 1 ? Optional.of(publicScopes.getFirst()) : Optional.empty(); } + public Optional publicProductionScope( + SessionContext caller, String canonicalWorldSlug, Instant now) { + StoredWorldIdentity identity = uniqueStoredWorld(caller, canonicalWorldSlug); + return identity == null + ? Optional.empty() + : publicProductionScope(caller, identity.tenantId(), identity.worldSlug(), now); + } + /** Atomically binds and reuses one JOIN request ID for the exact Account scope. */ public Optional publicProductionScopeForJoin( - SessionContext caller, String worldSelector, Instant now) { + SessionContext caller, + String requestedWorldSelector, + long tenantId, + String canonicalWorldSlug, + Instant now) { Objects.requireNonNull(caller, "caller must not be null"); Objects.requireNonNull(now, "now must not be null"); requireCallerIdentity(caller); - String selector = normalizeSelector(worldSelector); - if (selector == null) { + String selector = normalizeSelector(requestedWorldSelector); + String worldSlug = normalizeSelector(canonicalWorldSlug); + if (selector == null || worldSlug == null || tenantId <= 0L) { return Optional.empty(); } + String worldKey = worldIdentityKey(tenantId, worldSlug); long nowMillis = now.toEpochMilli(); JoinScope[] selected = new JoinScope[1]; mutate( @@ -338,12 +462,14 @@ public Optional publicProductionScopeForJoin( if (!matchesCaller(current, caller)) { return current; } - String worldSlug = current.worldBySelector().get(selector); - if (worldSlug == null) { + StoredRealmsSnapshot realmsSnapshot = current.realmsByWorld().get(worldKey); + if (realmsSnapshot == null + || realmsSnapshot.expiresAtEpochMs() <= nowMillis + || !selector.equals(realmsSnapshot.requestedWorldSelector())) { return current; } List scopes = - current.scopesByWorld().getOrDefault(worldSlug, List.of()); + current.scopesByWorld().getOrDefault(worldKey, List.of()); List validPublicScopes = scopes.stream() .filter(scope -> scope.expiresAtEpochMs() > nowMillis) @@ -367,7 +493,7 @@ public Optional publicProductionScopeForJoin( .map(candidate -> candidate == scopeToReplace ? scopeToStore : candidate) .toList(); Map> byWorld = new HashMap<>(current.scopesByWorld()); - byWorld.put(worldSlug, updatedScopes); + byWorld.put(worldKey, updatedScopes); current = current.withScopes(byWorld, current.worldBySelector()); } selected[0] = new JoinScope(fromStoredScope(boundScope), requestId); @@ -376,6 +502,15 @@ public Optional publicProductionScopeForJoin( return Optional.ofNullable(selected[0]); } + public Optional publicProductionScopeForJoin( + SessionContext caller, String worldSelector, Instant now) { + StoredWorldIdentity identity = uniqueStoredWorld(caller, worldSelector); + return identity == null + ? Optional.empty() + : publicProductionScopeForJoin( + caller, worldSelector, identity.tenantId(), identity.worldSlug(), now); + } + public void clearSession(long transportSessionId) { requireTransportSessionId(transportSessionId); backend.delete(key(transportSessionId)); @@ -529,15 +664,89 @@ private static ScopedRealm fromStoredScope(StoredScopedRealm stored) { } } - private static void validateScopeIdentity(SessionContext caller, ScopedRealm scope) { + private static void validateScopeIdentity( + SessionContext caller, long tenantId, ScopedRealm scope) { Objects.requireNonNull(scope, "scope must not be null"); PlayerExecutionContext context = scope.playerContext(); if (!Long.toString(caller.accountId()).equals(context.getAccountId()) - || !Long.toString(caller.sessionId()).equals(context.getSessionId())) { + || !Long.toString(caller.sessionId()).equals(context.getSessionId()) + || tenantId <= 0L + || !Long.toString(tenantId).equals(context.getTenantId())) { throw new ConflictingIdentityException("Account scope caller identity did not match session"); } } + private static long parsePositiveLong(String value) { + try { + long parsed = Long.parseLong(value); + return parsed > 0L ? parsed : -1L; + } catch (NumberFormatException ex) { + return -1L; + } + } + + private static long uniqueTenantId(List scopes) { + List tenantIds = + Objects.requireNonNull(scopes, "scopes must not be null").stream() + .map(scope -> parsePositiveLong(scope.playerContext().getTenantId())) + .distinct() + .toList(); + if (tenantIds.size() != 1 || tenantIds.getFirst() <= 0L) { + throw new IllegalArgumentException("scopes must identify exactly one tenant"); + } + return tenantIds.getFirst(); + } + + private StoredWorldIdentity uniqueStoredWorld(SessionContext caller, String selector) { + Objects.requireNonNull(caller, "caller must not be null"); + requireCallerIdentity(caller); + String normalized = normalizeSelector(selector); + if (normalized == null) { + return null; + } + LobbyRecord record = readRecord(caller.sessionId()); + if (!matchesCaller(record, caller)) { + return null; + } + List matches; + if (normalized.chars().allMatch(Character::isDigit)) { + int ordinal; + try { + ordinal = Integer.parseInt(normalized); + } catch (NumberFormatException ex) { + return null; + } + matches = + record.ordinalTargets().stream() + .filter(target -> target.ordinal() == ordinal) + .map(target -> new StoredWorldIdentity(target.tenantId(), target.worldSlug())) + .distinct() + .toList(); + } else { + matches = + record.realmsByWorld().values().stream() + .filter(snapshot -> snapshot.worldSlug().equals(normalized)) + .map(snapshot -> new StoredWorldIdentity(snapshot.tenantId(), snapshot.worldSlug())) + .distinct() + .toList(); + } + return matches.size() == 1 ? matches.getFirst() : null; + } + + private record StoredWorldIdentity(long tenantId, String worldSlug) {} + + private static String worldIdentityKey(long tenantId, String worldSlug) { + String normalized = normalizeSelector(worldSlug); + if (tenantId <= 0L || normalized == null) { + throw new IllegalArgumentException("world identity must be complete"); + } + String encodedSlug = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(normalized.getBytes(StandardCharsets.UTF_8)); + return tenantId + ":" + encodedSlug; + } + private static boolean matchesCaller(LobbyRecord record, SessionContext caller) { return record != null && record.sessionId() == caller.sessionId() @@ -616,13 +825,11 @@ public record WorldOrdinalTarget( long catalogRevision, String targetFingerprint) { public WorldOrdinalTarget { + worldSlug = normalizeSelector(worldSlug); if (ordinal < 1 || tenantId <= 0L || catalogRevision < 0L) { throw new IllegalArgumentException("world ordinal target authority was invalid"); } - if (worldSlug == null - || worldSlug.isBlank() - || targetFingerprint == null - || targetFingerprint.isBlank()) { + if (worldSlug == null || targetFingerprint == null || targetFingerprint.isBlank()) { throw new IllegalArgumentException("world ordinal target identity must not be blank"); } } @@ -663,12 +870,17 @@ public record WorldsSnapshot( public record RealmsSnapshot( String worldSlug, + long tenantId, + String requestedWorldSelector, String catalogFingerprint, Instant expiresAt, List ordinalTargets) { public RealmsSnapshot { - if (worldSlug == null || worldSlug.isBlank()) { - throw new IllegalArgumentException("worldSlug must not be blank"); + if (worldSlug == null || worldSlug.isBlank() || tenantId <= 0L) { + throw new IllegalArgumentException("world identity must be complete"); + } + if (requestedWorldSelector == null || requestedWorldSelector.isBlank()) { + throw new IllegalArgumentException("requestedWorldSelector must not be blank"); } if (catalogFingerprint == null || catalogFingerprint.isBlank()) { throw new IllegalArgumentException("catalogFingerprint must not be blank"); @@ -861,12 +1073,19 @@ private StoredScopedRealm withJoinRequestId(String requestId) { } private record StoredRealmsSnapshot( + long tenantId, String worldSlug, + String requestedWorldSelector, String catalogFingerprint, long expiresAtEpochMs, List ordinalTargets) { private StoredRealmsSnapshot { + if (tenantId < 0L) { + throw new IllegalArgumentException("tenantId must not be negative"); + } Objects.requireNonNull(worldSlug, "worldSlug must not be null"); + requestedWorldSelector = + requestedWorldSelector == null ? "" : normalizeSelector(requestedWorldSelector); Objects.requireNonNull(catalogFingerprint, "catalogFingerprint must not be null"); ordinalTargets = List.copyOf(ordinalTargets == null ? List.of() : ordinalTargets); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java index 3aef226645..18d3460089 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java @@ -71,6 +71,7 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws firstInstance.replaceWorldScopes( caller, "1", + 22L, "demo-world", List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( @@ -79,6 +80,22 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws "account-connect-scope-17", now.plusSeconds(600), playerContext(caller)))); + firstInstance.replaceWorldScopes( + caller, + "2", + 33L, + "demo-world", + List.of( + new DirectTextConnectScopeSessionStore.ScopedRealm( + "production", + true, + "account-connect-scope-33", + now.plusSeconds(600), + playerContext(caller, 33L)))); + assertThat( + replacementJoinScope(newStoreInstance(), caller, "2", 33L, "demo-world", Instant.now())) + .satisfies( + selected -> assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("33")); List replacementInstances = java.util.stream.IntStream.range(0, 8).mapToObj(ignored -> newStoreInstance()).toList(); @@ -103,7 +120,7 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws throw new IllegalStateException("concurrent JOIN test did not start"); } return replacement - .publicProductionScopeForJoin(caller, "1", Instant.now()) + .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", Instant.now()) .orElseThrow() .requestId(); })); @@ -118,12 +135,16 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws assertThat(requestIds).containsOnly(requestIds.getFirst()); DirectTextConnectScopeSessionStore replacement = replacementInstances.getLast(); - replacement.clearWorldScopes(caller, "1"); - assertThat(firstInstance.publicProductionScopeForJoin(caller, "1", Instant.now())).isEmpty(); + replacement.clearWorldScopes(caller, 22L, "demo-world"); + assertThat( + firstInstance.publicProductionScopeForJoin( + caller, "1", 22L, "demo-world", Instant.now())) + .isEmpty(); replacement.replaceWorldScopes( caller, "1", + 22L, "demo-world", List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( @@ -134,14 +155,17 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws playerContext(caller)))); String freshRequestId = firstInstance - .publicProductionScopeForJoin(caller, "1", Instant.now()) + .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", Instant.now()) .orElseThrow() .requestId(); assertThat(freshRequestId).isNotEqualTo(requestIds.getFirst()); replacement.clearSession(SESSION_ID); assertThat(firstInstance.worldsSnapshot(caller, Instant.now())).isEmpty(); - assertThat(firstInstance.publicProductionScopeForJoin(caller, "1", Instant.now())).isEmpty(); + assertThat( + firstInstance.publicProductionScopeForJoin( + caller, "1", 22L, "demo-world", Instant.now())) + .isEmpty(); } finally { workers.shutdownNow(); } @@ -156,14 +180,28 @@ private static SessionContext session() { } private static PlayerExecutionContext playerContext(SessionContext caller) { + return playerContext(caller, 22L); + } + + private static PlayerExecutionContext playerContext(SessionContext caller, long tenantId) { return PlayerExecutionContext.newBuilder() .setAccountId(Long.toString(caller.accountId())) .setSessionId(Long.toString(caller.sessionId())) - .setTenantId("22") + .setTenantId(Long.toString(tenantId)) .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") .setPlayableStateScope("SHARED") .setGameInstanceId("9") .build(); } + + private static DirectTextConnectScopeSessionStore.JoinScope replacementJoinScope( + DirectTextConnectScopeSessionStore store, + SessionContext caller, + String selector, + long tenantId, + String slug, + Instant now) { + return store.publicProductionScopeForJoin(caller, selector, tenantId, slug, now).orElseThrow(); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 22dfc0abe8..85ddb1e7e8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -8,6 +8,8 @@ import java.util.List; import java.util.UUID; import java.util.stream.Stream; +import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.junit.jupiter.api.Test; @@ -34,22 +36,31 @@ void visibleWorldsDropsAmbiguousRealmSelectorRows() { } @Test - void visibleWorldsDropsWorldSlugSharedAcrossTenants() { + void visibleWorldsKeepsSameWorldSlugSeparateAcrossTenants() { when(authorityService.listPointers()) .thenReturn( List.of( pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), - pointer("DEMO", "Other Demo", "production", "Other Live", 2L, 21L, 8L), - pointer("other", "Other World", "production", "Other Live", 1L, 22L, 9L))); + pointer("DEMO", "Other Demo", "production", "Other Live", 2L, 21L, 8L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); assertThat(catalog.visibleWorlds()) .extracting(GameplayWorldCatalog.WorldView::slug) - .containsExactly("other"); + .containsExactly("demo", "DEMO"); assertThat(catalog.resolveWorld("demo")).isEmpty(); - assertThat(catalog.publicProductionRealmCardinality(1L)) - .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); - assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); + GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.readDiscoverySnapshot(); + assertThat(snapshot.output().worlds()) + .extracting(WorldsViewOutput.WorldEntry::ordinal) + .containsExactly(1, 2); + assertThat(snapshot.output().worlds()) + .extracting(WorldsViewOutput.WorldEntry::slug) + .containsExactly("demo", "DEMO"); + assertThat(snapshot.ordinalTargets()) + .extracting(DirectTextConnectScopeSessionStore.WorldOrdinalTarget::tenantId) + .containsExactly(1L, 2L); + assertThat(catalog.resolveSnapshotOrdinal(snapshot, snapshot.ordinalTargets().get(1))) + .hasValueSatisfying( + world -> assertThat(world.realms().getFirst().tenantId()).isEqualTo(2L)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 4d851651ee..a0ace4e33b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -6,6 +6,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -383,6 +384,181 @@ void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { scriptEventPublisher); } + @Test + void numericPlayRealmUsesTenantQualifiedSnapshotForDuplicateWorldSlug() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayCatalogProperties.World secondTenantWorld = + world( + "demo", + "Demo World - Second Tenant", + List.of(realm("production", "Second Tenant Live Realm", 23L, 3L, true, false))); + List configuredWorlds = + new ArrayList<>(gameplayCatalogProperties.getWorlds()); + configuredWorlds.add(secondTenantWorld); + gameplayCatalogProperties.setWorlds(configuredWorlds); + + GameplayWorldCatalog.DiscoverySnapshot worlds = worldCatalog.readDiscoverySnapshot(); + DirectTextConnectScopeSessionStore.WorldOrdinalTarget selectedWorldTarget = + worlds.ordinalTargets().stream() + .filter(target -> target.tenantId() == 23L) + .findFirst() + .orElseThrow(); + GameplayWorldCatalog.WorldView selectedWorld = + worlds.visibleWorlds().stream() + .filter( + candidate -> candidate.realms().stream().anyMatch(realm -> realm.tenantId() == 23L)) + .findFirst() + .orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot realms = + worldCatalog.readRealmDiscoverySnapshot(selectedWorld); + String worldSelector = Integer.toString(selectedWorldTarget.ordinal()); + connectScopeSessionStore.replaceWorldSnapshot( + context.sessionId(), + context.accountId(), + worlds.catalogFingerprint(), + worlds.ordinalTargets(), + Instant.now()); + connectScopeSessionStore.replaceRealmSnapshot( + context, + worldSelector, + 23L, + selectedWorld.slug(), + realms.catalogFingerprint(), + realms.ordinalTargets(), + List.of(), + Instant.now()); + when(entityManagementClient.findCharacterByName( + context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Sora")) + .thenReturn( + Optional.of( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("7001") + .setName("Sora") + .build())); + when(accountClient.getTenantMembershipForRuntime( + Mockito.eq("123"), Mockito.eq("23"), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("23") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.eq("23"), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("23") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(sessionAuthenticationService.resolveByGameplayIdentity(23L, 3L, 7001L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of(worldSelector, "1", "Sora"), + "PLAY " + worldSelector + " 1 Sora")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("23"), Mockito.anyString()); + Mockito.verify(moderationPolicyClient).evaluateGameplayAdmission(23L, 123L); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.tenantId() == 23L + && saved.gameInstanceId() == 3L + && "demo".equals(saved.worldSlug()) + && "production".equals(saved.realmSlug()))); + } + + @Test + void numericPlayRealmFailsClosedForWrongTenantOrStaleRealmSnapshot() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + List configuredWorlds = + new ArrayList<>(gameplayCatalogProperties.getWorlds()); + configuredWorlds.add( + world( + "demo", + "Demo World - Second Tenant", + List.of(realm("production", "Second Tenant Live Realm", 23L, 3L, true, false)))); + gameplayCatalogProperties.setWorlds(configuredWorlds); + + GameplayWorldCatalog.DiscoverySnapshot worlds = worldCatalog.readDiscoverySnapshot(); + DirectTextConnectScopeSessionStore.WorldOrdinalTarget selectedWorldTarget = + worlds.ordinalTargets().stream() + .filter(target -> target.tenantId() == 23L) + .findFirst() + .orElseThrow(); + GameplayWorldCatalog.WorldView selectedWorld = + worlds.visibleWorlds().stream() + .filter( + candidate -> candidate.realms().stream().anyMatch(realm -> realm.tenantId() == 23L)) + .findFirst() + .orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot realms = + worldCatalog.readRealmDiscoverySnapshot(selectedWorld); + String worldSelector = Integer.toString(selectedWorldTarget.ordinal()); + connectScopeSessionStore.replaceWorldSnapshot( + context.sessionId(), + context.accountId(), + worlds.catalogFingerprint(), + worlds.ordinalTargets(), + Instant.now()); + + // A snapshot for the colliding slug under the other tenant must not bind this selection. + connectScopeSessionStore.replaceRealmSnapshot( + context, + worldSelector, + 22L, + selectedWorld.slug(), + realms.catalogFingerprint(), + realms.ordinalTargets(), + List.of(), + Instant.now()); + PlayCommandHandlingResult wrongTenantResult = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of(worldSelector, "1"), "PLAY " + worldSelector + " 1")); + assertThat(wrongTenantResult.commandResult().accepted()).isFalse(); + assertThat(wrongTenantResult.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + + // The right tenant key still fails when its retained REALMS fingerprint is stale. + connectScopeSessionStore.replaceRealmSnapshot( + context, + worldSelector, + 23L, + selectedWorld.slug(), + "stale-fingerprint", + realms.ordinalTargets(), + List.of(), + Instant.now()); + PlayCommandHandlingResult staleResult = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of(worldSelector, "1"), "PLAY " + worldSelector + " 1")); + + assertThat(staleResult.commandResult().accepted()).isFalse(); + assertThat(staleResult.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); + } + @Test void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { gameplayCatalogProperties diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index bb68cfe598..a1fb3249d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -126,6 +126,88 @@ void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { Mockito.verifyNoInteractions(accountClient, entityManagementClient); } + @Test + void sameWorldSlugAcrossTenantsKeepsDistinctOrdinalsAndJoinTargets() { + GameplayWorldCatalog.WorldView worldA = worldView("demo", "Tenant A", 22L, 1L); + GameplayWorldCatalog.WorldView worldB = worldView("DEMO", "Tenant B", 33L, 2L); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + Mockito.when( + accountClient.joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews(List.of(worldA, worldB)), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + WorldsViewOutput worlds = localHandler.browseView("7", Optional.of(authenticatedSession())); + assertThat(worlds.worlds()) + .extracting(WorldsViewOutput.WorldEntry::ordinal) + .containsExactly(1, 2); + assertThat(worlds.worlds()) + .extracting(WorldsViewOutput.WorldEntry::slug) + .containsExactly("demo", "DEMO"); + assertThat(localHandler.browseRealms("7", authenticatedSession(), "1")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(localHandler.browseRealms("7", authenticatedSession(), "2")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + + Mockito.clearInvocations(accountClient); + assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "1")) + .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "2")) + .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); + Mockito.verify(accountClient) + .joinPublicProductionMembership( + Mockito.argThat(context -> context.getTenantId().equals("22")), + Mockito.eq("scope"), + Mockito.anyString()); + Mockito.verify(accountClient) + .joinPublicProductionMembership( + Mockito.argThat(context -> context.getTenantId().equals("33")), + Mockito.eq("scope"), + Mockito.anyString()); + } + + @Test + void joinRejectsUnboundOrdinalBeforeCallingAccount() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + Mockito.clearInvocations(accountClient); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "1")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient); + } + @Test void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { GameplayWorldCatalog.RealmView realmA = @@ -214,7 +296,7 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() new GameplayWorldCatalog.RealmView( "preview", "Preview Realm", - 23L, + 22L, 2L, 1L, true, @@ -1356,7 +1438,7 @@ void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySucces } @Test - void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { + void joinRejectsRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { GameplayWorldCatalog.RealmView realmA = new GameplayWorldCatalog.RealmView( "production", @@ -1421,21 +1503,13 @@ void joinUsesRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); worlds.set(List.of(worldB, worldA)); assertThat(catalog.resolveWorld("1")).hasValue(worldB); + Mockito.clearInvocations(accountClient); WorldsCommandHandler.JoinMembershipResult join = localHandler.joinPublicProductionMembership(authenticatedSession(), "1"); - assertThat(join).isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); - assertThat( - ((WorldsCommandHandler.JoinMembershipResult.Response) join).response().getOutcomeCode()) - .isEqualTo("CONNECT_SCOPE_MISMATCH"); - Mockito.verify(accountClient) - .joinPublicProductionMembership( - Mockito.argThat( - context -> - context.getTenantId().equals("22") - && context.getRealmId().equals(realmA.realmId().toString())), - Mockito.eq("scope-a"), - Mockito.anyString()); + assertThat(join) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient); Mockito.verifyNoInteractions(entityManagementClient); } @@ -1571,7 +1645,9 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { assertThat(catalog.publicProductionRealmCardinality(22L)) .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); - assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); + assertThat(catalog.readDiscoverySnapshot().output().worlds()) + .extracting(WorldsViewOutput.WorldEntry::slug) + .containsExactly("DEMO"); Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "other")) @@ -1579,8 +1655,7 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { Mockito.verifyNoInteractions(accountClient); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) - .isEqualTo( - WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); Mockito.verifyNoInteractions(accountClient); Mockito.verifyNoInteractions(entityManagementClient); } @@ -1683,6 +1758,26 @@ private GameplayAdmissionPointerSnapshot admissionPointer(long gameInstanceId) { ADMISSION_NAMESPACE_ID); } + private GameplayWorldCatalog.WorldView worldView( + String worldSlug, String displayName, long tenantId, long gameInstanceId) { + GameplayWorldCatalog.RealmView realm = + new GameplayWorldCatalog.RealmView( + "production", + "Production", + tenantId, + gameInstanceId, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); + return new GameplayWorldCatalog.WorldView(worldSlug, displayName, List.of(realm)); + } + private GameplayCatalogProperties publicProductionProperties() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("demo", 22L, 1L, false))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 432e82b3e7..9f606a9833 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -20,13 +20,14 @@ void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { store.replaceWorldScopes( caller, "1", + 22L, "demo-world", List.of(scopedRealm(caller, "demo-world", "scope-secret", expiry))); - assertThat(store.publicProductionScope(caller, "1", now)) + assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)) .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("scope-secret")); - assertThat(store.publicProductionScope(session(8L, 41L), "1", now)).isEmpty(); - assertThat(store.publicProductionScope(session(7L, 42L), "1", now)).isEmpty(); + assertThat(store.publicProductionScope(session(8L, 41L), 22L, "demo-world", now)).isEmpty(); + assertThat(store.publicProductionScope(session(7L, 42L), 22L, "demo-world", now)).isEmpty(); } @Test @@ -36,20 +37,22 @@ void refusesExpiredAndAmbiguousPublicScopes() { store.replaceWorldScopes( caller, "demo-world", + 22L, "demo-world", List.of(scopedRealm(caller, "production", "expired-scope", now.minusSeconds(1)))); - assertThat(store.publicProductionScope(caller, "demo-world", now)).isEmpty(); + assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); store.replaceWorldScopes( caller, "demo-world", + 22L, "demo-world", List.of( scopedRealm(caller, "production-a", "scope-a", now.plusSeconds(3600)), scopedRealm(caller, "production-b", "scope-b", now.plusSeconds(3600)))); - assertThat(store.publicProductionScope(caller, "demo-world", now)).isEmpty(); + assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); } @Test @@ -59,12 +62,13 @@ void clearsPriorScopeBeforeReplacingTheWorldBinding() { store.replaceWorldScopes( caller, "1", + 22L, "demo-world", List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(3600)))); - store.clearWorldScopes(caller, "1"); + store.clearWorldScopes(caller, 22L, "demo-world"); - assertThat(store.publicProductionScope(caller, "1", now)).isEmpty(); + assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); } @Test @@ -75,26 +79,34 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { store.replaceWorldScopes( caller, "demo-world", + 22L, "demo-world", List.of(scopedRealm(caller, "production", "scope-first", expiry))); DirectTextConnectScopeSessionStore.JoinScope firstAttempt = - store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); + store + .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) + .orElseThrow(); DirectTextConnectScopeSessionStore.JoinScope retryAttempt = - store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); + store + .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) + .orElseThrow(); assertThat(firstAttempt.requestId()).isEqualTo(retryAttempt.requestId()); assertThat(firstAttempt.scope().connectScopeId()) .isEqualTo(retryAttempt.scope().connectScopeId()); - store.clearWorldScopes(caller, "demo-world"); + store.clearWorldScopes(caller, 22L, "demo-world"); store.replaceWorldScopes( caller, "demo-world", + 22L, "demo-world", List.of(scopedRealm(caller, "production", "scope-second", expiry))); DirectTextConnectScopeSessionStore.JoinScope newAttempt = - store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); + store + .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) + .orElseThrow(); assertThat(newAttempt.scope().connectScopeId()).isEqualTo("scope-second"); assertThat(newAttempt.requestId()).isNotEqualTo(firstAttempt.requestId()); @@ -107,22 +119,30 @@ void clearingTransportLobbyRemovesScopeAndBoundJoinIdentityBeforeReuse() { store.replaceWorldScopes( caller, "demo-world", + 22L, "demo-world", List.of(scopedRealm(caller, "production", "old-scope", now.plusSeconds(600)))); String oldRequestId = - store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow().requestId(); + store + .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) + .orElseThrow() + .requestId(); store.clearSession(caller.sessionId()); - assertThat(store.publicProductionScopeForJoin(caller, "demo-world", now)).isEmpty(); - assertThat(store.publicProductionScope(caller, "demo-world", now)).isEmpty(); + assertThat(store.publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now)) + .isEmpty(); + assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); store.replaceWorldScopes( caller, "demo-world", + 22L, "demo-world", List.of(scopedRealm(caller, "production", "new-scope", now.plusSeconds(600)))); DirectTextConnectScopeSessionStore.JoinScope newAttempt = - store.publicProductionScopeForJoin(caller, "demo-world", now).orElseThrow(); + store + .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) + .orElseThrow(); assertThat(newAttempt.scope().connectScopeId()).isEqualTo("new-scope"); assertThat(newAttempt.requestId()).isNotEqualTo(oldRequestId); } @@ -147,16 +167,61 @@ void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { store.replaceWorldScopes( caller, "1", + 22L, "demo-world", List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(86_400)))); DirectTextConnectScopeSessionStore.JoinScope selected = - store.publicProductionScopeForJoin(caller, "1", now).orElseThrow(); + store.publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now).orElseThrow(); assertThat(selected.scope().expiresAt()).isBeforeOrEqualTo(now.plusSeconds(901)); assertThat(selected.scope().playerContext().getAccountId()).isEqualTo("7"); assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); } + @Test + void sameWorldSlugInDifferentTenantsKeepsOrdinalScopesIsolated() { + SessionContext caller = session(41L, 7L); + Instant now = Instant.now(); + store.replaceWorldSnapshot( + caller.sessionId(), + 0L, + "catalog-fingerprint", + List.of( + new DirectTextConnectScopeSessionStore.WorldOrdinalTarget( + 1, "demo", 22L, 3L, "tenant-22-target"), + new DirectTextConnectScopeSessionStore.WorldOrdinalTarget( + 2, "DEMO", 33L, 4L, "tenant-33-target")), + now); + store.replaceWorldScopes( + caller, + "1", + 22L, + "demo", + List.of(scopedRealm(caller, 22L, "production", "tenant-22-scope", now.plusSeconds(60)))); + store.replaceWorldScopes( + caller, + "2", + 33L, + "demo", + List.of(scopedRealm(caller, 33L, "production", "tenant-33-scope", now.plusSeconds(60)))); + + assertThat(store.publicProductionScopeForJoin(caller, "1", 22L, "demo", now)) + .hasValueSatisfying( + selected -> { + assertThat(selected.scope().connectScopeId()).isEqualTo("tenant-22-scope"); + assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); + }); + assertThat(store.publicProductionScopeForJoin(caller, "2", 33L, "demo", now)) + .hasValueSatisfying( + selected -> { + assertThat(selected.scope().connectScopeId()).isEqualTo("tenant-33-scope"); + assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("33"); + }); + assertThat(store.publicProductionScopeForJoin(caller, "2", 22L, "demo", now)).isEmpty(); + assertThat(store.publicProductionScope(caller, "demo", now)).isEmpty(); + assertThat(store.publicProductionScopeForJoin(caller, "demo", now)).isEmpty(); + } + @Test void storesRealmsResponseSnapshotOnlyForTheIssuingAccountAndBeforeExpiry() { SessionContext caller = session(41L, 7L); @@ -165,19 +230,21 @@ void storesRealmsResponseSnapshotOnlyForTheIssuingAccountAndBeforeExpiry() { new DirectTextConnectScopeSessionStore.RealmOrdinalTarget( 1, "production", 22L, 29L, 3L, "realm-target-fingerprint"); store.replaceRealmSnapshot( - caller, "demo", "demo", "realm-catalog-fingerprint", List.of(target), List.of(), now); + caller, "demo", 22L, "demo", "realm-catalog-fingerprint", List.of(target), List.of(), now); - assertThat(store.realmsSnapshot(caller, "demo", now)) + assertThat(store.realmsSnapshot(caller, 22L, "demo", now)) .hasValueSatisfying( snapshot -> { assertThat(snapshot.worldSlug()).isEqualTo("demo"); + assertThat(snapshot.tenantId()).isEqualTo(22L); + assertThat(snapshot.requestedWorldSelector()).isEqualTo("demo"); assertThat(snapshot.catalogFingerprint()).isEqualTo("realm-catalog-fingerprint"); assertThat(snapshot.ordinalTargets()).containsExactly(target); assertThat(snapshot.expiresAt()).isBeforeOrEqualTo(now.plusSeconds(301)); }); - assertThat(store.realmsSnapshot(session(41L, 8L), "demo", now)).isEmpty(); - assertThat(store.realmsSnapshot(session(42L, 7L), "demo", now)).isEmpty(); - assertThat(store.realmsSnapshot(caller, "demo", now.plusSeconds(301))).isEmpty(); + assertThat(store.realmsSnapshot(session(41L, 8L), 22L, "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(session(42L, 7L), 22L, "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(caller, 22L, "demo", now.plusSeconds(301))).isEmpty(); } @Test @@ -198,11 +265,16 @@ private static SessionContext session(long sessionId, long accountId) { private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( SessionContext caller, String realmSlug, String scopeId, Instant expiry) { + return scopedRealm(caller, 22L, realmSlug, scopeId, expiry); + } + + private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( + SessionContext caller, long tenantId, String realmSlug, String scopeId, Instant expiry) { PlayerExecutionContext playerContext = PlayerExecutionContext.newBuilder() .setAccountId(Long.toString(caller.accountId())) .setSessionId(Long.toString(caller.sessionId())) - .setTenantId("22") + .setTenantId(Long.toString(tenantId)) .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") .setPlayableStateScope("SHARED") From 285d7bc2f7b39217b177d5da2991cf3b36590b63 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:53:49 +1300 Subject: [PATCH 021/105] Hide inaccessible private-only world selectors --- .../command/text/GameplayWorldCatalog.java | 16 +++ .../command/text/PlayCommandHandler.java | 20 ++- .../command/text/WorldsCommandHandler.java | 34 +++-- .../command/text/PlayCommandHandlerTest.java | 57 ++++++++- .../text/WorldsCommandHandlerTest.java | 121 +++++++++++++++--- 5 files changed, 213 insertions(+), 35 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 2d2a91bcc1..d5f2759676 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -522,6 +522,22 @@ public boolean hasValidPublicProductionRealm(DiscoverySnapshot snapshot, WorldVi tenantId -> snapshot.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L); } + /** + * Returns whether a world is represented by the public WORLDS discovery projection. + * + *

Private-only worlds remain in the catalog so an account with a matching grant can resolve + * them for admission. Callers handling a selector must not use that broader admission catalog as + * proof that an ungranted private world is discoverable. + */ + public boolean isPubliclyDiscoverable(DiscoverySnapshot snapshot, WorldView world) { + Objects.requireNonNull(snapshot, "snapshot must not be null"); + if (world == null) { + return false; + } + return hasPublicDiscoveryRealm( + world, new CatalogState(snapshot.visibleWorlds(), snapshot.publicProductionCounts())); + } + public boolean requiresExplicitRealmSelection(WorldView world) { return visibleRealms(world).size() > 1; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index ffda0ec3d9..2dd893c0cc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -357,7 +357,20 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { selectedTenantTag, selection.characterSelector()); if (authorityFailure.isPresent()) { - return authorityFailure.get(); + PlayCommandHandlingResult failure = authorityFailure.orElseThrow(); + if (!gameplayWorldCatalog.isPubliclyDiscoverable(currentCatalog, selectedWorld) + && isDefinitivePrivateWorldDenial(failure)) { + return failure( + GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, + GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_MESSAGE, + "error.play.selection-required", + Map.of(), + tenantTag, + null, + null, + null); + } + return failure; } String character = selection.characterSelector(); @@ -933,6 +946,11 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( null); } + private boolean isDefinitivePrivateWorldDenial(PlayCommandHandlingResult result) { + return GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE.equals( + result.commandResult().errorCode()); + } + private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( SessionContext context, String tenantTag, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index c25f742b9a..9992816637 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -131,15 +131,6 @@ public RealmBrowseResult browseRealms( } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); - if (connectScopeSessionStore == null) { - return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); - } - try { - connectScopeSessionStore.clearWorldScopes(sessionContext, worldTenantId(world), world.slug()); - } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException - | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { - return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); - } if (!worldCatalog.hasValidPublicProductionRealm(catalogSnapshot, world)) { return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } @@ -199,6 +190,21 @@ public RealmBrowseResult browseRealms( responseRealms.add(realm); } + // A private-only world is retained for granted admission, but a denied selector must be + // indistinguishable from an unknown world and must not write lobby scope state. + if (responseRealms.isEmpty() && !worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { + return RealmBrowseResult.invalidSelector(); + } + if (connectScopeSessionStore == null) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + try { + connectScopeSessionStore.clearWorldScopes(sessionContext, worldTenantId(world), world.slug()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + try { GameplayWorldCatalog.RealmDiscoverySnapshot realmSnapshot = worldCatalog.realmDiscoverySnapshot(world, responseRealms); @@ -829,6 +835,10 @@ public CharacterBrowseResult browseCharacters( : mapNonPublicCharacterAuthorization( authorizeNonPublicRealm(sessionContext, world, realm, requestId)); if (authorization != CharacterBrowseAuthorization.AUTHORIZED) { + if (!worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) + && authorization.isDefinitiveAccessDenial()) { + return CharacterBrowseResult.invalidWorld(); + } return CharacterBrowseResult.failure(authorization.code()); } @@ -1022,6 +1032,12 @@ private enum CharacterBrowseAuthorization { private String code() { return code; } + + private boolean isDefinitiveAccessDenial() { + return this == DENIED + || this == PUBLIC_PRODUCTION_ADMISSION_DENIED + || this == NON_PUBLIC_ENROLLMENT_REQUIRED; + } } private record PublicEntitlementAuthorization( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index a0ace4e33b..dd470ef64d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1433,7 +1433,8 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { "PLAY sandbox preview Emberline")); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); } @Test @@ -1507,7 +1508,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); Mockito.verify(accountClient, Mockito.never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1557,7 +1558,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq("123"), @@ -1567,6 +1568,52 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.anyString()); } + @Test + void privateOnlyWorldPlayDenialMatchesUnknownAndGrantedAccessStillWorks() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt(evaluatedAtNow()) + .build(), + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("sandbox"), + Mockito.eq("preview"), + Mockito.anyString())) + .thenReturn(validGrant()); + + PlayCommandHandlingResult denied = handler.handle("1", previewRealmPlayCommand()); + PlayCommandHandlingResult unknown = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("unknown"), "PLAY unknown")); + PlayCommandHandlingResult granted = handler.handle("1", previewRealmPlayCommand()); + + assertThat(denied.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + assertThat(unknown.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + assertThat(granted.commandResult()).isEqualTo(CommandEnqueueResult.success()); + } + @Test void playInvisibleRealmWithDeniedGrantClearsBinding() { markPreviewRealmInvisible(); @@ -1583,7 +1630,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } @@ -1610,7 +1657,7 @@ void playInvisibleRealmWithNonAuthorityGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index a1fb3249d9..00a0608c95 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -704,10 +704,7 @@ void browseCharactersDeniesRevokedPrivateMembershipBeforeReadingEntityRoster() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); - assertThat(result) - .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "NON_PUBLIC_ENROLLMENT_REQUIRED")); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); Mockito.verifyNoInteractions(entityManagementClient); Mockito.verify(accountClient, Mockito.never()) .getRealmAccessGrantForRuntime( @@ -732,11 +729,9 @@ void browseRealmsOmitsActivePrivateMembershipWithoutAdmissionWhileCharactersDeny WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) - .isInstanceOfSatisfying( - WorldsCommandHandler.RealmBrowseResult.Success.class, - success -> assertThat(success.output().realms()).isEmpty()); + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("WORLD_ACCESS_DENIED")); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); Mockito.verifyNoInteractions(entityManagementClient); Mockito.verify(accountClient, Mockito.never()) .getRealmAccessGrantForRuntime( @@ -771,8 +766,7 @@ void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoste WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); - assertThat(result) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("WORLD_ACCESS_DENIED")); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); Mockito.verifyNoInteractions(entityManagementClient); } @@ -1083,9 +1077,7 @@ void authenticatedBrowseOmitsPrivateRealmForNonMember() { WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "preview"); - assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) - .isEmpty(); + assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); Mockito.verify(accountClient, Mockito.never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1095,6 +1087,84 @@ void authenticatedBrowseOmitsPrivateRealmForNonMember() { Mockito.anyString()); } + @Test + void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { + GameplayCatalogProperties properties = privateOnlyWorldProperties(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership(), publicMembership(false, false, 0L, 0L, "MISSING")); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("private-only"), + Mockito.eq("preview"), + Mockito.anyString())) + .thenReturn(grant("private-only", "preview", true)); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(properties), + entityManagementClient, + accountClient, + scopeStore); + + assertThat(localHandler.browseRealms(authenticatedSession(), "private-only")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + Optional grantedSnapshot = + scopeStore.realmsSnapshot(authenticatedSession(), 22L, "private-only", Instant.now()); + assertThat(grantedSnapshot).isPresent(); + + assertThat(localHandler.browseRealms(authenticatedSession(), "private-only")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + assertThat(localHandler.browseRealms(authenticatedSession(), "unknown")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + assertThat( + scopeStore.realmsSnapshot(authenticatedSession(), 22L, "private-only", Instant.now())) + .hasValue(grantedSnapshot.orElseThrow()); + } + + @Test + void privateOnlyCharacterSelectorMatchesUnknownWhenDeniedAndRemainsReachableWhenGranted() { + GameplayCatalogProperties properties = privateOnlyWorldProperties(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING"), activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("private-only"), + Mockito.eq("preview"), + Mockito.anyString())) + .thenReturn(grant("private-only", "preview", true)); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "preview")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "unknown", "preview")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "preview")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + @Test void authenticatedBrowseOmitsPrivateRealmWithoutExactGrant() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -1119,9 +1189,7 @@ void authenticatedBrowseOmitsPrivateRealmWithoutExactGrant() { WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "preview"); - assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) - .isEmpty(); + assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); } @Test @@ -1262,9 +1330,7 @@ void authenticatedBrowseOmitsPrivateRealmWhenGameplayEntitlementIsUnavailable() WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "preview"); - assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) - .isEmpty(); + assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); Mockito.verify(accountClient) .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); } @@ -1852,17 +1918,32 @@ private GetRealmAccessGrantForRuntimeResponse grant(boolean granted) { } private GetRealmAccessGrantForRuntimeResponse grant(String worldSlug, boolean granted) { + return grant(worldSlug, "production", granted); + } + + private GetRealmAccessGrantForRuntimeResponse grant( + String worldSlug, String realmSlug, boolean granted) { return GetRealmAccessGrantForRuntimeResponse.newBuilder() .setAccountId("123") .setTenantId("22") .setWorldSlug(worldSlug) - .setRealmSlug("production") + .setRealmSlug(realmSlug) .setGranted(granted) .setGrantVersion(granted ? 1L : 0L) .setEvaluatedAt(Instant.now().toString()) .build(); } + private GameplayCatalogProperties privateOnlyWorldProperties() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds( + List.of(world("public", 22L, 1L, false), world("private-only", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + properties.getWorlds().get(1).getRealms().getFirst().setSlug("preview"); + properties.getWorlds().get(1).getRealms().getFirst().setPublicProductionRealm(false); + return properties; + } + private void stubActivePrivateAuthorization(AccountClient accountClient, String worldSlug) { Mockito.when( accountClient.getTenantMembershipForRuntime( From 74edccdf8fe190e29d9a050fe646f29ab4f1f5a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 18:29:18 +1300 Subject: [PATCH 022/105] Bind PLAY actor to selected account roster --- .../command/text/PlayCommandHandler.java | 144 +++++---- .../command/text/PlayCommandHandlerTest.java | 303 +++++++++++++++++- .../text/SessionResumptionFlowTest.java | 4 +- .../text/TextCommandInterpreterTest.java | 4 +- 4 files changed, 376 insertions(+), 79 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 2dd893c0cc..2ed761e521 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -13,6 +13,8 @@ import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.entitymanagement.v1.Character; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -349,13 +351,10 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { if (connectScopeFailure.isPresent()) { return connectScopeFailure.get(); } + String character = selection.characterSelector(); + long gameInstanceId = selectedRealm.gameInstanceId(); Optional authorityFailure = - validateRuntimeAdmission( - context, - selectedWorld, - selectedRealm, - selectedTenantTag, - selection.characterSelector()); + validateRuntimeAdmission(context, selectedWorld, selectedRealm, selectedTenantTag, 0L); if (authorityFailure.isPresent()) { PlayCommandHandlingResult failure = authorityFailure.orElseThrow(); if (!gameplayWorldCatalog.isPubliclyDiscoverable(currentCatalog, selectedWorld) @@ -372,9 +371,6 @@ && isDefinitivePrivateWorldDenial(failure)) { } return failure; } - - String character = selection.characterSelector(); - String characterName = resolveCharacterName(context, character); if (selectedRealm.requiresCharacterSelection() && !StringUtils.hasText(character)) { return failure( "PLAY_SELECTION_REQUIRED", @@ -394,19 +390,20 @@ && isDefinitivePrivateWorldDenial(failure)) { null, null); } - long gameInstanceId = selectedRealm.gameInstanceId(); + ResolvedCharacter resolvedCharacter; + try { + resolvedCharacter = resolveCharacter(context, selectedRealm, character); + } catch (IllegalStateException ex) { + return characterIdentityUnavailableFailure( + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); + } + String characterName = resolvedCharacter.name(); Optional moderationFailure = validateModerationPolicy(context, selectedRealm, selectedTenantTag); if (moderationFailure.isPresent()) { return moderationFailure.get(); } - long characterId; - try { - characterId = resolveCharacterId(context, selectedRealm, character, characterName); - } catch (IllegalStateException ex) { - return characterIdentityUnavailableFailure( - selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), characterName, ex); - } + long characterId = resolvedCharacter.id(); try (GameplayLoggingContext gameplayContext = GameplayLoggingContext.open( selectedTenantTag, @@ -434,7 +431,7 @@ && isDefinitivePrivateWorldDenial(failure)) { boolean freshEntryFallback = maybeRecordFreshEntryFallback( - context, selectedRealm, character, gameInstanceId, characterId); + context, selectedRealm, characterName, gameInstanceId, characterId); Optional existingBinding = sessionAuthenticationService @@ -604,47 +601,60 @@ private PlayCommandHandlingResult failure( List.of(PlayerOutput.error(errorCode, message, messageKey, arguments))); } - private long resolveCharacterId( + private ResolvedCharacter resolveCharacter( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, - String requestedCharacter, - String characterName) { - if (context.characterId() > 0) { - return context.characterId(); + String requestedCharacter) { + PlayableStateScope playableStateScope = toPlayableStateScope(selectedRealm); + ListCharactersByAccountResponse response = + entityManagementClient.listCharactersByAccount( + Long.toString(selectedRealm.tenantId()), + Long.toString(context.accountId()), + Long.toString(selectedRealm.gameInstanceId()), + playableStateScope); + if (response == null || response.hasError()) { + throw new IllegalStateException("Character roster unavailable for selected gameplay target"); } - if (StringUtils.hasText(characterName)) { - Optional character = - entityManagementClient.findCharacterByName( - context, toPlayableStateScope(selectedRealm), characterName.trim()); - if (character.isPresent()) { - return requireResolvedCharacterId(character.get().getId()); + + List roster = response.getCharactersList(); + java.util.Set characterIds = new java.util.HashSet<>(); + for (Character character : roster) { + long characterId = requireResolvedCharacterId(character.getId()); + if (!Long.toString(selectedRealm.tenantId()).equals(character.getTenantId()) + || !Long.toString(context.accountId()).equals(character.getAccountId()) + || character.getPlayableStateScope() != playableStateScope + || !StringUtils.hasText(character.getName()) + || !characterIds.add(characterId)) { + throw new IllegalStateException( + "Malformed or unauthorized character roster for selected gameplay target"); } } - if (!StringUtils.hasText(requestedCharacter)) { - return context.accountId(); - } - return Math.floorMod( - Objects.hash( - selectedRealm.tenantId(), - selectedRealm.gameInstanceId(), - characterName.trim().toLowerCase()), - Integer.MAX_VALUE - 1) - + 1L; - } - private String resolveCharacterName(SessionContext context, String character) { - if (StringUtils.hasText(character)) { - return character.trim(); - } - if (StringUtils.hasText(context.characterName())) { - return context.characterName().trim(); - } - if (StringUtils.hasText(context.loginName())) { - String login = context.loginName().trim(); - int at = login.indexOf('@'); - return at > 0 ? login.substring(0, at) : login; + Character selected; + if (StringUtils.hasText(requestedCharacter)) { + List matches = + roster.stream() + .filter( + character -> + Objects.equals( + normalizeName(character.getName()), normalizeName(requestedCharacter))) + .toList(); + if (matches.size() != 1) { + throw new IllegalStateException( + matches.isEmpty() + ? "Selected character is not present in the authenticated account roster" + : "Selected character is ambiguous in the authenticated account roster"); + } + selected = matches.getFirst(); + } else { + if (roster.size() != 1) { + throw new IllegalStateException( + "PLAY without a character requires exactly one current account character"); + } + selected = roster.getFirst(); } - return "character-" + context.accountId(); + return new ResolvedCharacter( + requireResolvedCharacterId(selected.getId()), selected.getName().trim()); } private boolean handleExistingBinding( @@ -752,18 +762,8 @@ private Optional validateRuntimeAdmission( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, String tenantTag, - String requestedCharacter) { + long requestedCharacterId) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); - String characterName = resolveCharacterName(context, requestedCharacter); - long requestedCharacterId; - try { - requestedCharacterId = - resolveCharacterId(context, selectedRealm, requestedCharacter, characterName); - } catch (IllegalStateException ex) { - return Optional.of( - characterIdentityUnavailableFailure( - tenantTag, Long.toString(selectedRealm.gameInstanceId()), characterName, ex)); - } GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); @@ -1195,7 +1195,7 @@ private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { private boolean maybeRecordFreshEntryFallback( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, - String requestedCharacter, + String selectedCharacterName, long requestedGameInstanceId, long requestedCharacterId) { if (context.gameInstanceId() != requestedGameInstanceId @@ -1204,8 +1204,7 @@ private boolean maybeRecordFreshEntryFallback( } if (StringUtils.hasText(context.roomInstanceId()) && Objects.equals( - normalizeName(context.characterName()), - normalizeName(resolveCharacterName(context, requestedCharacter)))) { + normalizeName(context.characterName()), normalizeName(selectedCharacterName))) { return false; } meterRegistry @@ -1449,6 +1448,8 @@ private String charsUsage( private record ResolvedPlaySelection( String worldSelector, String explicitRealmSelector, String characterSelector) {} + private record ResolvedCharacter(long id, String name) {} + private void recordResumeDeniedIfApplicable( SessionContext context, String requestedWorldSlug, @@ -1458,13 +1459,18 @@ private void recordResumeDeniedIfApplicable( long requestedCharacterId, String tenantTag, String reason) { + boolean selectedTenantMatchesContext = hasMatchingTenantId(tenantTag, context.tenantId()); boolean sameGameplayIdentity = - context.gameInstanceId() == requestedGameInstanceId + selectedTenantMatchesContext + && context.gameInstanceId() == requestedGameInstanceId && context.characterId() == requestedCharacterId; boolean sameVisibleRealm = - sameSlug(context.worldSlug(), requestedWorldSlug) + selectedTenantMatchesContext + && sameSlug(context.worldSlug(), requestedWorldSlug) && sameSlug(context.realmSlug(), requestedRealmSlug); - if (!sameGameplayIdentity && !sameVisibleRealm) { + boolean sameRuntimeTarget = + selectedTenantMatchesContext && context.gameInstanceId() == requestedGameInstanceId; + if (!sameGameplayIdentity && !sameVisibleRealm && !sameRuntimeTarget) { return; } meterRegistry.counter(RESUME_DENIED_METRIC, "reason", reason).increment(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index dd470ef64d..67be0686d7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -158,6 +159,43 @@ void setUp() { Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); when(firstPartyConnectContextRegistry.find(Mockito.anyLong())).thenReturn(Optional.empty()); + when(entityManagementClient.listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class))) + .thenAnswer( + invocation -> { + String tenantId = invocation.getArgument(0); + String accountId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String name; + String characterId; + if ("41".equals(gameInstanceId)) { + name = "Emberline"; + characterId = "123"; + } else if ("2".equals(gameInstanceId)) { + name = "Emberline"; + characterId = "9007"; + } else if ("23".equals(tenantId)) { + name = "Sora"; + characterId = "7001"; + } else { + name = "demo"; + characterId = "7001"; + } + return ListCharactersByAccountResponse.newBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId(characterId) + .setTenantId(tenantId) + .setAccountId(accountId) + .setName(name) + .setPlayableStateScope(scope) + .build()) + .build(); + }); } @Test @@ -258,6 +296,120 @@ void playPromotesSessionIntoGameplay() { "play-spawn:1:1:7001:1"); } + @Test + void playUsesSelectedTargetRosterInsteadOfStaleContextCharacterId() { + SessionContext context = + new SessionContext( + 1L, 22L, 123L, "demo@example.com", 9999L, "demo", 41L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 8008L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + Mockito.verify(sessionContextService) + .save(Mockito.argThat(saved -> saved.characterId() == 8008L)); + Mockito.verify(gameplayPresenceLifecycleService) + .registerConnected(Mockito.argThat(saved -> saved.characterId() == 8008L)); + Mockito.verify(scriptEventPublisher) + .publishCommandEvent(Mockito.argThat(saved -> saved.characterId() == 8008L), Mockito.any()); + } + + @Test + void playRejectsSameNameCharacterFromAnotherAccountBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsMissingCharacterEvidenceBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsAmbiguousCharacterEvidenceBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + ListCharactersByAccountResponse roster = + characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .toBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("8009") + .setTenantId("22") + .setAccountId("123") + .setName("Demo") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build()) + .build(); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(roster); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsCharacterRosterErrorBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + ListCharactersByAccountResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("CHARACTER_LIST_UNAVAILABLE") + .setMessage("Character list unavailable")) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + @Test void numericWorldPlayRejectsReorderedWorldSnapshotBeforeAdmissionSideEffects() { SessionContext context = @@ -321,6 +473,11 @@ void numericWorldPlayTreatsUnrecognizedSecondSelectorAsCharacterWhenDefaultRealm .setId("7001") .setName("Sora") .build())); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7001", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -732,6 +889,11 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { .setId("9007") .setName("Emberline") .build())); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "9007", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) .thenReturn(Optional.empty()); @@ -817,6 +979,11 @@ void playRejectsMalformedResolvedCharacterId() { .setId("abc") .setName("Emberline") .build())); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "abc", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -1303,6 +1470,11 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { .setId("7002") .setName("Sora") .build())); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .thenReturn( + characterRoster( + "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -1353,6 +1525,11 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { .setId("7002") .setName("Sora") .build())); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .thenReturn( + characterRoster( + "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -1437,6 +1614,33 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); } + @Test + void playDeniedDoesNotClearCrossTenantSameSlugBinding() { + SessionContext context = + new SessionContext( + 1L, 23L, 123L, "demo@example.com", 7001L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + } + @Test void playActiveNonAdmittingMembershipDoesNotSuggestJoinOrBind() { SessionContext context = @@ -1750,6 +1954,71 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); } + @Test + void playPublicMissingMembershipReturnsJoinRequiredBeforeCharacterRosterLookup() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playPrivateDeniedReturnsPrivacyOutcomeBeforeCharacterRosterLookup() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + verifyNoGameplayBindingSideEffects(); + } + @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { SessionContext context = @@ -2151,7 +2420,7 @@ void staleRoomContextFallsBackToFreshEntry() { 22L, 123L, "demo@example.com", - 123L, + 7001L, "demo", 1L, gameLogicProperties.getDefaultRoomId(), @@ -2169,7 +2438,7 @@ void staleRoomContextFallsBackToFreshEntry() { "reason", "stale_or_missing_context") .count()) - .isEqualTo(1.0); + .isEqualTo(0.0); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( @@ -2177,7 +2446,7 @@ void staleRoomContextFallsBackToFreshEntry() { 22L, 123L, "demo@example.com", - 123L, + 7001L, "demo", 1L, gameLogicProperties.getDefaultRoomId(), @@ -2188,7 +2457,7 @@ void staleRoomContextFallsBackToFreshEntry() { "production", 1L, "SHARED"), - command("play-command:1:1:123:1", PLAY_COMMAND_NAME, "PLAY demo")); + command("play-command:1:1:7001:1", PLAY_COMMAND_NAME, "PLAY demo")); Mockito.verify(scriptEventPublisher) .publishSpawnEvent( new SessionContext( @@ -2196,7 +2465,7 @@ void staleRoomContextFallsBackToFreshEntry() { 22L, 123L, "demo@example.com", - 123L, + 7001L, "demo", 1L, gameLogicProperties.getDefaultRoomId(), @@ -2208,7 +2477,7 @@ void staleRoomContextFallsBackToFreshEntry() { 1L, "SHARED"), "play_entry", - "play-spawn:1:1:123:1"); + "play-spawn:1:1:7001:1"); } private static String joinedOutputText(List outputs) { @@ -2337,4 +2606,26 @@ private static GameplayCommand command(String commandId, String commandName, Str gameplayCommand.setCommandText(commandText); return gameplayCommand; } + + private static ListCharactersByAccountResponse characterRoster( + String id, String name, String tenantId, String accountId, PlayableStateScope scope) { + return ListCharactersByAccountResponse.newBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId(id) + .setTenantId(tenantId) + .setAccountId(accountId) + .setName(name) + .setPlayableStateScope(scope) + .build()) + .build(); + } + + private void verifyNoGameplayBindingSideEffects() { + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); + Mockito.verify(scriptEventPublisher, never()) + .publishSpawnEvent(Mockito.any(), Mockito.any(), Mockito.any()); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 29f8713c4e..ad230decf8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -406,9 +406,9 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { context -> context.sessionId() == 1L && context.gameInstanceId() == 1L - && context.characterId() == 77L + && context.characterId() == 7001L && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("disconnect:takeover:1:1:77"), + Mockito.eq("disconnect:takeover:1:1:7001"), Mockito.eq("TAKEOVER")); assertEquals(1.0, meterRegistry.counter("gamesession.session.takeover").count()); assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 1846046736..c60993b024 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -425,7 +425,7 @@ void setUp() { .setTenantId("22") .setAccountId("123") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setName("Emberline") + .setName("demo") .setLevel(12) .build()) .build()); @@ -553,7 +553,7 @@ void charsAreVisibleAfterLogin() { interpreter.interpret("1", "CHARS demo", false); assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("CHARS demo", interpretation).contains("Emberline")); + assertTrue(renderedResponse("CHARS demo", interpretation).contains("demo")); assertTrue( renderedResponse("CHARS demo", interpretation) .contains("Realm state: shared, creation: allow_new")); From 2123f48de81b4ea9d4b94f0e7df36dcff209f014 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 21:20:18 +1300 Subject: [PATCH 023/105] Preserve catalog failure classification after parent reconciliation --- .../command/text/GameplayWorldCatalog.java | 1 + .../text/GameplayWorldCatalogTest.java | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index d5f2759676..c51a08b0c8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -260,6 +260,7 @@ public Optional resolveWorldFromAuthoritySnapshot(String selector) { "Authoritative gameplay pointer is incomplete"); } } + requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); CatalogState catalogState = catalogStateFromPointers(pointers); List visibleWorlds = catalogState.worlds().stream().filter(this::hasVisibleRealmEntries).toList(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 85ddb1e7e8..31b7c434c8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -183,6 +183,29 @@ void authoritySnapshotRejectsTenantWithoutVisiblePublicRealm() { .hasMessageContaining("public-production realm count is invalid"); } + @ParameterizedTest(name = "authority selector resolution rejects {0} public realms") + @MethodSource("invalidPublicRealmCardinalities") + void resolveWorldFromAuthoritySnapshotRejectsInvalidPublicRealmCardinalityBeforeLookup( + String cardinality, List pointers) { + when(authorityService.listPointers()).thenReturn(pointers); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(() -> catalog.resolveWorldFromAuthoritySnapshot("unknown-world")) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasMessageContaining("public-production realm count is invalid"); + Mockito.verify(authorityService, Mockito.times(1)).listPointers(); + } + + @Test + void resolveWorldFromAuthoritySnapshotKeepsHealthyUnknownSelectorAsEmpty() { + when(authorityService.listPointers()) + .thenReturn(List.of(publicPointer("demo", "Demo World", 1L, 11L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.resolveWorldFromAuthoritySnapshot("unknown-world")).isEmpty(); + Mockito.verify(authorityService, Mockito.times(1)).listPointers(); + } + @Test void authoritySnapshotKeepsPrivateRealmsWhenTenantHasOneVisiblePublicRealm() { when(authorityService.listPointers()) @@ -670,6 +693,17 @@ private static Stream incompleteAuthorityPointers() { "shared"))); } + private static Stream invalidPublicRealmCardinalities() { + return Stream.of( + Arguments.of( + "zero", List.of(pointer("demo", "Demo World", "private", "Private", 1L, 11L, 7L))), + Arguments.of( + "multiple", + List.of( + publicPointer("alpha", "Alpha World", 1L, 11L), + publicPointer("beta", "Beta World", 1L, 12L)))); + } + private static GameplayAdmissionPointerSnapshot copyAuthorityPointer( GameplayAdmissionPointerSnapshot pointer, long catalogRevision, From 6aa904d1624ce7eb14917632bfa7d7a0977a29bd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 04:49:03 +1300 Subject: [PATCH 024/105] Hide inaccessible realms in character browse responses --- .../command/text/WorldsCommandHandler.java | 7 +- .../text/WorldsCommandHandlerTest.java | 60 +++++++++++ .../WorldsTextCommandDispatchHandlerTest.java | 101 ++++++++++++++++++ 3 files changed, 165 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 9992816637..79231e0b8f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -835,9 +835,10 @@ public CharacterBrowseResult browseCharacters( : mapNonPublicCharacterAuthorization( authorizeNonPublicRealm(sessionContext, world, realm, requestId)); if (authorization != CharacterBrowseAuthorization.AUTHORIZED) { - if (!worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) - && authorization.isDefinitiveAccessDenial()) { - return CharacterBrowseResult.invalidWorld(); + if (!realm.publicProductionRealm() && authorization.isDefinitiveAccessDenial()) { + return worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) + ? CharacterBrowseResult.invalidRealm(world.slug()) + : CharacterBrowseResult.invalidWorld(); } return CharacterBrowseResult.failure(authorization.code()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 00a0608c95..3584549ad3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -742,6 +742,52 @@ void browseRealmsOmitsActivePrivateMembershipWithoutAdmissionWhileCharactersDeny Mockito.anyString()); } + @Test + void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + publicMembership(false, false, 0L, 0L, "MISSING"), + publicMembership(true, false, 1L, 1L, "INACTIVE"), + activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("playtest"), + Mockito.anyString())) + .thenReturn(grant("demo", "playtest", false)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult unknownRealm = + localHandler.browseCharacters(authenticatedSession(), "demo", "guessed"); + assertThat(unknownRealm) + .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.InvalidRealm("demo")); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) + .isEqualTo(unknownRealm); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) + .isEqualTo(unknownRealm); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) + .isEqualTo(unknownRealm); + + Mockito.verify(accountClient, Mockito.times(3)) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(accountClient, Mockito.times(1)) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("playtest"), + Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + } + @Test void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoster() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -1851,6 +1897,20 @@ private GameplayCatalogProperties publicProductionProperties() { return properties; } + private GameplayCatalogProperties publicWorldWithPrivateRealm() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + GameplayCatalogProperties.World world = world("demo", 22L, 1L, false); + GameplayCatalogProperties.Realm production = world.getRealms().getFirst(); + production.setPublicProductionRealm(true); + GameplayCatalogProperties.Realm playtest = world("demo", 22L, 2L, false).getRealms().getFirst(); + playtest.setSlug("playtest"); + playtest.setDisplayName("Playtest Realm"); + playtest.setPublicProductionRealm(false); + world.setRealms(List.of(production, playtest)); + properties.setWorlds(List.of(world)); + return properties; + } + private void assertPublicMembershipFailsClosed(GetTenantMembershipForRuntimeResponse membership) { AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index b0091335ef..d96b66469d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -237,6 +237,98 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { && "CHARS demo".equals(gameplayCommand.getCommandText()))); } + @Test + void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { + GameplayCatalogProperties.World world = world("demo", 22L, 1L, false); + GameplayCatalogProperties.Realm production = world.getRealms().getFirst(); + production.setPublicProductionRealm(true); + GameplayCatalogProperties.Realm playtest = world("demo", 22L, 2L, false).getRealms().getFirst(); + playtest.setSlug("playtest"); + playtest.setDisplayName("Playtest Realm"); + playtest.setPublicProductionRealm(false); + world.setRealms(List.of(production, playtest)); + gameplayCatalogProperties.setWorlds(List.of(world)); + + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt(Instant.now().toString()) + .build(), + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setMembershipLifecycleState("INACTIVE") + .setEvaluatedAt(Instant.now().toString()) + .build(), + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setMembershipLifecycleState("ACTIVE") + .setEvaluatedAt(Instant.now().toString()) + .build()); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("playtest"), + Mockito.anyString())) + .thenReturn( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setWorldSlug("demo") + .setRealmSlug("playtest") + .setGranted(false) + .setEvaluatedAt(Instant.now().toString()) + .build()); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); + SessionContext context = + new SessionContext( + 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + + TextCommandInterpretationResult unknownRealm = + scopedHandler.handle(charsRequest("guessed", context)); + assertThat(unknownRealm.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(unknownRealm.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isEqualTo( + new net.firedevops.firemud.gamesession.presentation.ErrorOutput( + "INVALID_ARGUMENT", "Use REALMS demo to choose a visible realm first.")); + + for (int i = 0; i < 3; i++) { + TextCommandInterpretationResult deniedRealm = + scopedHandler.handle(charsRequest("playtest", context)); + assertThat(deniedRealm.commandResult().errorCode()) + .isEqualTo(unknownRealm.commandResult().errorCode()); + assertThat(deniedRealm.outputs()).isEqualTo(unknownRealm.outputs()); + } + + Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + } + @Test void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); @@ -576,4 +668,13 @@ private static GameplayCatalogProperties.World world( world.setRealms(List.of(realm)); return world; } + + private TextCommandDispatchRequest charsRequest(String realmSelector, SessionContext context) { + return new TextCommandDispatchRequest( + "7", + new TextCommand( + TextCommandType.CHARS, List.of("demo", realmSelector), "CHARS demo " + realmSelector), + false, + Optional.of(context)); + } } From 08819aef1a0a0882ddddda271154f79cdecb3784 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 04:49:03 +1300 Subject: [PATCH 025/105] Preserve authenticated lobby after denied gameplay admission --- .../command/text/PlayCommandHandler.java | 6 +- .../command/text/PlayCommandHandlerTest.java | 216 +++++++++++++----- .../text/SessionResumptionFlowTest.java | 28 ++- 3 files changed, 189 insertions(+), 61 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 2ed761e521..e214d8b6d3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1479,13 +1479,13 @@ && sameSlug(context.worldSlug(), requestedWorldSlug) new SessionContext( context.sessionId(), context.tenantId(), + context.accountId(), + context.loginName(), 0L, null, 0L, null, - 0L, - null, - null, + context.jwt(), context.localeTag(), context.bootstrapGameInstanceId(), requestedWorldSlug, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 26f2541177..72d814ad8a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -14,6 +14,8 @@ import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; @@ -21,6 +23,7 @@ import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; import net.firedevops.firemud.gamesession.config.GameLogicProperties; +import net.firedevops.firemud.gamesession.config.GameSessionProperties; import net.firedevops.firemud.gamesession.config.PresentationProperties; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameplayCommand; @@ -43,6 +46,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; class PlayCommandHandlerTest { @@ -1975,35 +1979,7 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { - SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("MISSING") - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setEvaluatedAt(evaluatedAtNow()) - .build()); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); - assertThat(result.commandResult().errorMessage()) - .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_MESSAGE); - assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) - .isEqualTo("error.play.join-required"); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); + assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoin(false, "MISSING", 0L, 0L); } @Test @@ -2073,34 +2049,7 @@ void playPrivateDeniedReturnsPrivacyOutcomeBeforeCharacterRosterLookup() { @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { - SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("INACTIVE") - .setMembershipVersion(4L) - .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt(evaluatedAtNow()) - .build()); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); - assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) - .isEqualTo("error.play.join-required"); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); + assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoin(true, "INACTIVE", 4L, 1L); } @Test @@ -2603,6 +2552,159 @@ private TextCommand previewRealmPlayCommand() { "PLAY sandbox preview Emberline"); } + private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoin( + boolean membershipExists, + String lifecycleState, + long membershipVersion, + long membershipAuthorityGeneration) { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1", + "jwt-token", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "login-account-scope", + "login-account-request"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(membershipExists) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState(lifecycleState) + .setMembershipVersion(membershipVersion) + .setMembershipAuthorityGeneration(membershipAuthorityGeneration) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_MESSAGE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.join-required"); + assertThat( + meterRegistry + .counter("gamesession.session.resume_denied", "reason", "join_required") + .count()) + .isEqualTo(1.0); + Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); + + ArgumentCaptor savedContextCaptor = + ArgumentCaptor.forClass(SessionContext.class); + Mockito.verify(sessionContextService).save(savedContextCaptor.capture()); + SessionContext savedContext = savedContextCaptor.getValue(); + assertThat(savedContext.accountId()).isEqualTo(context.accountId()); + assertThat(savedContext.loginName()).isEqualTo(context.loginName()); + assertThat(savedContext.jwt()).isEqualTo(context.jwt()); + assertThat(savedContext.connectScopeId()).isEqualTo(context.connectScopeId()); + assertThat(savedContext.connectRequestId()).isEqualTo(context.connectRequestId()); + assertThat(savedContext.localeTag()).isEqualTo(context.localeTag()); + assertThat(savedContext.bootstrapGameInstanceId()).isEqualTo(context.bootstrapGameInstanceId()); + assertThat(savedContext.characterId()).isZero(); + assertThat(savedContext.characterName()).isNull(); + assertThat(savedContext.gameInstanceId()).isZero(); + assertThat(savedContext.roomInstanceId()).isNull(); + assertThat(savedContext.playableStateScope()).isNull(); + assertThat(savedContext.worldSlug()).isEqualTo("demo"); + assertThat(savedContext.realmSlug()).isEqualTo("production"); + assertThat(savedContext.pointerVersion()).isEqualTo(1L); + + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(entityManagementClient, never()) + .findCharacterByName( + Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, never()) + .publishCommandEvent(Mockito.any(), Mockito.any(GameplayCommand.class)); + Mockito.verify(scriptEventPublisher, never()) + .publishSpawnEvent(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, never()) + .joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + + when(sessionContextService.findBySessionId(1L)).thenReturn(Optional.of(savedContext)); + when(sessionContextService.findByTenantAndSessionId(22L, 1L)) + .thenReturn(Optional.of(savedContext)); + SessionRoutingNormalizationService realRoutingNormalizationService = + new SessionRoutingNormalizationService( + sessionContextService, Mockito.mock(GameplayAdmissionPointerAuthorityService.class)); + SessionAuthenticationService realSessionAuthenticationService = + new SessionAuthenticationService( + sessionContextService, + new GameSessionProperties(), + realRoutingNormalizationService, + gameplayPresenceLifecycleService); + SessionContext resolvedContext = + realSessionAuthenticationService.resolveSessionContext("1").orElseThrow(); + assertThat(resolvedContext).isEqualTo(savedContext); + assertThat(resolvedContext.accountId()).isEqualTo(123L); + Mockito.verify(sessionContextService, Mockito.times(1)).save(Mockito.any()); + + String exactJoinScopeId = "account-issued-join-scope"; + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(exactJoinScopeId) + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + when(accountClient.joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); + WorldsCommandHandler worldsCommandHandler = + new WorldsCommandHandler( + worldCatalog, entityManagementClient, accountClient, connectScopeSessionStore); + assertThat(worldsCommandHandler.browseRealms(resolvedContext, "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + WorldsTextCommandDispatchHandler worldsDispatchHandler = + new WorldsTextCommandDispatchHandler(worldsCommandHandler, scriptEventPublisher); + TextCommandInterpretationResult joinResult = + worldsDispatchHandler.handle( + new TextCommandDispatchRequest( + "1", + new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo"), + false, + Optional.of(resolvedContext))); + assertThat(joinResult.commandResult()).isEqualTo(CommandEnqueueResult.success()); + + ArgumentCaptor playerContextCaptor = + ArgumentCaptor.forClass(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + ArgumentCaptor scopeIdCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(String.class); + Mockito.verify(accountClient) + .joinPublicProductionMembership( + playerContextCaptor.capture(), scopeIdCaptor.capture(), requestIdCaptor.capture()); + assertThat(scopeIdCaptor.getValue()).isEqualTo(exactJoinScopeId); + assertThat(playerContextCaptor.getValue().getAccountId()).isEqualTo("123"); + assertThat(playerContextCaptor.getValue().getSessionId()).isEqualTo("1"); + assertThat(playerContextCaptor.getValue().getTenantId()).isEqualTo("22"); + assertThat(playerContextCaptor.getValue().getRequestId()).isEqualTo(requestIdCaptor.getValue()); + } + private static GameplayCatalogProperties.World world( String slug, String displayName, List realms) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index ad230decf8..73b0c7fab7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -490,14 +491,39 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { TextCommandInterpretationResult secondLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); assertTrue(secondLogin.commandResult().accepted()); + SessionContext authenticatedContextBeforeDeniedPlay = + sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow(); + assertEquals(77L, authenticatedContextBeforeDeniedPlay.accountId()); + assertEquals("demo@example.com", authenticatedContextBeforeDeniedPlay.loginName()); + assertEquals("jwt", authenticatedContextBeforeDeniedPlay.jwt()); + assertTrue(authenticatedContextBeforeDeniedPlay.hasGameplayRegionBinding()); + TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertFalse(deniedPlay.commandResult().accepted()); assertEquals("JOIN_REQUIRED", deniedPlay.commandResult().errorCode()); + SessionContext authenticatedLobbyContext = + sessionAuthenticationService.resolveSessionContext("1").orElseThrow(); + assertEquals( + authenticatedContextBeforeDeniedPlay.accountId(), authenticatedLobbyContext.accountId()); + assertEquals( + authenticatedContextBeforeDeniedPlay.loginName(), authenticatedLobbyContext.loginName()); + assertEquals(authenticatedContextBeforeDeniedPlay.jwt(), authenticatedLobbyContext.jwt()); + assertEquals(0L, authenticatedLobbyContext.gameInstanceId()); + assertEquals(0L, authenticatedLobbyContext.characterId()); + assertNull(authenticatedLobbyContext.characterName()); + assertNull(authenticatedLobbyContext.roomInstanceId()); + assertNull(authenticatedLobbyContext.playableStateScope()); + assertFalse( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(presence -> presence.sessionId() == 1L)); + Mockito.verify(accountClient, Mockito.never()) + .joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); assertFalse(lookAfterDeniedReconnect.commandResult().accepted()); - assertEquals("LOGIN_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); + assertEquals("PLAY_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); } @Test From 70f7038ff1901863d625e0e2e1f341ba484c2b8d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 05:13:18 +1300 Subject: [PATCH 026/105] Keep REALMS runtime targets server-side --- .../command/text/GameplayWorldCatalog.java | 1 - .../command/text/WorldsCommandHandler.java | 1 - .../presentation/RealmBrowseViewOutput.java | 1 - .../WebSocketOutputProjectorTest.java | 43 +++++++++++++++++++ 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index c51a08b0c8..2595a01242 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -783,7 +783,6 @@ private List realmEntries(WorldView world) { i + 1, realm.slug(), realm.displayName(), - realm.gameInstanceId(), realm.requiresCharacterSelection(), realm.stateScope(), realm.characterCreationPolicy())); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 79231e0b8f..85a8fce497 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -698,7 +698,6 @@ private RealmBrowseViewOutput.RealmEntry realmEntry( ordinal, realm.slug(), realm.displayName(), - realm.gameInstanceId(), realm.requiresCharacterSelection(), realm.stateScope(), realm.characterCreationPolicy()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java index aceaec97b7..1d5ea3a487 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java @@ -15,7 +15,6 @@ public record RealmEntry( int ordinal, String realmSlug, String displayName, - long gameInstanceId, boolean requiresCharacterSelection, String stateScope, String characterCreationPolicy) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index e6d4c63271..7f8a9ce394 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -11,6 +11,7 @@ import java.util.List; import java.util.Map; import net.firedevops.firemud.cache.ScreenBufferService; +import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.command.text.AdmittedTextCommandRegistryResolver; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandActionCategory; @@ -30,9 +31,11 @@ import net.firedevops.firemud.gamesession.presentation.ItemMutationResultOutput; import net.firedevops.firemud.gamesession.presentation.LookViewOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WhoViewOutput; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.Test; import org.springframework.web.socket.WebSocketSession; @@ -114,6 +117,46 @@ void firstPartyWebReceivesStructuredCommandEnvelope() throws Exception { .isEqualTo("demo> "); } + @Test + void firstPartyRealmsCommandDoesNotExposeRuntimeTargetOrEnterReplayBuffer() throws Exception { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + RealmBrowseViewOutput realms = + TestGameplayWorldCatalogs.fromProperties(new GameplayCatalogProperties()) + .browseRealms("sandbox") + .orElseThrow(); + PlayerOutput output = PlayerOutput.view(realms); + + String payload = + projector.projectCommandResponse( + session, + new TextCommand(TextCommandType.REALMS, List.of("sandbox"), "REALMS sandbox"), + new TextCommandInterpretationResult(CommandEnqueueResult.success(), List.of(output)), + List.of(output), + "en-NZ", + presentation); + + JsonNode json = objectMapper.readTree(payload); + JsonNode outputJson = json.path("outputs").get(0); + JsonNode realmJson = outputJson.path("payload").path("realms").get(0); + assertThat(json.path("eventType").asText()).isEqualTo("command_result"); + assertThat(json.path("commandType").asText()).isEqualTo("REALMS"); + assertThat(json.path("accepted").asBoolean()).isTrue(); + assertThat(outputJson.path("payloadType").asText()).isEqualTo("realms_view"); + assertThat(outputJson.path("replayPolicy").asText()).isEqualTo("NO_REPLAY"); + assertThat(realmJson.path("ordinal").asInt()).isEqualTo(1); + assertThat(realmJson.path("realmSlug").asText()).isEqualTo("production"); + assertThat(realmJson.path("displayName").asText()).isEqualTo("Live Realm"); + assertThat(realmJson.path("requiresCharacterSelection").asBoolean()).isTrue(); + assertThat(realmJson.path("stateScope").asText()).isEqualTo("SHARED"); + assertThat(realmJson.path("characterCreationPolicy").asText()).isEqualTo("ALLOW_NEW"); + assertThat(realmJson.has("gameInstanceId")).isFalse(); + assertThat(output.screenBufferEligible()).isFalse(); + } + @Test void firstPartyWebReceivesCanonicalAuthoredCommandId() throws Exception { WebSocketSession session = mock(WebSocketSession.class); From 9b8d1fc4917f4e0acb49e1f897f9ae70ce853ffa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 05:46:09 +1300 Subject: [PATCH 027/105] Classify final PLAY authority outages as retryable --- .../command/text/PlayCommandHandler.java | 11 +++- .../command/text/PlayCommandHandlerTest.java | 61 +++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index e214d8b6d3..ba62369132 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -335,8 +335,15 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { currentPointerMatches = gameplayWorldCatalog.matchesCurrentAdmissionPointer(selectedWorld, selectedRealm); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { - return admissionPointerUnavailableFailure( - selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); + return failure( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE, + "error.play.authority-unavailable", + Map.of(), + selectedTenantTag, + Long.toString(selectedRealm.gameInstanceId()), + null, + ex); } if (!currentPointerMatches) { return admissionPointerUnavailableFailure( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 72d814ad8a..4882253d8e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -810,6 +810,67 @@ void playRejectsPointerRevisionCutoverBeforeAdmissionReads() { scriptEventPublisher); } + @ParameterizedTest + @ValueSource(strings = {"throw", "null"}) + void playMapsFinalPointerReadOutageToAuthUnavailableWithoutAdmissionSideEffects( + String failureMode) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + AtomicInteger pointerReads = new AtomicInteger(); + when(authorityService.listPointers()) + .thenAnswer( + invocation -> { + if (pointerReads.getAndIncrement() == 0) { + return List.of(admissionPointer(1L)); + } + if ("throw".equals(failureMode)) { + throw new IllegalStateException("authority down on final read"); + } + return null; + }); + PlayCommandHandler authorityBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authorityService), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + connectScopeSessionStore); + SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + authorityBackedHandler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE); + assertThat(((ErrorOutput) result.outputs().getFirst().payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + assertThat(pointerReads).hasValue(2); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + Mockito.verify(firstPartyConnectContextRegistry, never()) + .register(Mockito.anyLong(), Mockito.any()); + Mockito.verify(firstPartyConnectContextRegistry, never()).unregister(Mockito.anyLong()); + } + @Test void playMapsPointerAuthorityReadFailureBeforeAccountOrEntityAdmissionReads() { GameplayAdmissionPointerAuthorityService authorityService = From a2551ce8faf7b572e8d53aa6dcd715322f918ce8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 06:17:56 +1300 Subject: [PATCH 028/105] Localize direct-text JOIN responses and align session status --- .../system-architecture-session-behavior.md | 2 +- .../WorldsTextCommandDispatchHandler.java | 42 +++- .../presentation-messages.properties | 9 + .../presentation-messages_fr.properties | 9 + .../WorldsTextCommandDispatchHandlerTest.java | 223 +++++++++++++++++- 5 files changed, 276 insertions(+), 9 deletions(-) diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index cb1c1b4ef8..163f150a61 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -30,7 +30,7 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no ## Implementation Status -Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `evaluatedAt`, and `error`; the current Game Session `PLAY` path consumes that response, while roles, the target exact one-tenant `membershipVersion` map carrier, `membershipAuthorityGeneration`, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. +Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`; the current Game Session text `PLAY` path validates this lifecycle and generation evidence before admission. Roles, the target exact one-tenant `membershipVersion` map carrier, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware event consumers, same-stream reconciliation, remaining player-facing legacy mapping, and complete proof across admission/reconnect paths remain gaps; the bounded text `PLAY` checks do not establish those broader guarantees. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. Account Service is the sole writer of account authority-generation advances and all canonical `session:auth:generation:*` projections, including `session:auth:generation:account:`. Account commits every applicable canonical tuple field, cutoff, `issuanceFence`, and monotonic outbox event together; the generation projection is an asynchronous outbox output, not an atomically committed part of that durable generation/event transaction. Game Session and other downstream services consume Account-owned generation events and projections; they must not advance canonical authority or write canonical projections directly, and they fail closed while projection or freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Game Session's only generation projection write is its derived `session:game:auth:issuer-generation:v1:` consumer-local record under the ADR 0022 schema. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index c38a33afa0..ede8ed3609 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -91,13 +91,16 @@ private TextCommandInterpretationResult handleRealms(TextCommandDispatchRequest private TextCommandInterpretationResult handleJoin(TextCommandDispatchRequest request) { if (request.command().joinRequestPayload().isEmpty() || request.sessionContext().isEmpty()) { - return errorResult("INVALID_ARGUMENT", "JOIN requires a world selector after LOGIN."); + return joinErrorResult( + "INVALID_ARGUMENT", + "JOIN requires a world selector after LOGIN.", + "error.join.invalid-request"); } TextCommandPayload.JoinRequest payload = request.command().joinRequestPayload().orElseThrow(); return switch (worldsHandler.joinPublicProductionMembership( request.sessionId(), request.sessionContext().orElseThrow(), payload.worldSelector())) { case WorldsCommandHandler.JoinMembershipResult.Failure failure -> - errorResult(failure.code(), joinFailureMessage(failure.code())); + joinErrorResult(failure.code()); case WorldsCommandHandler.JoinMembershipResult.Response response -> handleJoinResponse(response.response()); }; @@ -110,17 +113,19 @@ private TextCommandInterpretationResult handleJoinResponse( if (code.isBlank()) { code = "JOIN_FAILED"; } - return errorResult(code, joinFailureMessage(code)); + return joinErrorResult(code); } if (!response.getSuccess()) { String code = response.getOutcomeCode().isBlank() ? "JOIN_FAILED" : response.getOutcomeCode(); - return errorResult(code, joinFailureMessage(code)); + return joinErrorResult(code); } return new TextCommandInterpretationResult( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.notice( - "Membership is ready. Continue with CHARS and PLAY."))); + "Membership is ready. Continue with CHARS and PLAY.", + "notice.join.success", + java.util.Map.of()))); } private String realmBrowseFailureMessage(String code) { @@ -148,6 +153,33 @@ private String joinFailureMessage(String code) { }; } + private String joinFailureMessageKey(String code) { + return switch (code) { + case "CONNECT_SCOPE_INVALID" -> "error.join.connect-scope-invalid"; + case "CONNECT_SCOPE_MISMATCH" -> "error.join.connect-scope-mismatch"; + case "MEMBERSHIP_RECONCILIATION_REQUIRED" -> "error.join.membership-reconciliation-required"; + case "AUTH_UNAVAILABLE", "UNAVAILABLE", "DEADLINE_EXCEEDED" -> + "error.join.authority-unavailable"; + case "ENTITLEMENT_UNAVAILABLE" -> "error.join.entitlement-unavailable"; + case "LOGIN_REQUIRED" -> "error.join.login-required"; + default -> "error.join.failed"; + }; + } + + private TextCommandInterpretationResult joinErrorResult(String code) { + String message = joinFailureMessage(code); + return joinErrorResult(code, message, joinFailureMessageKey(code)); + } + + private TextCommandInterpretationResult joinErrorResult( + String code, String message, String messageKey) { + return new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.failure(code, message), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.error( + code, message, messageKey, java.util.Map.of()))); + } + private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest request) { if (request.command().characterBrowsePayload().isEmpty() || request.sessionContext().isEmpty()) { diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 016d634978..bdce22b8f4 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -25,6 +25,15 @@ error.play.public-production-admission-denied=Public joining is not available fo error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. error.play.entitlement-unavailable=Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. error.play.billing-blocked=That world is temporarily unavailable for gameplay. +error.join.connect-scope-invalid=Join scope is invalid or expired. Run REALMS again. +error.join.connect-scope-mismatch=Join scope expired or changed. Run REALMS again. +error.join.membership-reconciliation-required=Membership needs reconciliation. Contact support before retrying JOIN. +error.join.authority-unavailable=Account authority unavailable. Retry JOIN shortly. +error.join.entitlement-unavailable=Join policy could not be checked. Retry the same JOIN while its realm scope is valid. +error.join.login-required=Log in before joining a world. +error.join.invalid-request=JOIN requires a world selector after LOGIN. +error.join.failed=The selected world could not be joined. +notice.join.success=Membership is ready. Continue with CHARS and PLAY. error.look.room-not-found=Room not found. error.look.world-unavailable=World data is temporarily unavailable. error.look.entity-unavailable=Nearby entity state is temporarily unavailable. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index d87355bdc4..479057d57f 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -25,6 +25,15 @@ error.play.public-production-admission-denied=L’adhésion publique n’est pas error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.entitlement-unavailable=L’autorité d’abonnement est temporairement indisponible. Réessayez PLAY sous peu. error.play.billing-blocked=Ce monde est temporairement indisponible pour le jeu. +error.join.connect-scope-invalid=La portée de JOIN est invalide ou expirée. Relancez REALMS. +error.join.connect-scope-mismatch=La portée de JOIN a expiré ou changé. Relancez REALMS. +error.join.membership-reconciliation-required=L’adhésion nécessite une réconciliation. Contactez le support avant de réessayer JOIN. +error.join.authority-unavailable=L’autorité du compte est indisponible. Réessayez JOIN sous peu. +error.join.entitlement-unavailable=La politique d’adhésion n’a pas pu être vérifiée. Réessayez le même JOIN tant que la portée de son royaume est valide. +error.join.login-required=Connectez-vous avant de rejoindre un monde. +error.join.invalid-request=JOIN requiert un sélecteur de monde après LOGIN. +error.join.failed=Le monde sélectionné n’a pas pu être rejoint. +notice.join.success=L’adhésion est prête. Continuez avec CHARS et PLAY. error.look.room-not-found=Salle introuvable. error.look.world-unavailable=Les donnees du monde sont temporairement indisponibles. error.look.entity-unavailable=L’état des entités proches est temporairement indisponible. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index d96b66469d..82c7c6c006 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Stream; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; @@ -20,12 +21,16 @@ import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; +import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; class WorldsTextCommandDispatchHandlerTest { @@ -496,7 +501,9 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .isEqualTo( new net.firedevops.firemud.gamesession.presentation.ErrorOutput( "ENTITLEMENT_UNAVAILABLE", - "Join policy could not be checked. Retry the same JOIN while its realm scope is valid.")); + "Join policy could not be checked. Retry the same JOIN while its realm scope is valid.", + "error.join.entitlement-unavailable", + java.util.Map.of())); assertThat(retryJoinResult.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); assertThat(finalJoinResult.commandResult().accepted()).isTrue(); assertThat(realmsResult.outputs()) @@ -639,7 +646,10 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { .extracting(output -> output.payload()) .isEqualTo( new net.firedevops.firemud.gamesession.presentation.ErrorOutput( - "CONNECT_SCOPE_INVALID", "Join scope is invalid or expired. Run REALMS again.")); + "CONNECT_SCOPE_INVALID", + "Join scope is invalid or expired. Run REALMS again.", + "error.join.connect-scope-invalid", + java.util.Map.of())); assertThat(reconciliationResult.commandResult().errorCode()) .isEqualTo("MEMBERSHIP_RECONCILIATION_REQUIRED"); assertThat(reconciliationResult.outputs()) @@ -648,7 +658,214 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { .isEqualTo( new net.firedevops.firemud.gamesession.presentation.ErrorOutput( "MEMBERSHIP_RECONCILIATION_REQUIRED", - "Membership needs reconciliation. Contact support before retrying JOIN.")); + "Membership needs reconciliation. Contact support before retrying JOIN.", + "error.join.membership-reconciliation-required", + java.util.Map.of())); + } + + @Test + void joinMissingSelectorRendersLocalizedErrorWithoutCallingAccount() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); + TextCommand command = new TextCommand(TextCommandType.JOIN, List.of(), "JOIN"); + TextCommandInterpretationResult result = + scopedHandler.handle(new TextCommandDispatchRequest("7", command, false, Optional.empty())); + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()); + var error = + (net.firedevops.firemud.gamesession.presentation.ErrorOutput) + result.outputs().getFirst().payload(); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("JOIN requires a world selector after LOGIN."); + assertThat(error.code()).isEqualTo("INVALID_ARGUMENT"); + assertThat(error.message()).isEqualTo("JOIN requires a world selector after LOGIN."); + assertThat(error.messageKey()).isEqualTo("error.join.invalid-request"); + assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "fr")) + .isEqualTo("ERROR INVALID_ARGUMENT JOIN requiert un sélecteur de monde après LOGIN."); + assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "de")) + .isEqualTo("ERROR INVALID_ARGUMENT JOIN requires a world selector after LOGIN."); + Mockito.verifyNoInteractions(accountClient); + } + + @ParameterizedTest + @MethodSource("joinPresentationCases") + void joinDispatchOutputsRenderLocalizedGuidanceAndEnglishFallback( + String outcomeCode, + boolean success, + String expectedCode, + String expectedEnglish, + String expectedFrench) { + TextCommandInterpretationResult result = dispatchJoinOutcome(outcomeCode, success); + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()); + TextCommand command = + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"); + + assertThat(result.commandResult().accepted()).isEqualTo(success); + assertThat(result.outputs().getFirst().replayPolicy()) + .isEqualTo(net.firedevops.firemud.gamesession.presentation.ReplayPolicy.NO_REPLAY); + assertThat(result.outputs().getFirst().briefRenderPolicy()) + .isEqualTo(net.firedevops.firemud.gamesession.presentation.BriefRenderPolicy.ALWAYS_SHOW); + if (!success) { + assertThat(result.commandResult().errorCode()).isEqualTo(expectedCode); + assertThat(result.commandResult().errorMessage()).isEqualTo(expectedEnglish); + var error = + (net.firedevops.firemud.gamesession.presentation.ErrorOutput) + result.outputs().getFirst().payload(); + assertThat(error.code()).isEqualTo(expectedCode); + assertThat(error.message()).isEqualTo(expectedEnglish); + } + + assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "fr")) + .isEqualTo(expectedFrench); + assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "de")) + .isEqualTo( + success + ? "OK JOIN " + expectedEnglish + : "ERROR " + expectedCode + " " + expectedEnglish); + } + + private static Stream joinPresentationCases() { + return Stream.of( + Arguments.of( + "CONNECT_SCOPE_INVALID", + false, + "CONNECT_SCOPE_INVALID", + "Join scope is invalid or expired. Run REALMS again.", + "ERROR CONNECT_SCOPE_INVALID La portée de JOIN est invalide ou expirée. Relancez REALMS."), + Arguments.of( + "CONNECT_SCOPE_MISMATCH", + false, + "CONNECT_SCOPE_MISMATCH", + "Join scope expired or changed. Run REALMS again.", + "ERROR CONNECT_SCOPE_MISMATCH La portée de JOIN a expiré ou changé. Relancez REALMS."), + Arguments.of( + "MEMBERSHIP_RECONCILIATION_REQUIRED", + false, + "MEMBERSHIP_RECONCILIATION_REQUIRED", + "Membership needs reconciliation. Contact support before retrying JOIN.", + "ERROR MEMBERSHIP_RECONCILIATION_REQUIRED L’adhésion nécessite une réconciliation. Contactez le support avant de réessayer JOIN."), + Arguments.of( + "AUTH_UNAVAILABLE", + false, + "AUTH_UNAVAILABLE", + "Account authority unavailable. Retry JOIN shortly.", + "ERROR AUTH_UNAVAILABLE L’autorité du compte est indisponible. Réessayez JOIN sous peu."), + Arguments.of( + "UNAVAILABLE", + false, + "UNAVAILABLE", + "Account authority unavailable. Retry JOIN shortly.", + "ERROR UNAVAILABLE L’autorité du compte est indisponible. Réessayez JOIN sous peu."), + Arguments.of( + "DEADLINE_EXCEEDED", + false, + "DEADLINE_EXCEEDED", + "Account authority unavailable. Retry JOIN shortly.", + "ERROR DEADLINE_EXCEEDED L’autorité du compte est indisponible. Réessayez JOIN sous peu."), + Arguments.of( + "ENTITLEMENT_UNAVAILABLE", + false, + "ENTITLEMENT_UNAVAILABLE", + "Join policy could not be checked. Retry the same JOIN while its realm scope is valid.", + "ERROR ENTITLEMENT_UNAVAILABLE La politique d’adhésion n’a pas pu être vérifiée. Réessayez le même JOIN tant que la portée de son royaume est valide."), + Arguments.of( + "LOGIN_REQUIRED", + false, + "LOGIN_REQUIRED", + "Log in before joining a world.", + "ERROR LOGIN_REQUIRED Connectez-vous avant de rejoindre un monde."), + Arguments.of( + "", + false, + "JOIN_FAILED", + "The selected world could not be joined.", + "ERROR JOIN_FAILED Le monde sélectionné n’a pas pu être rejoint."), + Arguments.of( + "UNRECOGNIZED_ACCOUNT_OUTCOME", + false, + "UNRECOGNIZED_ACCOUNT_OUTCOME", + "The selected world could not be joined.", + "ERROR UNRECOGNIZED_ACCOUNT_OUTCOME Le monde sélectionné n’a pas pu être rejoint."), + Arguments.of( + "", + true, + null, + "Membership is ready. Continue with CHARS and PLAY.", + "OK JOIN L’adhésion est prête. Continuez avec CHARS et PLAY.")); + } + + private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, boolean success) { + UUID realmId = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + UUID namespaceId = UUID.fromString("42d234a2-7487-4dda-a7e5-a3831214328e"); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo-world", + "Demo World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 9L, + 4L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 7L, + realmId, + namespaceId))))); + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-account-scope") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build()); + when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(success) + .setOutcomeCode(outcomeCode) + .build()); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + catalog, + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); + SessionContext context = + new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.REALMS, List.of("demo-world"), "REALMS demo-world"), + false, + Optional.of(context))); + return scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.JOIN, List.of("demo-world"), "JOIN demo-world"), + false, + Optional.of(context))); } private static GameplayCatalogProperties.World world( From 6113649e6a4baceadddfd11f3a76dd8347ae9b6f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:20:50 +1300 Subject: [PATCH 029/105] Localize unavailable logout and clarify target protocol examples --- .../game-session-service/protocols.md | 4 ++-- .../presentation-messages.properties | 1 + .../presentation-messages_fr.properties | 1 + .../TextPlayerOutputRendererTest.java | 23 +++++++++++++++++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 501de34498..7cade710cb 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -122,7 +122,7 @@ If a client attempts gameplay commands before `LOGIN` succeeds, the service shou ### Login and world-selection examples -World-selection transcript showing public browsing plus slug and index equivalence; direct-text `JOIN` is implemented locally, while full end-to-end proof remains open: +Target-state illustrative world-selection transcript, not an executable end-to-end transcript for the current implementation. It shows public browsing and intended selector equivalence; the `JOIN demo/demo` world selector and numeric character selection such as `PLAY 1 production 2` are target-only and are not implemented. Direct-text `JOIN` is implemented locally, while full end-to-end proof remains open: ```text WORLDS @@ -155,7 +155,7 @@ PLAY 1 production 2 OK PLAY Entered world: Demo World / Live Realm as Sora ``` -The same resolution rules apply to `PLAY demo/demo production 2`: `demo/demo` is the stable `tenantSlug/worldSlug` selector from the exact snapshot, `production` is the tenant-local realm selector, and `2` is a response-local character index. `PLAY 1 1 Sora` likewise uses response-local menu indices and a character name to identify the same player-facing choices. Game Session resolves the selectors to `{tenantId, realmId}`, resolves the current admissible runtime target and stable namespace, then binds the internal session to the durable controller identity `{tenantId, playableStateNamespaceId, characterId}` while retaining the authenticated `accountId` as binding-owner evidence, `realmId` and `playableStateScope` as server-derived scope context, and `{gameInstanceId, regionId, regionEpoch}` as the current runtime fence where applicable; the player never selects `realmId`, `gameInstanceId`, `playableStateScope`, or a storage namespace directly. +In the target protocol, `PLAY demo/demo production 2` uses `demo/demo` as the stable `tenantSlug/worldSlug` selector from the exact snapshot, `production` as the tenant-local realm selector, and `2` as a response-local character index. The tenant/world-qualified selector and numeric character selection are target-only and are not implemented. Bound numeric world and realm menu selectors from the exact `WORLDS` and `REALMS` snapshots are implemented locally. `PLAY 1 1 Sora` illustrates target response-local world and realm indices with a character name. The full transcript remains target-state and is not executable end-to-end against the current implementation. Game Session resolves the selectors to `{tenantId, realmId}`, resolves the current admissible runtime target and stable namespace, then binds the internal session to the durable controller identity `{tenantId, playableStateNamespaceId, characterId}` while retaining the authenticated `accountId` as binding-owner evidence, `realmId` and `playableStateScope` as server-derived scope context, and `{gameInstanceId, regionId, regionEpoch}` as the current runtime fence where applicable; the player never selects `realmId`, `gameInstanceId`, `playableStateScope`, or a storage namespace directly. The Account Service returns canonical `AUTH_*` error codes such as `AUTH_INVALID_CREDENTIALS`, `AUTH_RETRY_LATER`, `AUTH_ACCOUNT_LOCKED`, and `AUTH_UNAVAILABLE`. Game Session translates them into protocol-level responses such as `ERROR INVALID_CREDENTIALS`, `ERROR RETRY_LATER`, and `ERROR AUTH_UNAVAILABLE` so Telnet and WebSocket clients can rely on stable error semantics while the human-readable message remains flexible. `AUTH_ACCOUNT_LOCKED` is the Account-owned safe outcome for an active durable lock; Game Session only translates it and does not decide or create the lock. It is exposed to the client only after sufficient identity proof or through the recovery path. The lock may be entered from verified or high-confidence compromise evidence, explicit Account security policy, or audited operator action; ordinary failed-login throttling uses `AUTH_RETRY_LATER`. diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index bdce22b8f4..1a9f21db71 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -13,6 +13,7 @@ error.login.account-locked=This account is locked. error.login.retry-later=Too many failed attempts; try again later. error.login.abuse-control-unavailable=Login protection is temporarily unavailable. Try again later. error.login.unavailable=Login is temporarily unavailable. +error.logout.unavailable=Logout is temporarily unavailable. Please try again. error.play.invalid-argument=PLAY command requires a world selector. error.play.selection-required=Use WORLDS to browse available worlds, then PLAY [realm] [character]. error.play.realm-selection-required=Selection required. Use PLAY {worldSlug} [character] or browse REALMS first. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 479057d57f..b6f2946d59 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -13,6 +13,7 @@ error.login.account-locked=Ce compte est verrouille. error.login.retry-later=Trop de tentatives échouées ; réessayez plus tard. error.login.abuse-control-unavailable=La protection de connexion est temporairement indisponible. Réessayez plus tard. error.login.unavailable=La connexion est temporairement indisponible. +error.logout.unavailable=La déconnexion est temporairement indisponible. Veuillez réessayer. error.play.invalid-argument=La commande PLAY requiert un selecteur de monde. error.play.selection-required=Utilisez WORLDS pour parcourir les mondes disponibles, puis PLAY [realm] [character]. error.play.realm-selection-required=Sélection requise. Utilisez PLAY {worldSlug} [character] ou consultez REALMS d’abord. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index 23118f28bb..1a0cc8a560 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -862,6 +862,29 @@ void localizedErrorUsesConfiguredLocaleTemplate() { .isEqualTo("ERROR LOGIN_REQUIRED You must LOGIN first. Use LOGIN [secret]."); } + @Test + void localizedLogoutUnavailableErrorUsesFrenchRegionalLocaleTemplate() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "fr-FR", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L))); + + String rendered = + renderer.render( + PlayerOutput.error( + "LOGOUT_UNAVAILABLE", + "Logout is temporarily unavailable. Please try again.", + "error.logout.unavailable", + java.util.Map.of())); + + assertThat(rendered) + .isEqualTo( + "ERROR LOGOUT_UNAVAILABLE La déconnexion est temporairement indisponible. Veuillez réessayer."); + } + @Test void publicJoinOutcomesRenderCurrentGuidanceAndPolicyDenial() { TextPlayerOutputRenderer renderer = From 66573cb0892245a68828fc96d47e765bcfbf4951 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:50:18 +1300 Subject: [PATCH 030/105] Align text roster validation and preserve retained lobby records --- .../account-service/runtime-and-data.md | 4 +- .../system-architecture-authentication.md | 2 +- .../player-access-and-session.md | 8 +- .../command/text/WorldsCommandHandler.java | 5 +- .../DirectTextConnectScopeSessionStore.java | 29 +---- ...irectTextConnectScopeSessionStoreTest.java | 86 +++++++++++++ .../text/WorldsCommandHandlerTest.java | 5 + ...irectTextConnectScopeSessionStoreTest.java | 119 ++++++++++++++++++ 8 files changed, 224 insertions(+), 34 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 0f9f6a205c..d537af0a2e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -22,7 +22,7 @@ The current public registration path creates only a global Account row and a pla Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The proto and Account producer emit lifecycle state and generation, but Game Session does not validate them; `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`, but the current consumer does not distinguish `INACTIVE` from another existing non-admitting lifecycle state. These paths do not create or restore membership. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains open; no Overseer decision is implied. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The Account proto and producer emit lifecycle state and generation; text `PLAY` now validates the exact identity and fresh lifecycle, admission, version, and generation evidence before binding, with its admission mapping owned by [Authentication](../../system-architecture-authentication.md). The response still omits `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints`, so these consumer checks do not establish a complete authority snapshot or resolve the Account reader exposure documented below. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; it does not establish the target independent membership-version and authority-generation baseline reread or durable replay revalidation. Text `PLAY`'s current lifecycle-aware `JOIN_REQUIRED` mapping and non-public denial remain documented by Authentication. These paths do not create or restore membership. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains open; no Overseer decision is implied. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. @@ -270,7 +270,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. A present non-admitting membership is denied without `JOIN_REQUIRED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Current text `PLAY` still may return `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target, as tracked for Unit 1B. The local explicit `JOIN`/`Join & Play` operation and controller exist. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. PostgreSQL exact-final-head proof, recovery/reconciliation after unknown JOIN commit outcomes, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership authority after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED` from connect-token issuance; a present non-admitting membership is denied. Text `PLAY` now validates the returned lifecycle and authority-generation evidence and applies the public `JOIN_REQUIRED` gate described in [Authentication](../../system-architecture-authentication.md). The local explicit `JOIN`/`Join & Play` operation and controller exist. Current non-public mappings differ by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED`, with grant denial separate. PostgreSQL exact-final-head proof, recovery/reconciliation after unknown JOIN commit outcomes, direct text-to-Logging end-to-end proof, and the target membership-version and authority-generation baseline reread at connect-token issuance remain incomplete. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. ## Monetization and Notification Domain Notes diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 2bd550bb6a..43be5ae674 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The adapter response has no `membershipLifecycleState` field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result remains a fail-closed admission denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the target independent membership-version and authority-generation baseline reread at connect-token issuance remains a proof gap. On a connect-token cache miss, current issuance consumes its implemented membership evidence; a `session:connect-token:*` replay hit can return cached success before fresh entitlement, membership, and pointer rereads. The exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` does not use that replay cache: each attempt reads current Account membership and validates exact `accountId`/`tenantId`, lifecycle, membership version, authority generation, admission state, and a fresh evaluation time before binding. Existing-member admission requires `membershipLifecycleState=ACTIVE` and `gameplayAdmissionAllowed=true`. For public production, only a fresh `MISSING` or `INACTIVE` membership can return `JOIN_REQUIRED`, and only after fresh tenant entitlement and `allowPublicJoin=true` checks; invalid or unavailable membership evidence fails closed, while public-policy denial remains a distinct denial. Text `PLAY` separately reads the current realm grant for private/playtest targets; its current non-public missing or non-admitting membership outcome is `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. The Account runtime response now includes lifecycle and authority-generation fields, but connect-token issuance does not establish the target independent issuance-time baseline or durable replay revalidation. The complete first-party browser/mobile sequence remains partial, with PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof gaps. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. 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 b7222dd9b9..e65f95b5bc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision; PostgreSQL runtime proof and direct text-client end-to-end proof are not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision; PostgreSQL runtime proof and direct text-client end-to-end proof are not claimed. The connect-token-issuance membership-version and authority-generation baseline reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -34,7 +34,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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. Generic payment scaffolds still retain provider-mutating drift. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Missing or `INACTIVE` public membership receives `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` non-admitting member is denied without JOIN advice, and unavailable evidence remains retryable. Explicit JOIN exists locally through Account's public-production writer, but this does not prove the direct text-client path; the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Missing or `INACTIVE` public membership receives `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` non-admitting member is denied without JOIN advice, and unavailable evidence remains retryable. Explicit JOIN exists locally through Account's public-production writer, but this does not prove the direct text-client path; the target membership-version and authority-generation baseline reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025. | | `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, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. 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. | | `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 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 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.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) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | @@ -61,7 +61,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Current connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target but does not revalidate the applicable non-public grant. Target issuance grant validation and its focused proof remain gaps. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit text `JOIN` is implemented locally through Game Session dispatch and the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. First-party `Join & Play`, the writer's `PENDING`/unknown-database-outcome recovery seam, and direct text-client end-to-end proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit text `JOIN` is implemented locally through Game Session dispatch and the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. First-party `Join & Play`, the writer's `PENDING`/unknown-database-outcome recovery seam, and direct text-client end-to-end proof remain open, so ADR 0025 is not complete. The target membership-version and authority-generation baseline reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -143,7 +143,7 @@ The evidence records focused unit, controller, gRPC, WebSocket, cross-service, a The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. First-party proofs cover fresh-token enforcement, bare verified-identity login, `PLAY` scope binding, replay/expiry/context/scope failures, screen-buffer restore, and fresh redraw. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. Explicit `JOIN`/`Join & Play`, transactional join authority, the connect-token membership-authority-generation reread, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. Explicit `JOIN`/`Join & Play`, transactional join authority, the connect-token membership-version and authority-generation baseline reread, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. - **Validation record:** Required current documentation, contract, settings-generation, allocation, ADR, and `git diff --check` gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Runtime proof is not applicable to this documentation-only change. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 85a8fce497..7d074676e3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; +import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.springframework.beans.factory.annotation.Autowired; @@ -856,10 +857,12 @@ public CharacterBrowseResult browseCharacters( Set characterIds = new HashSet<>(); for (int i = 0; i < response.getCharactersCount(); i++) { net.firedevops.firemud.entitymanagement.v1.Character character = response.getCharacters(i); + PositiveLongParsing.ParsedPositiveLong parsedCharacterId = + PositiveLongParsing.parseOptionalText(character.getId(), "characterId"); if (!Long.toString(realm.tenantId()).equals(character.getTenantId()) || !Long.toString(sessionContext.accountId()).equals(character.getAccountId()) || character.getPlayableStateScope() != toPlayableStateScope(realm) - || !StringUtils.hasText(character.getId()) + || !parsedCharacterId.valid() || !StringUtils.hasText(character.getName()) || !characterIds.add(character.getId())) { return CharacterBrowseResult.unavailable(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index 82713cd64e..b9a7b0fc57 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -186,7 +186,6 @@ public void replaceWorldScopes( record.catalogFingerprint(), record.ordinalTargets(), byWorld, - record.worldBySelector(), realmsByWorld); }); } @@ -252,11 +251,9 @@ public void replaceRealmSnapshot( record = LobbyRecord.empty(caller.sessionId()); } Map> byWorld = new HashMap<>(record.scopesByWorld()); - Map worldBySelector = new HashMap<>(record.worldBySelector()); Map realmsByWorld = new HashMap<>(record.realmsByWorld()); byWorld.remove(worldKey); realmsByWorld.remove(worldKey); - worldBySelector.entrySet().removeIf(entry -> worldKey.equals(entry.getValue())); if (!storedScopes.isEmpty()) { byWorld.put(worldKey, storedScopes); } @@ -278,7 +275,6 @@ record = LobbyRecord.empty(caller.sessionId()); record.catalogFingerprint(), record.ordinalTargets(), byWorld, - worldBySelector, realmsByWorld); }); } @@ -371,8 +367,6 @@ record = LobbyRecord.empty(caller.sessionId()); Map realmsByWorld = new HashMap<>(record.realmsByWorld()); byWorld.remove(worldKey); realmsByWorld.remove(worldKey); - Map worldBySelector = new HashMap<>(record.worldBySelector()); - worldBySelector.entrySet().removeIf(entry -> worldKey.equals(entry.getValue())); return new LobbyRecord( caller.sessionId(), caller.accountId(), @@ -380,7 +374,6 @@ record = LobbyRecord.empty(caller.sessionId()); record.catalogFingerprint(), record.ordinalTargets(), byWorld, - worldBySelector, realmsByWorld); }); } @@ -494,7 +487,7 @@ public Optional publicProductionScopeForJoin( .toList(); Map> byWorld = new HashMap<>(current.scopesByWorld()); byWorld.put(worldKey, updatedScopes); - current = current.withScopes(byWorld, current.worldBySelector()); + current = current.withScopes(byWorld); } selected[0] = new JoinScope(fromStoredScope(boundScope), requestId); return current; @@ -594,13 +587,6 @@ private LobbyRecord pruneExpired(LobbyRecord record, long nowMillis) { realmsByWorld.put(world, snapshot); } }); - Map worldBySelector = new HashMap<>(record.worldBySelector()); - worldBySelector - .entrySet() - .removeIf( - entry -> - !scopesByWorld.containsKey(entry.getValue()) - && !realmsByWorld.containsKey(entry.getValue())); if (worldsExpiry == 0L && scopesByWorld.isEmpty() && realmsByWorld.isEmpty()) { return null; } @@ -611,7 +597,6 @@ private LobbyRecord pruneExpired(LobbyRecord record, long nowMillis) { fingerprint, ordinalTargets, scopesByWorld, - worldBySelector, realmsByWorld); } @@ -1098,7 +1083,6 @@ private record LobbyRecord( String catalogFingerprint, List ordinalTargets, Map> scopesByWorld, - Map worldBySelector, Map realmsByWorld) { private LobbyRecord { ordinalTargets = ordinalTargets == null ? List.of() : List.copyOf(ordinalTargets); @@ -1107,12 +1091,11 @@ private record LobbyRecord( scopesByWorld.forEach((slug, scopes) -> scopesCopy.put(slug, List.copyOf(scopes))); } scopesByWorld = Map.copyOf(scopesCopy); - worldBySelector = worldBySelector == null ? Map.of() : Map.copyOf(worldBySelector); realmsByWorld = realmsByWorld == null ? Map.of() : Map.copyOf(realmsByWorld); } private static LobbyRecord empty(long sessionId) { - return new LobbyRecord(sessionId, 0L, 0L, null, List.of(), Map.of(), Map.of(), Map.of()); + return new LobbyRecord(sessionId, 0L, 0L, null, List.of(), Map.of(), Map.of()); } private LobbyRecord normalized() { @@ -1126,7 +1109,6 @@ private LobbyRecord normalized() { catalogFingerprint, ordinalTargets, scopesByWorld, - worldBySelector, realmsByWorld); } @@ -1142,7 +1124,6 @@ private LobbyRecord withWorldSnapshot( fingerprint, targets, scopesByWorld, - worldBySelector, realmsByWorld); } @@ -1154,7 +1135,6 @@ private LobbyRecord withWorldSnapshotFrom(LobbyRecord other) { other.catalogFingerprint(), other.ordinalTargets(), scopesByWorld, - worldBySelector, realmsByWorld); } @@ -1166,12 +1146,10 @@ private LobbyRecord withAccountId(long updatedAccountId) { catalogFingerprint, ordinalTargets, scopesByWorld, - worldBySelector, realmsByWorld); } - private LobbyRecord withScopes( - Map> updatedScopes, Map updatedSelectors) { + private LobbyRecord withScopes(Map> updatedScopes) { return new LobbyRecord( sessionId, accountId, @@ -1179,7 +1157,6 @@ private LobbyRecord withScopes( catalogFingerprint, ordinalTargets, updatedScopes, - updatedSelectors, realmsByWorld); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java index 18d3460089..1b01202029 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java @@ -4,7 +4,9 @@ import java.time.Instant; import java.util.ArrayList; +import java.util.Base64; import java.util.List; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -171,6 +173,90 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws } } + @Test + void readsLegacyLobbyJsonWithUnusedSelectorMapAcrossStoreInstances() throws Exception { + Instant now = Instant.now(); + long expiresAt = now.plusSeconds(600).toEpochMilli(); + String worldKey = "22:ZGVtby13b3JsZA"; + SessionContext caller = session(); + String legacyJson = + new ObjectMapper() + .writeValueAsString( + Map.of( + "sessionId", + SESSION_ID, + "accountId", + ACCOUNT_ID, + "worldsExpiresAtEpochMs", + expiresAt, + "catalogFingerprint", + "catalog-fingerprint-v13", + "ordinalTargets", + List.of(), + "scopesByWorld", + Map.of( + worldKey, + List.of( + Map.of( + "realmSlug", + "production", + "publicProductionRealm", + true, + "connectScopeId", + "account-connect-scope-legacy", + "expiresAtEpochMs", + expiresAt, + "playerContextBase64", + Base64.getEncoder() + .encodeToString(playerContext(caller).toByteArray()), + "joinRequestId", + "join-request-already-bound"))), + "worldBySelector", + Map.of("1", worldKey), + "realmsByWorld", + Map.of( + worldKey, + Map.of( + "tenantId", + 22L, + "worldSlug", + "demo-world", + "requestedWorldSelector", + "1", + "catalogFingerprint", + "realm-catalog-fingerprint-v13", + "expiresAtEpochMs", + expiresAt, + "ordinalTargets", + List.of())))); + redisTemplate.opsForValue().set(REDIS_KEY, legacyJson); + + DirectTextConnectScopeSessionStore replacement = newStoreInstance(); + + assertThat(replacement.realmsSnapshot(caller, 22L, "demo-world", now)) + .hasValueSatisfying( + snapshot -> { + assertThat(snapshot.tenantId()).isEqualTo(22L); + assertThat(snapshot.requestedWorldSelector()).isEqualTo("1"); + }); + assertThat( + replacement + .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now) + .orElseThrow()) + .satisfies( + selected -> { + assertThat(selected.scope().connectScopeId()) + .isEqualTo("account-connect-scope-legacy"); + assertThat(selected.scope().playerContext().getAccountId()) + .isEqualTo(Long.toString(ACCOUNT_ID)); + assertThat(selected.scope().playerContext().getSessionId()) + .isEqualTo(Long.toString(SESSION_ID)); + assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); + assertThat(selected.requestId()).isEqualTo("join-request-already-bound"); + }); + assertThat(redisTemplate.opsForValue().get(REDIS_KEY)).doesNotContain("worldBySelector"); + } + private DirectTextConnectScopeSessionStore newStoreInstance() { return new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 3584549ad3..9896a73151 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -487,6 +487,11 @@ void browseCharactersRejectsMismatchedOrDuplicateEntityRows() { .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .build(), valid.toBuilder().clearId().build(), + valid.toBuilder().setId("not-a-number").build(), + valid.toBuilder().setId("0").build(), + valid.toBuilder().setId("-1").build(), + valid.toBuilder().setId("9223372036854775808").build(), + valid.toBuilder().setId("-9223372036854775809").build(), valid.toBuilder().clearName().build())) { Mockito.when( entityManagementClient.listCharactersByAccount( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 9f606a9833..04a35ffb96 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -4,9 +4,18 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Instant; +import java.util.Base64; import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.core.script.RedisScript; +import tools.jackson.databind.ObjectMapper; class DirectTextConnectScopeSessionStoreTest { private final DirectTextConnectScopeSessionStore store = @@ -178,6 +187,116 @@ void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); } + @Test + @SuppressWarnings("unchecked") + void readsLegacyLobbyJsonAcrossProductionStoreInstances() throws Exception { + SessionContext caller = session(41L, 7L); + Instant now = Instant.now(); + long expiresAt = now.plusSeconds(600).toEpochMilli(); + String worldKey = "22:ZGVtby13b3JsZA"; + PlayerExecutionContext playerContext = + PlayerExecutionContext.newBuilder() + .setAccountId(Long.toString(caller.accountId())) + .setSessionId(Long.toString(caller.sessionId())) + .setTenantId(Long.toString(caller.tenantId())) + .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") + .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328e") + .setPlayableStateScope("SHARED") + .setGameInstanceId("9") + .build(); + String legacyJson = + new ObjectMapper() + .writeValueAsString( + Map.of( + "sessionId", caller.sessionId(), + "accountId", caller.accountId(), + "worldsExpiresAtEpochMs", expiresAt, + "catalogFingerprint", "catalog-fingerprint-v13", + "ordinalTargets", List.of(), + "scopesByWorld", + Map.of( + worldKey, + List.of( + Map.of( + "realmSlug", + "production", + "publicProductionRealm", + true, + "connectScopeId", + "account-connect-scope-legacy", + "expiresAtEpochMs", + expiresAt, + "playerContextBase64", + Base64.getEncoder().encodeToString(playerContext.toByteArray()), + "joinRequestId", + "join-request-already-bound"))), + "worldBySelector", Map.of("1", worldKey), + "realmsByWorld", + Map.of( + worldKey, + Map.of( + "tenantId", + 22L, + "worldSlug", + "demo-world", + "requestedWorldSelector", + "1", + "catalogFingerprint", + "realm-catalog-fingerprint-v13", + "expiresAtEpochMs", + expiresAt, + "ordinalTargets", + List.of())))); + AtomicReference sharedRedisValue = new AtomicReference<>(legacyJson); + StringRedisTemplate redisTemplate = Mockito.mock(StringRedisTemplate.class); + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + Mockito.when(redisTemplate.opsForValue()).thenReturn(valueOperations); + Mockito.when(valueOperations.get(Mockito.anyString())) + .thenAnswer(invocation -> sharedRedisValue.get()); + Mockito.doAnswer( + invocation -> { + Object[] arguments = + java.util.Arrays.copyOfRange( + invocation.getArguments(), 2, invocation.getArguments().length); + String expectedValue = "1".equals(arguments[0]) ? (String) arguments[1] : null; + if (!Objects.equals(sharedRedisValue.get(), expectedValue)) { + return 0L; + } + sharedRedisValue.set("1".equals(arguments[2]) ? (String) arguments[3] : null); + return 1L; + }) + .when(redisTemplate) + .execute(Mockito.any(RedisScript.class), Mockito.anyList(), Mockito.any(Object[].class)); + + DirectTextConnectScopeSessionStore firstInstance = + new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); + DirectTextConnectScopeSessionStore replacementInstance = + new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); + + assertThat(firstInstance.realmsSnapshot(caller, 22L, "demo-world", now)) + .hasValueSatisfying( + snapshot -> { + assertThat(snapshot.tenantId()).isEqualTo(22L); + assertThat(snapshot.requestedWorldSelector()).isEqualTo("1"); + }); + DirectTextConnectScopeSessionStore.JoinScope selected = + replacementInstance + .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now) + .orElseThrow(); + assertThat(selected.scope().connectScopeId()).isEqualTo("account-connect-scope-legacy"); + assertThat(selected.scope().playerContext().getAccountId()).isEqualTo("7"); + assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); + assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); + assertThat(selected.requestId()).isEqualTo("join-request-already-bound"); + assertThat( + firstInstance + .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now) + .orElseThrow() + .requestId()) + .isEqualTo("join-request-already-bound"); + assertThat(sharedRedisValue.get()).doesNotContain("worldBySelector"); + } + @Test void sameWorldSlugInDifferentTenantsKeepsOrdinalScopesIsolated() { SessionContext caller = session(41L, 7L); From f8a4a9018d7fb316237d9bcc3995bc2e18abe6a6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:21:11 +1300 Subject: [PATCH 031/105] Keep inherited audit migration unchanged in player stage --- .../db/migration/V7__audit_gameplay_catalog_revision.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql index f310583acc..9eff6e4d00 100644 --- a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql +++ b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql @@ -6,3 +6,4 @@ ALTER TABLE gameplay_admission_pointer_event CHECK (catalog_revision IS NULL OR catalog_revision > 0), ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); + From 2289a86c5e6c6bcb84f2bbd5ad56fae5ed0b9b90 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:57:32 +1300 Subject: [PATCH 032/105] Fence direct-text JOIN retries by retained scope expiry --- .../game-session-service/protocols.md | 4 +- design/project-management/ai-observations.md | 5 + .../gamesession/client/AccountClient.java | 49 +++++- .../command/text/WorldsCommandHandler.java | 2 +- .../gamesession/client/AccountClientTest.java | 160 +++++++++++++++++- .../command/text/PlayCommandHandlerTest.java | 10 +- .../text/SessionResumptionFlowTest.java | 3 +- .../text/WorldsCommandHandlerTest.java | 56 +++++- .../WorldsTextCommandDispatchHandlerTest.java | 14 +- 9 files changed, 275 insertions(+), 28 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 799e517dc5..3a97d22e27 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -89,9 +89,9 @@ The Account membership operation is `JoinPublicProductionMembership`; the direct - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. - Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the Account-issued scope in the shared Redis lobby record keyed by the stable numeric transport session ID. Atomic per-key compare-and-set preserves that request identity across retries and Game Session replacement. The record contains no raw JWT; the Account scope is bound to exact account/session identity and expires within its bounded lifetime. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. - An ambiguous or stale world/realm selector is a lobby-selection error: Game Session does not guess, does not invoke Account, and directs the client to refresh `WORLDS`/`REALMS`. A discovered scope that is stale or no longer matches the resolved `worldSlug`/`realmSlug` fails closed with the applicable scope or admission error rather than being translated to a newer target. -- JOIN idempotency uses the canonical preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session generates and retains the server-side `requestId`, passes the verified local digest inputs and retained scope to Account, and reuses that identity through retries and scope-expiry cleanup. Account replays an exact `{requestId, digest}` outcome and rejects a different digest as `IDEMPOTENCY_CONFLICT`; a new `requestId` is a distinct attempt after a new scope. +- JOIN idempotency uses the canonical preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session generates and retains the server-side `requestId`, passes the verified local digest inputs and retained scope to Account, and reuses that identity for same-scope retries only while the retained scope remains valid. The Game Session client sends JOIN only while the retained Account scope is strictly unexpired; after an ambiguous transport result it checks again before channel reload and immediately before any same-request retry. If expiry is reached, it returns retryable `AUTH_UNAVAILABLE` without resending JOIN or minting a replacement scope/request; after local scope expiry cleanup, any readback or reconciliation for an uncertain Account operation remains Account-owned. Account replays an exact `{requestId, digest}` outcome and rejects a different digest as `IDEMPOTENCY_CONFLICT`; a new `requestId` is a distinct attempt after a new scope. -Direct-text `JOIN` is implemented locally through Account, with focused Game Session coverage for the shared scope/request binding; a Docker-gated Redis integration test covers persistence across store instances and concurrent retry binding. The Game Session focused proof does not establish full direct-text/Telnet end-to-end completion. The membership-authority-generation reread and other admission gaps remain in [Implementation Status](#implementation-status); this section defines the target translation and current local handling. +Direct-text `JOIN` is implemented locally through Account, with focused Game Session coverage for the shared scope/request binding, no initial dispatch for missing/expired scope, and no retry when ambiguous transport or channel reload reaches expiry. A Docker-gated Redis integration test covers persistence across store instances and concurrent retry binding. The Game Session focused proof does not establish full direct-text/Telnet end-to-end completion. The membership-authority-generation reread and other admission gaps remain in [Implementation Status](#implementation-status); this section defines the target translation and current local handling. ## Login and Play Flow diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index d93588eb33..5b7d83d043 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -218,3 +218,8 @@ Entry format: - Observation: an explicitly selected embedded test application can still contaminate neighboring Spring test discovery when it is globally discoverable. Its isolated passing result does not prove test-suite coexistence. - Expected pattern: use isolated test configuration with explicit application selection, preserve the real HTTP route proof, and run the affected service suite when introducing an embedded application alongside MVC slices. - Outcome: an explicit context using `@Configuration` and `@TestComponent` isolates the embedded application; all 284 source-branch Account tests passed with zero skips, failures, or errors. `@TestConfiguration` alone loaded the real application's unrelated gRPC clients and was not sufficient here. The earlier failed combined run remains non-completion evidence. + +- `2026-10-02`: Preserve the producer exit status when capturing validation logs + - Context: a Game Session validation run failed a new fixture assertion, but a pipeline ending in `tee` returned exit0 because the shell did not enable `pipefail`. + - Expected pattern: enable `set -o pipefail` before captured validation pipelines and verify the terminal build result and test reports; a log sink's success is not the validation process's success. + - Outcome: the failed build was identified from its terminal report, not reported as passing. After the fixture correction, the guarded complete rerun passed; no production check or negative assertion was weakened. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 10bb5ebc71..2d8cb85f08 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -3,6 +3,8 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; +import java.time.Clock; +import java.time.Instant; import java.util.Objects; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.AuthenticationErrorCodes; @@ -32,6 +34,7 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** gRPC client for the Account Service login endpoint. */ @@ -41,13 +44,25 @@ public final class AccountClient private static final long READINESS_DEADLINE_SECONDS = 2L; private static final long CALL_DEADLINE_SECONDS = 5L; private static final Logger logger = LoggingUtil.getLogger(AccountClient.class); + private final Clock clock; + @Autowired public AccountClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, GrpcChannelFactory channelFactory, BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + AccountClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + Clock clock) { super(endpoints, tlsProps, channelFactory, stubCustomizer); + this.clock = Objects.requireNonNull(clock, "clock must not be null"); } @PostConstruct @@ -209,7 +224,10 @@ public IssueDirectTextConnectScopeResponse issueDirectTextConnectScope( /** Applies explicit direct-text JOIN with a caller-bound, immutable request identity. */ public JoinPublicProductionMembershipResponse joinPublicProductionMembership( - PlayerExecutionContext playerContext, String connectScopeId, String requestId) { + PlayerExecutionContext playerContext, + String connectScopeId, + String requestId, + Instant connectScopeExpiresAt) { Objects.requireNonNull(playerContext, "playerContext must not be null"); if (!hasDirectTextCallerIdentity(playerContext) || connectScopeId == null @@ -219,6 +237,9 @@ public JoinPublicProductionMembershipResponse joinPublicProductionMembership( || !playerContext.getRequestId().equals(requestId)) { return joinError("INVALID_ARGUMENT", "Direct-text JOIN request was incomplete"); } + if (!hasUsableConnectScope(connectScopeExpiresAt)) { + return joinError("CONNECT_SCOPE_INVALID", "Direct-text JOIN scope is missing or expired"); + } if (stub() == null) { return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); } @@ -229,19 +250,29 @@ public JoinPublicProductionMembershipResponse joinPublicProductionMembership( .setRequestId(requestId) .build(); try { - return callStub() - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .joinPublicProductionMembership(request); + AccountServiceGrpc.AccountServiceBlockingStub initialStub = + callStub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + if (!hasUsableConnectScope(connectScopeExpiresAt)) { + return joinError("CONNECT_SCOPE_INVALID", "Direct-text JOIN scope is missing or expired"); + } + return initialStub.joinPublicProductionMembership(request); } catch (StatusRuntimeException ex) { if (ex.getStatus().getCode() == Status.Code.UNAVAILABLE || ex.getStatus().getCode() == Status.Code.DEADLINE_EXCEEDED) { + if (!hasUsableConnectScope(connectScopeExpiresAt)) { + logger.warn("Account direct-text JOIN response was unavailable after scope expiry", ex); + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } logger.warn( "Account direct-text JOIN response was unavailable; retrying same request id", ex); try { initClient(); - return callStub() - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .joinPublicProductionMembership(request); + AccountServiceGrpc.AccountServiceBlockingStub retryStub = + callStub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + if (!hasUsableConnectScope(connectScopeExpiresAt)) { + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + return retryStub.joinPublicProductionMembership(request); } catch (Exception retryEx) { logger.warn("Account direct-text JOIN retry did not complete", retryEx); } @@ -255,6 +286,10 @@ public JoinPublicProductionMembershipResponse joinPublicProductionMembership( } } + private boolean hasUsableConnectScope(Instant expiresAt) { + return expiresAt != null && expiresAt.isAfter(clock.instant()); + } + private boolean hasDirectTextCallerIdentity(PlayerExecutionContext context) { return isPositiveLong(context.getAccountId()) && isPositiveLong(context.getSessionId()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 4eac8df695..b1ec76abce 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -643,7 +643,7 @@ public JoinMembershipResult joinPublicProductionMembership( scope.playerContext().toBuilder().setRequestId(requestId).build(); return JoinMembershipResult.response( accountClient.joinPublicProductionMembership( - playerContext, scope.connectScopeId(), requestId)); + playerContext, scope.connectScopeId(), requestId, scope.expiresAt())); } private static long worldTenantId(GameplayWorldCatalog.WorldView world) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 5d84ceca3b..126fe22281 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -5,7 +5,9 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.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; @@ -15,8 +17,13 @@ import io.grpc.StatusRuntimeException; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -45,6 +52,7 @@ import org.mockito.ArgumentCaptor; class AccountClientTest { + private static final Instant JOIN_TEST_NOW = Instant.parse("2026-10-02T00:00:00Z"); @Test void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() throws Exception { @@ -94,7 +102,8 @@ void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() t @Test void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { - RetryFixture fixture = newRetryFixture(); + TestClock clock = new TestClock(JOIN_TEST_NOW); + RetryFixture fixture = newRetryFixture(clock); when(fixture .initialStub() .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) @@ -110,9 +119,11 @@ void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { .thenReturn(expected); AccountClient client = fixture.client(); PlayerExecutionContext context = directTextContext("join-request-1"); + Instant expiresAt = JOIN_TEST_NOW.plusSeconds(60); JoinPublicProductionMembershipResponse actual = - client.joinPublicProductionMembership(context, "account-issued-scope", "join-request-1"); + client.joinPublicProductionMembership( + context, "account-issued-scope", "join-request-1", expiresAt); assertThat(actual).isEqualTo(expected); ArgumentCaptor firstCaptor = @@ -129,6 +140,102 @@ void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); } + @Test + void directTextJoinDoesNotDispatchForMissingExpiredOrBoundaryScope() throws Exception { + TestClock clock = new TestClock(JOIN_TEST_NOW); + RetryFixture fixture = newRetryFixture(clock); + Instant[] invalidExpiries = {null, JOIN_TEST_NOW.minusNanos(1), JOIN_TEST_NOW}; + + for (Instant expiresAt : invalidExpiries) { + JoinPublicProductionMembershipResponse response = + fixture + .client() + .joinPublicProductionMembership( + directTextContext("join-request-1"), + "account-issued-scope", + "join-request-1", + expiresAt); + + assertThat(response.getOutcomeCode()).isEqualTo("CONNECT_SCOPE_INVALID"); + assertThat(response.getError().getCode()).isEqualTo("CONNECT_SCOPE_INVALID"); + } + + verify(fixture.initialStub(), never()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.retryStub(), never()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @ParameterizedTest + @ValueSource(strings = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void directTextJoinDoesNotRetryWhenAmbiguousResponseReachesScopeExpiry(String statusName) + throws Exception { + TestClock clock = new TestClock(JOIN_TEST_NOW); + RetryFixture fixture = newRetryFixture(clock); + Instant expiresAt = JOIN_TEST_NOW.plusSeconds(1); + when(fixture + .initialStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenAnswer( + invocation -> { + clock.set(expiresAt); + throw new StatusRuntimeException(Status.fromCode(Status.Code.valueOf(statusName))); + }); + + JoinPublicProductionMembershipResponse response = + fixture + .client() + .joinPublicProductionMembership( + directTextContext("join-request-1"), + "account-issued-scope", + "join-request-1", + expiresAt); + + assertThat(response.getOutcomeCode()).isEqualTo("AUTH_UNAVAILABLE"); + verify(fixture.initialStub()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.retryStub(), never()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void directTextJoinRechecksExpiryAfterChannelReloadBeforeRetry() throws Exception { + TestClock clock = new TestClock(JOIN_TEST_NOW); + RetryFixture fixture = newRetryFixture(clock); + Instant expiresAt = JOIN_TEST_NOW.plusSeconds(1); + when(fixture + .initialStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + doAnswer( + invocation -> { + clock.set(expiresAt); + return mock(ManagedChannel.class); + }) + .when(fixture.channelFactory()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + + JoinPublicProductionMembershipResponse response = + fixture + .client() + .joinPublicProductionMembership( + directTextContext("join-request-1"), + "account-issued-scope", + "join-request-1", + expiresAt); + + assertThat(response.getOutcomeCode()).isEqualTo("AUTH_UNAVAILABLE"); + verify(fixture.initialStub()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + verify(fixture.retryStub(), never()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + } + private static PlayerExecutionContext directTextContext(String requestId) { return PlayerExecutionContext.newBuilder() .setAccountId("41") @@ -540,7 +647,8 @@ private static AccountClient newClient( private static AccountClient newClientWithRetryStub( AccountServiceGrpc.AccountServiceBlockingStub initialStub, AccountServiceGrpc.AccountServiceBlockingStub retryStub, - GrpcChannelFactory channelFactory) + GrpcChannelFactory channelFactory, + Clock clock) throws Exception { BlockingGrpcStubCustomizer customizer = mock(BlockingGrpcStubCustomizer.class); when(customizer.customize(any(AccountServiceGrpc.AccountServiceBlockingStub.class))) @@ -550,12 +658,17 @@ private static AccountClient newClientWithRetryStub( new ServiceEndpointsProperties(), new CommonGrpcClientProperties(), channelFactory, - customizer); + customizer, + clock); setStub(client, initialStub); return client; } private static RetryFixture newRetryFixture() throws Exception { + return newRetryFixture(Clock.systemUTC()); + } + + private static RetryFixture newRetryFixture(Clock clock) throws Exception { AccountServiceGrpc.AccountServiceBlockingStub initialStub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); AccountServiceGrpc.AccountServiceBlockingStub retryStub = @@ -567,7 +680,44 @@ private static RetryFixture newRetryFixture() throws Exception { initialStub, retryStub, channelFactory, - newClientWithRetryStub(initialStub, retryStub, channelFactory)); + newClientWithRetryStub(initialStub, retryStub, channelFactory, clock)); + } + + private static final class TestClock extends Clock { + private final AtomicReference current; + private final ZoneId zone; + + private TestClock(Instant current) { + this(current, ZoneOffset.UTC); + } + + private TestClock(Instant current, ZoneId zone) { + this(new AtomicReference<>(current), zone); + } + + private TestClock(AtomicReference current, ZoneId zone) { + this.current = current; + this.zone = zone; + } + + private void set(Instant value) { + current.set(value); + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId zone) { + return new TestClock(current, zone); + } + + @Override + public Instant instant() { + return current.get(); + } } private record RetryFixture( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 94a96f5103..5a704bf19a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2892,7 +2892,8 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi Mockito.verify(scriptEventPublisher, never()) .publishSpawnEvent(Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(accountClient, never()) - .joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + .joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class)); when(sessionContextService.findBySessionId(1L)).thenReturn(Optional.of(savedContext)); when(sessionContextService.findByTenantAndSessionId(22L, 1L)) @@ -2920,7 +2921,7 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); when(accountClient.joinPublicProductionMembership( - Mockito.any(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); WorldsCommandHandler worldsCommandHandler = new WorldsCommandHandler( @@ -2944,7 +2945,10 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(String.class); Mockito.verify(accountClient) .joinPublicProductionMembership( - playerContextCaptor.capture(), scopeIdCaptor.capture(), requestIdCaptor.capture()); + playerContextCaptor.capture(), + scopeIdCaptor.capture(), + requestIdCaptor.capture(), + Mockito.any(Instant.class)); assertThat(scopeIdCaptor.getValue()).isEqualTo(exactJoinScopeId); assertThat(playerContextCaptor.getValue().getAccountId()).isEqualTo("123"); assertThat(playerContextCaptor.getValue().getSessionId()).isEqualTo("1"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index f30893d9e4..0147555604 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -518,7 +518,8 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() .anyMatch(presence -> presence.sessionId() == 1L)); Mockito.verify(accountClient, Mockito.never()) - .joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + .joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class)); TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index ab8fb4b6e8..7568cc497d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -139,7 +139,10 @@ void sameWorldSlugAcrossTenantsKeepsDistinctOrdinalsAndJoinTargets() { .build()); Mockito.when( accountClient.joinPublicProductionMembership( - Mockito.any(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( @@ -175,12 +178,14 @@ void sameWorldSlugAcrossTenantsKeepsDistinctOrdinalsAndJoinTargets() { .joinPublicProductionMembership( Mockito.argThat(context -> context.getTenantId().equals("22")), Mockito.eq("scope"), - Mockito.anyString()); + Mockito.anyString(), + Mockito.any(Instant.class)); Mockito.verify(accountClient) .joinPublicProductionMembership( Mockito.argThat(context -> context.getTenantId().equals("33")), Mockito.eq("scope"), - Mockito.anyString()); + Mockito.anyString(), + Mockito.any(Instant.class)); } @Test @@ -208,6 +213,43 @@ void joinRejectsUnboundOrdinalBeforeCallingAccount() { Mockito.verifyNoInteractions(accountClient); } + @Test + void joinForwardsTheRetainedAccountScopeExpiry() { + Instant scopeExpiresAt = Instant.ofEpochMilli(Instant.now().plusSeconds(60).toEpochMilli()); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-with-expiry") + .setConnectScopeExpiresAt(scopeExpiresAt.toString()) + .build()); + Mockito.when( + accountClient.joinPublicProductionMembership( + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) + .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); + + Mockito.verify(accountClient) + .joinPublicProductionMembership( + Mockito.any(), + Mockito.eq("scope-with-expiry"), + Mockito.anyString(), + Mockito.eq(scopeExpiresAt)); + } + @Test void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { GameplayWorldCatalog.RealmView realmA = @@ -1603,7 +1645,10 @@ void joinRejectsRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { .build()); Mockito.when( accountClient.joinPublicProductionMembership( - Mockito.any(), Mockito.anyString(), Mockito.anyString())) + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) .thenReturn( JoinPublicProductionMembershipResponse.newBuilder() .setSuccess(false) @@ -1692,7 +1737,8 @@ void joinRejectsRetainedScopeWhenTenantPublicRealmBecomesAmbiguous() { .isEqualTo( WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verify(accountClient, Mockito.never()) - .joinPublicProductionMembership(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + .joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 82c7c6c006..b0b1f209a2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -446,7 +446,8 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .setConnectScopeId("opaque-account-scope") .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") .build()); - when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) + when(accountClient.joinPublicProductionMembership( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Instant.class))) .thenReturn( JoinPublicProductionMembershipResponse.newBuilder() .setSuccess(false) @@ -534,7 +535,10 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { org.mockito.ArgumentCaptor.forClass(String.class); Mockito.verify(accountClient, Mockito.times(3)) .joinPublicProductionMembership( - joinContextCaptor.capture(), scopeIdCaptor.capture(), requestIdCaptor.capture()); + joinContextCaptor.capture(), + scopeIdCaptor.capture(), + requestIdCaptor.capture(), + Mockito.any(Instant.class)); List joinContexts = joinContextCaptor.getAllValues(); List scopeIds = scopeIdCaptor.getAllValues(); @@ -600,7 +604,8 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { .setConnectScopeId("opaque-account-scope-2") .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") .build()); - when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) + when(accountClient.joinPublicProductionMembership( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Instant.class))) .thenReturn( JoinPublicProductionMembershipResponse.newBuilder() .setSuccess(false) @@ -838,7 +843,8 @@ private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, .setConnectScopeId("opaque-account-scope") .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") .build()); - when(accountClient.joinPublicProductionMembership(Mockito.any(), Mockito.any(), Mockito.any())) + when(accountClient.joinPublicProductionMembership( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Instant.class))) .thenReturn( JoinPublicProductionMembershipResponse.newBuilder() .setSuccess(success) From f577f5fd3c6f5fba3b179c92723795af761007f9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:55:04 +1300 Subject: [PATCH 033/105] Align player admission guidance and logout status --- .../architecture/system-architecture-session-behavior.md | 2 +- .../command/text/GameplayStageCommandConstants.java | 2 +- .../src/main/resources/presentation-messages.properties | 2 +- .../src/main/resources/presentation-messages_fr.properties | 2 +- .../gamesession/command/text/PlayCommandHandlerTest.java | 7 +++++++ 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index 163f150a61..0035e12956 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -30,7 +30,7 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no ## Implementation Status -Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`; the current Game Session text `PLAY` path validates this lifecycle and generation evidence before admission. Roles, the target exact one-tenant `membershipVersion` map carrier, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware event consumers, same-stream reconciliation, remaining player-facing legacy mapping, and complete proof across admission/reconnect paths remain gaps; the bounded text `PLAY` checks do not establish those broader guarantees. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. +Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`; the current Game Session text `PLAY` path validates this lifecycle and generation evidence before admission. Roles, the target exact one-tenant `membershipVersion` map carrier, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware event consumers, same-stream reconciliation, remaining player-facing legacy mapping, and complete proof across admission/reconnect paths remain gaps; the bounded text `PLAY` checks do not establish those broader guarantees. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; for an authenticated session, text `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before logout side effects, without invoking Account logout or performing local cleanup. The durable logout fence and its end-to-end proof remain gaps. Account Service is the sole writer of account authority-generation advances and all canonical `session:auth:generation:*` projections, including `session:auth:generation:account:`. Account commits every applicable canonical tuple field, cutoff, `issuanceFence`, and monotonic outbox event together; the generation projection is an asynchronous outbox output, not an atomically committed part of that durable generation/event transaction. Game Session and other downstream services consume Account-owned generation events and projections; they must not advance canonical authority or write canonical projections directly, and they fail closed while projection or freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Game Session's only generation projection write is its derived `session:game:auth:issuer-generation:v1:` consumer-local record under the ADR 0022 schema. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index 687b6f5d98..1bc5e7a471 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -23,7 +23,7 @@ public final class GameplayStageCommandConstants { "You are not allowed to enter that world."; public static final String JOIN_REQUIRED_CODE = "JOIN_REQUIRED"; public static final String JOIN_REQUIRED_MESSAGE = - "Membership is required before PLAY. Use JOIN ."; + "Membership is required before PLAY. Run REALMS first, then JOIN ."; public static final String TENANT_BILLING_BLOCKED_CODE = "TENANT_BILLING_BLOCKED"; public static final String TENANT_BILLING_BLOCKED_MESSAGE = "That world is temporarily unavailable for gameplay."; diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 1a9f21db71..ff488d4eb3 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -21,7 +21,7 @@ error.play.character-selection-required=Selection required. Use {playUsage} or b error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. -error.play.join-required=Membership is required before PLAY. Use JOIN . +error.play.join-required=Membership is required before PLAY. Run REALMS first, then JOIN . error.play.public-production-admission-denied=Public joining is not available for this world. error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. error.play.entitlement-unavailable=Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 6e518a8f25..e37962acac 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -21,7 +21,7 @@ error.play.character-selection-required=Selection requise. Utilisez {playUsage} error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. -error.play.join-required=Une adhésion est requise avant PLAY. Utilisez JOIN . +error.play.join-required=Une adhésion est requise avant PLAY. Consultez d’abord REALMS , puis utilisez JOIN . error.play.public-production-admission-denied=L’adhésion publique n’est pas disponible pour ce monde. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.entitlement-unavailable=Les droits de jeu sont temporairement indisponibles. Réessayez PLAY sous peu. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 5a704bf19a..4db243c233 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2850,6 +2850,13 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_MESSAGE); assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) .isEqualTo("error.play.join-required"); + TextPlayerOutputRenderer renderer = new TextPlayerOutputRenderer(new PresentationProperties()); + assertThat(renderer.render(result.outputs().get(0), "fr")) + .isEqualTo( + "ERROR JOIN_REQUIRED Une adhésion est requise avant PLAY. Consultez d’abord REALMS , puis utilisez JOIN ."); + assertThat(renderer.render(result.outputs().get(0), "de")) + .isEqualTo( + "ERROR JOIN_REQUIRED Membership is required before PLAY. Run REALMS first, then JOIN ."); assertThat( meterRegistry .counter("gamesession.session.resume_denied", "reason", "join_required") From a577dd1c2cc449eeaa6f2334abfb6c8316a61455 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 19:12:52 +1300 Subject: [PATCH 034/105] Preserve private discovery and caller-bound character selection --- .../command/text/GameplayWorldCatalog.java | 2 - .../command/text/WorldsCommandHandler.java | 106 +++++++-- .../presentation/WorldsViewOutput.java | 6 +- .../text/WorldsCommandHandlerTest.java | 222 +++++++++++++++++- .../presentation/PlayerOutputTest.java | 2 +- .../TextPlayerOutputRendererTest.java | 8 +- .../presentation/WorldsViewOutputTest.java | 4 +- .../WebSocketOutputProjectorTest.java | 33 +++ ...ionAccountCrossServiceIntegrationTest.java | 6 +- 9 files changed, 343 insertions(+), 46 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 2595a01242..3d6cdc25cc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -89,7 +89,6 @@ public DiscoverySnapshot readDiscoverySnapshot() { ordinal, world.slug(), world.displayName(), - defaultRealm.gameInstanceId(), defaultRealm.requiresCharacterSelection())); targets.add( new WorldOrdinalTarget( @@ -745,7 +744,6 @@ private List worldEntries() { entries.size() + 1, world.slug(), world.displayName(), - defaultRealm.gameInstanceId(), defaultRealm.requiresCharacterSelection())); } return List.copyOf(entries); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index b1ec76abce..cbc28bad7d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -324,35 +324,95 @@ private RealmSelectorResolution resolveLobbyRealm( return new RealmSelectorResolution.Unavailable(); } if (maybeSnapshot.isEmpty()) { - return new RealmSelectorResolution.Stale(); + return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR); } DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); if (!snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { - return new RealmSelectorResolution.Stale(); + return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } int ordinal; try { ordinal = Integer.parseInt(selector.trim()); } catch (NumberFormatException ex) { - return new RealmSelectorResolution.Stale(); + return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR); } Optional maybeTarget = snapshot.ordinalTargets().stream() .filter(target -> target.ordinal() == ordinal) .findFirst(); if (maybeTarget.isEmpty()) { - return new RealmSelectorResolution.Stale(); + return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR); } return worldCatalog .resolveRealmSnapshotOrdinal(world, currentCatalog, maybeTarget.orElseThrow()) .map(RealmSelectorResolution.Selected::new) - .orElseGet(RealmSelectorResolution.Stale::new); + .orElseGet( + () -> new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH)); + } + + private RealmSelectorResolution resolveOmittedLobbyRealm( + SessionContext caller, + GameplayWorldCatalog.DiscoverySnapshot currentWorldCatalog, + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog) { + if (connectScopeSessionStore == null) { + return new RealmSelectorResolution.Unavailable(); + } + Optional maybeSnapshot; + try { + maybeSnapshot = + connectScopeSessionStore.realmsSnapshot( + caller, worldTenantId(world), world.slug(), Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return new RealmSelectorResolution.Unavailable(); + } + if (maybeSnapshot.isPresent()) { + DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); + if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) + || snapshot.tenantId() != worldTenantId(world) + || !snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { + return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + } + if (snapshot.ordinalTargets().size() > 1) { + return new RealmSelectorResolution.RequiresSelection(); + } + if (snapshot.ordinalTargets().isEmpty()) { + return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + } + return worldCatalog + .resolveRealmSnapshotOrdinal( + world, currentRealmCatalog, snapshot.ordinalTargets().getFirst()) + .map(RealmSelectorResolution.Selected::new) + .orElseGet( + () -> new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH)); + } + + // Without a caller-specific REALMS snapshot, only the canonical public default is a safe + // omitted target. Private catalog cardinality is not evidence that the caller may discover or + // select any of those realms. + if (!worldCatalog.isPubliclyDiscoverable(currentWorldCatalog, world)) { + return new RealmSelectorResolution.Invalid(); + } + List publicRealms = + worldCatalog.visibleRealms(world).stream() + .filter(GameplayWorldCatalog.RealmView::publicProductionRealm) + .toList(); + return publicRealms.size() == 1 + ? new RealmSelectorResolution.Selected(publicRealms.getFirst()) + : new RealmSelectorResolution.RequiresSelection(); + } + + private enum RealmSelectorStaleReason { + UNBOUND_SELECTOR, + SNAPSHOT_MISMATCH } private sealed interface RealmSelectorResolution permits RealmSelectorResolution.Selected, RealmSelectorResolution.NoSelection, RealmSelectorResolution.Invalid, + RealmSelectorResolution.RequiresSelection, RealmSelectorResolution.Stale, RealmSelectorResolution.Unavailable { record Selected(GameplayWorldCatalog.RealmView realm) implements RealmSelectorResolution {} @@ -361,7 +421,9 @@ record NoSelection() implements RealmSelectorResolution {} record Invalid() implements RealmSelectorResolution {} - record Stale() implements RealmSelectorResolution {} + record RequiresSelection() implements RealmSelectorResolution {} + + record Stale(RealmSelectorStaleReason reason) implements RealmSelectorResolution {} record Unavailable() implements RealmSelectorResolution {} } @@ -794,28 +856,32 @@ public CharacterBrowseResult browseCharacters( } RealmSelectorResolution realmSelection = resolveLobbyRealm(sessionContext, world, realmSelector, currentRealmCatalog); + if (realmSelection instanceof RealmSelectorResolution.NoSelection) { + realmSelection = + resolveOmittedLobbyRealm(sessionContext, catalogSnapshot, world, currentRealmCatalog); + } if (realmSelection instanceof RealmSelectorResolution.Unavailable) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); } - if (realmSelection instanceof RealmSelectorResolution.Stale) { + if (realmSelection instanceof RealmSelectorResolution.Stale stale) { + if (stale.reason() == RealmSelectorStaleReason.UNBOUND_SELECTOR + && !worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { + return CharacterBrowseResult.invalidWorld(); + } return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } - java.util.Optional maybeRealm = - realmSelection instanceof RealmSelectorResolution.Selected selected - ? java.util.Optional.of(selected.realm()) - : StringUtils.hasText(realmSelector) - ? java.util.Optional.empty() - : worldCatalog.requiresExplicitRealmSelection(world) - ? java.util.Optional.empty() - : worldCatalog.resolveDefaultRealm(world); - if (StringUtils.hasText(realmSelector) && maybeRealm.isEmpty()) { - return CharacterBrowseResult.invalidRealm(world.slug()); - } - if (!StringUtils.hasText(realmSelector) && maybeRealm.isEmpty()) { + if (realmSelection instanceof RealmSelectorResolution.RequiresSelection) { return CharacterBrowseResult.realmSelectionRequired(world.slug()); } + if (realmSelection instanceof RealmSelectorResolution.Invalid) { + return StringUtils.hasText(realmSelector) + && worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) + ? CharacterBrowseResult.invalidRealm(world.slug()) + : CharacterBrowseResult.invalidWorld(); + } - GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); + GameplayWorldCatalog.RealmView realm = + ((RealmSelectorResolution.Selected) realmSelection).realm(); boolean currentPointerMatches; try { currentPointerMatches = worldCatalog.matchesCurrentAdmissionPointer(world, realm); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java index bbfe4786cd..1d858ea5a8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java @@ -10,11 +10,7 @@ public record WorldsViewOutput(List worlds) implements PlayerOutputP } public record WorldEntry( - int ordinal, - String slug, - String displayName, - long gameInstanceId, - boolean requiresCharacterSelection) { + int ordinal, String slug, String displayName, boolean requiresCharacterSelection) { public WorldEntry { if (ordinal < 1) { throw new IllegalArgumentException("ordinal must be at least 1"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 7568cc497d..3ef5453dba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -342,7 +342,7 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() 2L, 1L, true, - true, + false, false, "SHARED", "ALLOW_NEW", @@ -354,6 +354,15 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() AtomicReference> worlds = new AtomicReference<>(List.of(original)); AccountClient accountClient = Mockito.mock(AccountClient.class); + stubActivePrivateAuthorization(accountClient, "demo"); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("preview"), + Mockito.anyString())) + .thenReturn(grant("demo", "preview", true)); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() @@ -367,7 +376,10 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); - localHandler.browseRealms("7", authenticatedSession(), "demo"); + assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().realms()).hasSize(2)); Mockito.clearInvocations(accountClient, entityManagementClient); worlds.set( List.of( @@ -430,12 +442,15 @@ void browseCharactersReturnsStructuredCharacterList() { .build()); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); + SessionContext session = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + assertThat(localHandler.browseRealms(session, "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().realms()).hasSize(1)); WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), - "demo", - null); + localHandler.browseCharacters(session, "demo", null); assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); CharacterBrowseViewOutput output = @@ -484,12 +499,15 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .build()); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); + SessionContext session = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + assertThat(localHandler.browseRealms(session, "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().realms()).hasSize(1)); WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), - "demo", - null); + localHandler.browseCharacters(session, "demo", null); assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); CharacterBrowseViewOutput output = @@ -569,7 +587,7 @@ void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { localHandler.browseCharacters( new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), "demo", - null); + "production"); assertThat(result) .isEqualTo( @@ -1259,6 +1277,188 @@ void privateOnlyCharacterSelectorMatchesUnknownWhenDeniedAndRemainsReachableWhen .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } + @Test + void privateOnlyUnknownAmbiguousAndUnboundRealmSelectorsMatchUnknownWorld() { + GameplayCatalogProperties properties = privateOnlyWorldProperties(); + GameplayCatalogProperties.World privateWorld = properties.getWorlds().get(1); + GameplayCatalogProperties.Realm caseAlias = + world("private-only", 22L, 3L, false).getRealms().getFirst(); + caseAlias.setSlug("PREVIEW"); + caseAlias.setPublicProductionRealm(false); + privateWorld.setRealms(List.of(privateWorld.getRealms().getFirst(), caseAlias)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult unknownWorld = + localHandler.browseCharacters(authenticatedSession(), "unknown", "preview"); + + assertThat(unknownWorld).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "missing")) + .isEqualTo(unknownWorld); + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "PrEvIeW")) + .isEqualTo(unknownWorld); + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) + .isEqualTo(unknownWorld); + assertThat(localHandler.browseCharacters(authenticatedSession(), "PRIVATE-ONLY", "1")) + .isEqualTo(unknownWorld); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + + @Test + void unboundPublicRealmOrdinalRemainsConnectScopeMismatch() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + authenticatedHandler(publicProductionProperties(), accountClient); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + + @Test + void omittedCharactersIgnoreHiddenPrivateRealmCardinalityForPublicDefault() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); + WorldsCommandHandler localHandler = + authenticatedHandler(publicWorldWithPrivateRealm(), accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", null); + + assertThat(result) + .isInstanceOfSatisfying( + WorldsCommandHandler.CharacterBrowseResult.Success.class, + success -> assertThat(success.output().realmSlug()).isEqualTo("production")); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + @Test + void omittedCharactersRequireChoiceAmongCallerVisibleRealmsAndKeepOrdinalBinding() { + GameplayCatalogProperties properties = privateOnlyWorldProperties(); + GameplayCatalogProperties.World privateWorld = properties.getWorlds().get(1); + GameplayCatalogProperties.Realm staff = + world("private-only", 22L, 3L, false).getRealms().getFirst(); + staff.setSlug("staff"); + staff.setDisplayName("Staff Realm"); + staff.setPublicProductionRealm(false); + privateWorld.setRealms(List.of(privateWorld.getRealms().getFirst(), staff)); + + AccountClient accountClient = Mockito.mock(AccountClient.class); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("private-only"), + Mockito.anyString(), + Mockito.anyString())) + .thenAnswer( + invocation -> grant("private-only", invocation.getArgument(3, String.class), true)); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + Mockito.when( + entityManagementClient.listCharactersByAccount( + Mockito.eq("22"), + Mockito.eq("123"), + Mockito.anyString(), + Mockito.eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED))) + .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(properties), + entityManagementClient, + accountClient, + scopeStore); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + assertThat(localHandler.browseRealms(authenticatedSession(), "PRIVATE-ONLY")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().realms()).hasSize(2)); + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.realmSelectionRequired("private-only")); + + WorldsCommandHandler.CharacterBrowseResult ordinalSelection = + localHandler.browseCharacters(authenticatedSession(), "PRIVATE-ONLY", "1"); + + assertThat(ordinalSelection) + .isInstanceOfSatisfying( + WorldsCommandHandler.CharacterBrowseResult.Success.class, + success -> assertThat(success.output().realmSlug()).isEqualTo("preview")); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + @Test + void omittedCharactersRequireExplicitRealmWhenPublicAndPrivateChoicesWereDiscovered() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("playtest"), + Mockito.anyString())) + .thenReturn(grant("demo", "playtest", true)); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(publicWorldWithPrivateRealm()), + entityManagementClient, + accountClient, + scopeStore); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().realms()).hasSize(2)); + Mockito.clearInvocations(accountClient, entityManagementClient); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", null)) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.realmSelectionRequired("demo")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } + @Test void authenticatedBrowseOmitsPrivateRealmWithoutExactGrant() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java index 29f1a4a443..4ee23a730b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java @@ -33,7 +33,7 @@ void screenBufferEligibilityFollowsReplayPolicyAndOutputKind() { PlayerOutput.view( new WorldsViewOutput( java.util.List.of( - new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", 1L, false)))) + new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", false)))) .screenBufferEligible()) .isFalse(); assertThat(PlayerOutput.prompt("demo> ").screenBufferEligible()).isFalse(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index 1a0cc8a560..10a123cfc8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -899,7 +899,9 @@ void publicJoinOutcomesRenderCurrentGuidanceAndPolicyDenial() { renderer.render( PlayerOutput.error( "JOIN_REQUIRED", "fallback", "error.play.join-required", java.util.Map.of()))) - .isEqualTo("ERROR JOIN_REQUIRED Membership is required before PLAY. Use JOIN ."); + .isEqualTo( + "ERROR JOIN_REQUIRED Membership is required before PLAY. " + + "Run REALMS first, then JOIN ."); assertThat( renderer.render( PlayerOutput.error( @@ -1068,9 +1070,9 @@ void renderAllFormatsWorldsViewAsCommandBody() { PlayerOutput.view( new WorldsViewOutput( List.of( - new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", 1L, false), + new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", false), new WorldsViewOutput.WorldEntry( - 2, "sandbox", "Builder Sandbox", 2L, true)))))); + 2, "sandbox", "Builder Sandbox", true)))))); assertThat(rendered) .isEqualTo("OK WORLDS\n1) Demo World (demo)\n2) Builder Sandbox (sandbox)\n\n"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java index 7e3bdd2e97..7d453de71c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java @@ -11,7 +11,7 @@ class WorldsViewOutputTest { void worldsAreCopiedDefensively() { List worlds = new java.util.ArrayList<>( - List.of(new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", 1L, false))); + List.of(new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", false))); WorldsViewOutput output = new WorldsViewOutput(worlds); worlds.clear(); @@ -21,7 +21,7 @@ void worldsAreCopiedDefensively() { @Test void ordinalMustBePositive() { - assertThatThrownBy(() -> new WorldsViewOutput.WorldEntry(0, "demo", "Demo World", 1L, false)) + assertThatThrownBy(() -> new WorldsViewOutput.WorldEntry(0, "demo", "Demo World", false)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("ordinal"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index 7f8a9ce394..0646e3b7fd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -34,6 +34,7 @@ import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WhoViewOutput; +import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.Test; @@ -157,6 +158,38 @@ void firstPartyRealmsCommandDoesNotExposeRuntimeTargetOrEnterReplayBuffer() thro assertThat(output.screenBufferEligible()).isFalse(); } + @Test + void firstPartyWorldsCommandDoesNotExposeRuntimeTarget() throws Exception { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + GameplayCatalogProperties catalog = new GameplayCatalogProperties(); + catalog.setWorlds(List.of(catalog.getWorlds().getFirst())); + WorldsViewOutput worlds = TestGameplayWorldCatalogs.fromProperties(catalog).browseView(); + PlayerOutput output = PlayerOutput.view(worlds); + + String payload = + projector.projectCommandResponse( + session, + new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), + new TextCommandInterpretationResult(CommandEnqueueResult.success(), List.of(output)), + List.of(output), + "en-NZ", + presentation); + + JsonNode json = objectMapper.readTree(payload); + JsonNode outputJson = json.path("outputs").get(0); + JsonNode worldJson = outputJson.path("payload").path("worlds").get(0); + assertThat(json.path("commandType").asText()).isEqualTo("WORLDS"); + assertThat(outputJson.path("payloadType").asText()).isEqualTo("worlds_view"); + assertThat(worldJson.path("ordinal").asInt()).isEqualTo(1); + assertThat(worldJson.path("slug").asText()).isEqualTo("demo"); + assertThat(worldJson.path("displayName").asText()).isEqualTo("Demo World"); + assertThat(worldJson.has("gameInstanceId")).isFalse(); + } + @Test void firstPartyWebReceivesCanonicalAuthoredCommandId() throws Exception { WebSocketSession session = mock(WebSocketSession.class); diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 496d6abdef..8be8f6b897 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -177,13 +177,15 @@ void telnetReconnectAfterRevocationFailsPlayAdmission() throws Exception { assertThat(client.readLineContaining("ERROR JOIN_REQUIRED")) .contains("ERROR JOIN_REQUIRED") .contains( - "Membership is required before PLAY; joining this world is not available yet."))) { + "Membership is required before PLAY. " + + "Run REALMS first, then JOIN ."))) { assertThat(scenario.responses()) .anyMatch(response -> response.contains("ERROR JOIN_REQUIRED")) .anyMatch( response -> response.contains( - "Membership is required before PLAY; joining this world is not available yet.")); + "Membership is required before PLAY. " + + "Run REALMS first, then JOIN .")); } } From a4e8939bf980e1882dec5d6dabc91e37c6de1b9f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 19:59:35 +1300 Subject: [PATCH 035/105] Align text PLAY and JOIN status without claiming full admission --- ...021-staged-player-authentication-and-gameplay-binding.md | 4 ++-- .../microservices/account-service/api-contracts.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md index 50424d44fd..094a525895 100644 --- a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md +++ b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. Explicit `POST /auth/bootstrap/join` before bootstrap character creation/connect-token work remains a gap. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance and text `PLAY` require the four-field Account admission response, never invoke an implicit membership writer, and may return non-actionable `JOIN_REQUIRED` for an eligible fresh authoritative public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable; the obsolete writer seam has been removed. The current response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains target-only. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven, and explicit `JOIN` remains unimplemented. The target first-party admission gate therefore remains incomplete until explicit `JOIN`, the joining-policy gate, the active-state check, the generation reread, the unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the unimplemented explicit-membership `JOIN` path; its `known_drift` must also explicitly name the missing joining-policy, active-state, membership-generation, and membership-version baseline checks. +Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The Account `/auth/bootstrap/join` controller and operation exist locally, but its public Gateway route remains denied, so browser `Join & Play` is still unavailable. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance still uses the partial membership response and does not enforce the emitted lifecycle/generation fields; its independent version/generation issuance baseline reread and fresh replay validation remain unproved. In contrast, Game Session text `PLAY` locally validates the fresh response identity, lifecycle, membership version, authority generation, and evaluation time. Missing or `INACTIVE` public-production membership gets `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` checks; other non-admitting states remain denials. Game Session direct-text `REALMS`/`JOIN` dispatch now invokes the Account writer using its retained scope and request state. These local checks do not establish positive live Account runtime reads, which remain fail closed pending typed caller/target authority, or prove the full direct-text/Telnet flow. The exact connect-token issuance baseline and ADR 0030 admission-lease/replay requirements remain unimplemented or unproved. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. Current route status and proof gaps are recorded in [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../../project-management/implementation-tracking/player-access-and-session.md#capability-status). The current `GameplayHandshakeFilter` accepts one cookie or header, rejects simultaneous carriers, and consumes an untagged replay marker through the generic Cache-bound client, but does not implement ADR 0029's tagged Coordination Redis readiness/fence and quarantine contract. Target player-facing admission remains quarantined until that cutover and proof complete. That current parser support does not establish public non-browser issuance or an accepted target non-first-party route/carrier. @@ -27,7 +27,7 @@ That current parser support does not establish public non-browser issuance or an First-party browsers and explicitly classified non-browser WebSocket clients authenticate through the HTTPS bootstrap/connect-token path before opening public gameplay WebSockets, while Telnet and other non-WebSocket text transports need an in-band credential path. FireMUD must distinguish transport admission, account authentication, and gameplay binding without making the Gateway the general account-authentication authority. [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md) subsequently made a connect token mandatory for every non-proxy public `/ws/game/**` handshake and defined the dedicated header carrier for non-browser clients. -The staged design is partially implemented and tested. It keeps the first-party browser bootstrap/connect-token/WebSocket path separate from the credential-bearing text-protocol path, while both leave Game Session as the final gameplay-login state owner. The current membership existence check is implemented, while explicit membership joining and the complete membership-authority-generation reread remain target-state work. +The staged design is partially implemented and tested. It keeps the first-party browser bootstrap/connect-token/WebSocket path separate from the credential-bearing text-protocol path, while both leave Game Session as the final gameplay-login state owner. Local direct-text joining and response validation exist; the complete first-party issuance baseline, live authority and end-to-end proof remain gaps as recorded in [Implementation Status](#implementation-status). ## Decision diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d2dccc38e0..07f0c70011 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token issuance and text `PLAY` do not enforce the emitted lifecycle state or generation; they proceed only when the two admission booleans are true, and an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`. The consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. The Account writer's unknown-commit recovery, PostgreSQL runtime proof, and direct-text end-to-end proof remain open. Game Session's direct-text `REALMS`/`JOIN` dispatch now uses the retained Account-issued scope and invokes that writer locally. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token issuance still does not enforce the emitted lifecycle state or generation and relies on `membershipExists`/`gameplayAdmissionAllowed`; its independent issuance baseline, fresh replay validation, and complete lease contract remain unproved. In contrast, Game Session text `PLAY` locally validates the fresh response's account/tenant identity, membership lifecycle, positive membership version and authority generation for an existing member, and evaluation time. It returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh entitlement and `allowPublicJoin` checks; other non-admitting states remain denials. These local checks do not prove positive live Account runtime reads, which remain fail closed pending typed caller/target authority. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current vs Target Export Lifecycle @@ -109,7 +109,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`; Game Session text `PLAY` locally validates the response identity, lifecycle, version, generation, and evaluation time before admission. Account's live runtime reader still fails closed before returning positive data until the required typed caller/target authority is implemented, so this local validation is not end-to-end admission proof. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, including the issuance baseline and reread, and consumers must fail closed on exact lifecycle/generation checks. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. @@ -190,7 +190,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | | `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. The Account route exists locally, but its exact public Gateway path is currently denied by the explicit route guard; this is an exposure restriction, not target-only controller status. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | +| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. The Account route exists locally, but its exact public Gateway path is currently denied by the explicit route guard; this is an exposure restriction, not target-only controller status. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session direct-text `REALMS`/`JOIN` dispatch is implemented locally against the retained Account-issued scope; the complete text flow remains unproved. Unknown-outcome recovery/reconciliation and Logging receipt receiver/readback remain open, as do first-party browser `Join & Play` and public Gateway route availability. See [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) and the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status) for current flow and proof status. | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | From 16e7659a4aebf23f38d219c85def1536639b8cdd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:35:00 +1300 Subject: [PATCH 036/105] Preserve strict authority error and realm fixture contracts after reconciliation --- .../command/text/GameplayWorldCatalog.java | 6 +++--- .../command/text/SessionResumptionFlowTest.java | 2 +- .../command/text/WorldsCommandHandlerTest.java | 13 +++++++++++++ .../text/WorldsTextCommandDispatchHandlerTest.java | 6 ++++++ 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index f25ebe7467..2af921e9e1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -251,7 +251,7 @@ public Optional resolveWorldFromAuthoritySnapshot(String selector) { return resolveWorld(selector, visibleWorlds, visibleWorlds) .filter(world -> hasValidPublicProductionRealm(world, catalogState)); } - List pointers = readAuthorityPointers(); + List pointers = authorityPointerSupplier.get(); if (pointers == null) { throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); @@ -624,7 +624,7 @@ public List visibleWorldsFromAuthoritySnapshot() { if (authorityPointerSupplier == null) { return visibleWorlds(); } - List pointers = readAuthorityPointers(); + List pointers = authorityPointerSupplier.get(); if (pointers == null) { throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); @@ -653,7 +653,7 @@ public void requireUniqueVisiblePublicProductionRealm( throw new AuthorityPointerUnavailableException( "Authoritative public-production realm identity is unavailable"); } - List pointers = readAuthorityPointers(); + List pointers = authorityPointerSupplier.get(); if (pointers == null) { throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index f4558034be..a815f5f545 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -449,7 +449,7 @@ void logoutAliasesDoNotNormalizeStaleBindingBeforeFailingClosed() { assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); SessionContext before = sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow(); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) - .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 2L))); + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 2L, true))); for (String alias : List.of("LOGOUT", "LOGOFF", "QUIT")) { TextCommandInterpretationResult result = interpreter.interpret("1", alias, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 621f5fa16c..70353dafaf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -418,6 +418,12 @@ void browseRealmsToleratesNullRealmEnums() { void browseCharactersReturnsStructuredCharacterList() { gameplayCatalogProperties.setWorlds( List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(false); gameplayCatalogProperties .getWorlds() .get(1) @@ -470,6 +476,12 @@ void browseCharactersReturnsStructuredCharacterList() { @Test void browseCharactersUsesIsolatedStateRealmRoster() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(false); gameplayCatalogProperties .getWorlds() .getFirst() @@ -893,6 +905,7 @@ void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoste void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 5a3ad2f9ab..c330a86bb4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -83,6 +83,12 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { void publishesCommandEventForGameplayScopedRealmsBrowse() { gameplayCatalogProperties.setWorlds( List.of(world("sandbox", 1L, 2L, false), world("authority", 1L, 1L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(false); gameplayCatalogProperties .getWorlds() .get(1) From 8984cc182b4cb6d1ddf8e7a91c97d067e6fefad4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:13:36 +1300 Subject: [PATCH 037/105] Map default PLAY authority outages to typed failure --- .../command/text/PlayCommandHandler.java | 25 ++++++-- .../command/text/PlayCommandHandlerTest.java | 59 +++++++++++++++++++ 2 files changed, 78 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 47ff202b04..43a4ea06e2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -301,12 +301,25 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { null, null); } - Optional maybeRealm = - realmSelection instanceof RealmSelectorResolution.Selected selected - ? Optional.of(selected.realm()) - : selection.explicitRealmSelector() != null - ? Optional.empty() - : selectDefaultRealm(selectedWorld, connectContextResolution.connectContext()); + Optional maybeRealm; + try { + maybeRealm = + realmSelection instanceof RealmSelectorResolution.Selected selected + ? Optional.of(selected.realm()) + : selection.explicitRealmSelector() != null + ? Optional.empty() + : selectDefaultRealm(selectedWorld, connectContextResolution.connectContext()); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return failure( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE, + "error.play.authority-unavailable", + Map.of(), + tenantTag, + null, + null, + ex); + } if (maybeRealm.isEmpty()) { return failure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 736b12805d..6dd954493e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -917,6 +917,65 @@ void playMapsPointerAuthorityReadFailureBeforeAccountOrEntityAdmissionReads() { scriptEventPublisher); } + @ParameterizedTest + @ValueSource(strings = {"throw", "null"}) + void playMapsDefaultRealmPointerReadFailureToAuthUnavailableWithoutAdmissionSideEffects( + String failureMode) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + AtomicInteger pointerReads = new AtomicInteger(); + when(authorityService.listPointers()) + .thenAnswer( + invocation -> { + if (pointerReads.getAndIncrement() == 0) { + return List.of(admissionPointer(1L)); + } + if ("throw".equals(failureMode)) { + throw new IllegalStateException("authority down during default realm resolution"); + } + return null; + }); + PlayCommandHandler authorityBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authorityService), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + connectScopeSessionStore); + SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + authorityBackedHandler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE); + assertThat(((ErrorOutput) result.outputs().getFirst().payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + assertThat(pointerReads).hasValue(2); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + Mockito.verify(firstPartyConnectContextRegistry, never()) + .register(Mockito.anyLong(), Mockito.any()); + Mockito.verify(firstPartyConnectContextRegistry, never()).unregister(Mockito.anyLong()); + } + @Test void playUsesSelectedTenantAuthorityWhenAnotherTenantInWorldHasNoPublicProductionRealm() { gameplayCatalogProperties From 2f7cd7c99af58ae9f5faa8f0208fb04773ac7b16 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:42:19 +1300 Subject: [PATCH 038/105] Keep hidden realm PLAY denials non-enumerating --- .../game-session-service/protocols.md | 2 +- .../system-architecture-authentication.md | 2 +- .../command/text/PlayCommandHandler.java | 58 +++-- .../command/text/PlayCommandHandlerTest.java | 206 ++++++++++++++++++ 4 files changed, 244 insertions(+), 24 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 3a97d22e27..46dac68f86 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`. For a public-production target with fresh `MISSING` or non-admitting `INACTIVE` membership, it evaluates fresh tenant entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public-policy denial takes precedence. Non-public missing or non-admitting membership is first classified as `WORLD_ACCESS_DENIED`; when the selected world is absent from the public `WORLDS` projection, current `PLAY` returns generic `PLAY_SELECTION_REQUIRED` without target metadata instead. Publicly discoverable worlds retain `WORLD_ACCESS_DENIED`, and unavailable authority is not masked. This is current implementation behavior, not a target-contract change; canonical error ownership and discovery policy remain in [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries) and [ADR 0168](../../decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md). Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. Its fresh membership response now carries lifecycle, authority-generation, version, and evaluation-time fields, but the target independent issuance-time generation/version baseline reread and durable replay revalidation remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`. For a public-production target with fresh `MISSING` or non-admitting `INACTIVE` membership, it evaluates fresh tenant entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public-policy denial takes precedence. Current two-token `PLAY ` shorthand recognizes only visible realm names and otherwise treats the name as a character selector; an explicit `PLAY ` retains its realm selector even when unresolved or hidden. Non-public missing or non-admitting membership is first classified as `WORLD_ACCESS_DENIED`; a definitive denial for a selected realm that is not both visible and public-production returns generic `PLAY_SELECTION_REQUIRED`, even when its containing world is publicly discoverable. For a discoverable world, this projection matches the unresolved-realm result; the existing generic projection for a non-discoverable world is retained. A visible public-production target retains its canonical `WORLD_ACCESS_DENIED` outcome, and unavailable authority is not masked. This is current implementation behavior, not a target-contract change; canonical error ownership and discovery policy remain in [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries) and [ADR 0168](../../decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md). Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. Its fresh membership response now carries lifecycle, authority-generation, version, and evaluation-time fields, but the target independent issuance-time generation/version baseline reread and durable replay revalidation remain gaps. For logout and retained private semantic context, [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) owns the binding termination fence and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) owns namespace-scoped `resumeContextGeneration` and replay eligibility. Current player text handling rejects `LOGOUT` before side effects, and first-party private semantic transcript replay is gated when durable episode/binding termination proof is unavailable; fresh authoritative `LOOK` remains available. This fail-closed child behavior does not establish the durable successor protocol or complete either ADR. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 43be5ae674..4476096c35 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the target independent membership-version and authority-generation baseline reread at connect-token issuance remains a proof gap. On a connect-token cache miss, current issuance consumes its implemented membership evidence; a `session:connect-token:*` replay hit can return cached success before fresh entitlement, membership, and pointer rereads. The exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` does not use that replay cache: each attempt reads current Account membership and validates exact `accountId`/`tenantId`, lifecycle, membership version, authority generation, admission state, and a fresh evaluation time before binding. Existing-member admission requires `membershipLifecycleState=ACTIVE` and `gameplayAdmissionAllowed=true`. For public production, only a fresh `MISSING` or `INACTIVE` membership can return `JOIN_REQUIRED`, and only after fresh tenant entitlement and `allowPublicJoin=true` checks; invalid or unavailable membership evidence fails closed, while public-policy denial remains a distinct denial. Text `PLAY` separately reads the current realm grant for private/playtest targets; its current non-public missing or non-admitting membership outcome is `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. The Account runtime response now includes lifecycle and authority-generation fields, but connect-token issuance does not establish the target independent issuance-time baseline or durable replay revalidation. The complete first-party browser/mobile sequence remains partial, with PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof gaps. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the target independent membership-version and authority-generation baseline reread at connect-token issuance remains a proof gap. On a connect-token cache miss, current issuance consumes its implemented membership evidence; a `session:connect-token:*` replay hit can return cached success before fresh entitlement, membership, and pointer rereads. The exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` does not use that replay cache: each attempt reads current Account membership and validates exact `accountId`/`tenantId`, lifecycle, membership version, authority generation, admission state, and a fresh evaluation time before binding. Existing-member admission requires `membershipLifecycleState=ACTIVE` and `gameplayAdmissionAllowed=true`. For public production, only a fresh `MISSING` or `INACTIVE` membership can return `JOIN_REQUIRED`, and only after fresh tenant entitlement and `allowPublicJoin=true` checks; invalid or unavailable membership evidence fails closed, while public-policy denial remains a distinct denial. Text `PLAY` separately reads the current realm grant for private/playtest targets; its internal non-public missing or non-admitting membership classification is `WORLD_ACCESS_DENIED`. Definitive denial for an explicitly selected hidden or non-public-production realm projects the same selection-required response as an unresolved realm within a publicly discoverable world; a non-discoverable world retains the generic selection-required response without target metadata. Visible public-production denial and unavailable authority retain their distinct outcomes. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. The Account runtime response now includes lifecycle and authority-generation fields, but connect-token issuance does not establish the target independent issuance-time baseline or durable replay revalidation. The complete first-party browser/mobile sequence remains partial, with PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof gaps. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 43a4ea06e2..4ea0800612 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -321,15 +321,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { ex); } if (maybeRealm.isEmpty()) { - return failure( - GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, - explicitRealmSelectionMessage(selectedWorld), - "error.play.realm-selection-required", - Map.of("worldSlug", selectedWorld.slug()), - tenantTag, - null, - null, - null); + return realmSelectionRequiredFailure(selectedWorld, tenantTag); } GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); @@ -368,17 +360,24 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { validateRuntimeAdmission(context, selectedWorld, selectedRealm, selectedTenantTag, 0L); if (authorityFailure.isPresent()) { PlayCommandHandlingResult admissionFailure = authorityFailure.orElseThrow(); - if (!gameplayWorldCatalog.isPubliclyDiscoverable(currentCatalog, selectedWorld) - && isDefinitivePrivateWorldDenial(admissionFailure)) { - return failure( - GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, - GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_MESSAGE, - "error.play.selection-required", - Map.of(), - tenantTag, - null, - null, - null); + if (isDefinitivePrivateWorldDenial(admissionFailure)) { + boolean publiclyDiscoverableWorld = + gameplayWorldCatalog.isPubliclyDiscoverable(currentCatalog, selectedWorld); + if (!publiclyDiscoverableWorld + || !selectedRealm.visible() + || !selectedRealm.publicProductionRealm()) { + return publiclyDiscoverableWorld + ? realmSelectionRequiredFailure(selectedWorld, tenantTag) + : failure( + GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, + GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_MESSAGE, + "error.play.selection-required", + Map.of(), + tenantTag, + null, + null, + null); + } } return admissionFailure; } @@ -1375,11 +1374,13 @@ private Optional resolveSelection( private ResolvedPlaySelection disambiguateSelection( ResolvedPlaySelection requestedSelection, GameplayWorldCatalog.WorldView selectedWorld) { String secondSelector = requestedSelection.explicitRealmSelector(); - if (!StringUtils.hasText(secondSelector) + if (StringUtils.hasText(requestedSelection.characterSelector()) + || !StringUtils.hasText(secondSelector) || GameplayWorldCatalog.isOrdinalSelector(secondSelector) - || gameplayWorldCatalog.hasRealmForAdmission(selectedWorld, secondSelector)) { + || gameplayWorldCatalog.resolveRealm(selectedWorld, secondSelector).isPresent()) { return requestedSelection; } + // Character shorthand must not reveal hidden realm existence through interpretation. return new ResolvedPlaySelection(requestedSelection.worldSelector(), null, secondSelector); } @@ -1407,6 +1408,19 @@ private String explicitRealmSelectionMessage(GameplayWorldCatalog.WorldView sele + " [character] or browse REALMS first."; } + private PlayCommandHandlingResult realmSelectionRequiredFailure( + GameplayWorldCatalog.WorldView selectedWorld, String tenantTag) { + return failure( + GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, + explicitRealmSelectionMessage(selectedWorld), + "error.play.realm-selection-required", + Map.of("worldSlug", selectedWorld.slug()), + tenantTag, + null, + null, + null); + } + private String characterSelectionMessage( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { return "Selection required. Use " diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 6dd954493e..97f047cb80 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2287,6 +2287,190 @@ void privateOnlyWorldPlayDenialMatchesUnknownAndGrantedAccessStillWorks() { assertThat(granted.commandResult()).isEqualTo(CommandEnqueueResult.success()); } + @Test + void playCharacterShorthandDoesNotDistinguishHiddenRealmFromUnknownName() { + addNonPublicRealmToPublicDemoWorld(false); + when(sessionAuthenticationService.resolveSessionContext("1")) + .thenReturn(Optional.of(loggedInUnboundContext())); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult hidden = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "invite-only"), "PLAY demo invite-only")); + PlayCommandHandlingResult unknown = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "unlisted"), "PLAY demo unlisted")); + + assertThat(hidden.commandResult()).isEqualTo(unknown.commandResult()); + assertThat(hidden.outputs()).isEqualTo(unknown.outputs()); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playHiddenRealmInPublicWorldMasksMembershipDenialLikeUnknownSelection() { + addNonPublicRealmToPublicDemoWorld(false); + SessionContext context = loggedInUnboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult denied = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "invite-only", "Emberline"), + "PLAY demo invite-only Emberline")); + PlayCommandHandlingResult unknown = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "unlisted", "Emberline"), + "PLAY demo unlisted Emberline")); + + assertHiddenRealmDenialMatchesUnknownSelection(denied, unknown, "invite-only"); + Mockito.verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playUnlistedNonPublicRealmInPublicWorldMasksDeniedGrantLikeUnknownSelection() { + addNonPublicRealmToPublicDemoWorld(true); + SessionContext context = loggedInUnboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("invite-only"), + Mockito.anyString())) + .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + + PlayCommandHandlingResult denied = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "invite-only", "Emberline"), + "PLAY demo invite-only Emberline")); + PlayCommandHandlingResult unknown = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "unlisted", "Emberline"), + "PLAY demo unlisted Emberline")); + + assertHiddenRealmDenialMatchesUnknownSelection(denied, unknown, "invite-only"); + Mockito.verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("demo"), + Mockito.eq("invite-only"), + Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playHiddenRealmInPublicWorldDoesNotMaskUnavailableMembershipAuthority() { + addNonPublicRealmToPublicDemoWorld(false); + SessionContext context = loggedInUnboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE") + .setMessage("Membership authority unavailable") + .build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "invite-only", "Emberline"), + "PLAY demo invite-only Emberline")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + ErrorOutput error = (ErrorOutput) result.outputs().getFirst().payload(); + assertThat(error.arguments()).isEmpty(); + assertThat(error.message()).doesNotContain("invite-only", "51"); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + } + @Test void playInvisibleRealmWithDeniedGrantClearsBinding() { markPreviewRealmInvisible(); @@ -2939,6 +3123,28 @@ private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } + private void addNonPublicRealmToPublicDemoWorld(boolean visible) { + GameplayCatalogProperties.Realm hiddenRealm = + realm("invite-only", "Invite-only Realm", 22L, 51L, visible, true); + hiddenRealm.setPublicProductionRealm(false); + gameplayCatalogProperties.getWorlds().getFirst().getRealms().add(hiddenRealm); + } + + private void assertHiddenRealmDenialMatchesUnknownSelection( + PlayCommandHandlingResult denied, PlayCommandHandlingResult unknown, String hiddenRealmSlug) { + assertThat(denied.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + assertThat(unknown.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + ErrorOutput error = (ErrorOutput) denied.outputs().getFirst().payload(); + assertThat(error).isEqualTo(unknown.outputs().getFirst().payload()); + assertThat(error.message()).doesNotContain(hiddenRealmSlug, "51"); + } + + private SessionContext loggedInUnboundContext() { + return new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + } + private SessionContext previewRealmContext() { return new SessionContext( 1L, From 9534981923a2e1644478ac407f90e8058cf51202 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:32:13 +1300 Subject: [PATCH 039/105] Contain namespace-unqualified character roster access --- .../game-session-service/protocols.md | 2 + .../player-access-and-session.md | 2 + .../client/EntityManagementClient.java | 26 +------ .../client/EntityManagementClientTest.java | 73 +++++++++++++++++++ .../command/text/PlayCommandHandlerTest.java | 6 +- .../text/WorldsCommandHandlerTest.java | 33 +++++++++ 6 files changed, 118 insertions(+), 24 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 46dac68f86..5c776b932e 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -18,6 +18,8 @@ For logout and retained private semantic context, [ADR 0019](../../decisions/adr Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). +Current production `CHARS` and `PLAY` roster access is contained at the shared Entity client because the live `ListCharactersByAccount` request and `Character` response do not establish the stable playable-state namespace. A positive `gameInstanceId` is only a replaceable runtime fence and cannot stand in for durable actor identity. The client preserves the existing `CHARACTER_LIST_UNAVAILABLE` failure without dispatching the legacy RPC; `CHARS` remains unavailable and `PLAY` retains its existing identity-unavailable outcome. Positive handler fixtures are offline-only evidence for mapping and error behavior, not runtime namespace proof. This containment follows [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity API contract](../entity-management-service/api-contracts.md); it does not alter separate `WORLDS` or `REALMS` discovery. + ### Reset and Recovery Consequence The canonical [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model) policy applies to Game Session coordination state. Any target region- or tenant-scoped reset must carry exactly one explicit gameplay-session policy, `--preserve-sessions` or `--invalidate-sessions`; no preserve default is allowed. Cluster-scoped reset requires `--invalidate-sessions`, and `sessionctx:*` pre-auth transport context is always invalidated or rebuilt and never preserved. The current runtime has no supported scoped-reset protocol; current clients therefore follow the existing fail-closed pause/status and reconnect behavior rather than treating reset as implicit session preservation. 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 1f85e4bdf3..36ab84554e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,6 +14,8 @@ Account runtime admission reads remain a security/proof blocker: both `GetTenant PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. +Current `AA-2.1` consequence: Game Session fails closed for production `CHARS` and `PLAY` roster access because the live `ListCharactersByAccount` request and returned `Character` omit `playableStateNamespaceId`; `gameInstanceId` cannot replace that stable durable actor identity. The shared Entity client returns the existing `CHARACTER_LIST_UNAVAILABLE` outcome without calling the legacy RPC; `CHARS` remains unavailable and `PLAY` preserves `PLAY_IDENTITY_UNAVAILABLE` before binding. Existing positive handler fixtures are offline-only proof of result mapping. The target namespace and actor rules remain owned by [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity Management API](../../architecture/microservices/entity-management-service/api-contracts.md). Namespace-qualified Entity authority, retained-row convergence, and its required migration gate remain separate gaps; `WORLDS` and `REALMS` continue through their current discovery paths. + Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` path provides read-only baseline evidence only. Namespace-aware shared-versus-isolated playable-state persistence exists for current state families, but the Account-owned restricted-synthetic identity/isolation verifier and corresponding persistent/shared mutation proof remain unavailable; independent two-transport mutation parity remains unimplemented and unproved. Run-owned Compose mutation and teardown remain implemented and proved at their bounded scope. See the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). SEC-04 does not move player session ownership into Logging & Admin. Game Session `/sessions*` lifecycle routes remain current owner-local hooks with direct owner edge exposure denied; the target external operator path forwards from Logging & Admin to Game Session after Account issues the authorization reference and the receiving Game Session redeems that same reference. That target lifecycle family, and other operator mutation families gated by action schemas, shared `mutationDigest/v1` vectors, and the authorization-reference flow, are not currently available to players or operators. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java index 17dcdc8914..18d933c243 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java @@ -16,7 +16,6 @@ import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.FindCharacterByNameRequest; import net.firedevops.firemud.entitymanagement.v1.FindCharacterByNameResponse; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesRequest; import net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse; @@ -136,28 +135,9 @@ public ListCharactersByAccountResponse listCharactersByAccount( String accountId, String gameInstanceId, PlayableStateScope playableStateScope) { - ListCharactersByAccountRequest request = - ListCharactersByAccountRequest.newBuilder() - .setTenantId(tenantId) - .setAccountId(accountId) - .setGameInstanceId(gameInstanceId) - .setPlayableStateScope(playableStateScope) - .build(); - try { - return callStub().listCharactersByAccount(request); - } catch (StatusRuntimeException ex) { - logger.warn( - "Failed to call Entity Management list-characters endpoint tenantId={} accountId={}", - tenantId, - accountId, - ex); - } catch (Exception ex) { - logger.warn( - "Failed to call Entity Management list-characters endpoint tenantId={} accountId={}", - tenantId, - accountId, - ex); - } + // The current Entity roster API cannot prove the stable playable-state namespace for these + // actors. gameInstanceId is only a replaceable runtime fence, so it cannot authorize a roster + // lookup as a substitute for namespace-qualified character identity. return ListCharactersByAccountResponse.newBuilder() .setError( ErrorDetail.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java index 370c36e59c..a4a27094e4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java @@ -1,13 +1,24 @@ 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.Mockito.mock; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.security.GameplaySessionAttestationService; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.Test; @@ -107,6 +118,68 @@ void findCharacterByNameRejectsLegacyRuntimeRoomIdsInSessionContextBeforeDispatc .hasMessageContaining("roomInstanceId must be a runtime room id like R-1021"); } + @Test + void listCharactersFailsClosedForCurrentAndReplacementInstancesWithinTheSameNamespace() + throws Exception { + AtomicInteger rosterRpcCalls = new AtomicInteger(); + String serverName = InProcessServerBuilder.generateName(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService( + new EntityManagementServiceGrpc.EntityManagementServiceImplBase() { + @Override + public void listCharactersByAccount( + ListCharactersByAccountRequest request, + StreamObserver responseObserver) { + rosterRpcCalls.incrementAndGet(); + responseObserver.onNext(ListCharactersByAccountResponse.getDefaultInstance()); + responseObserver.onCompleted(); + } + }) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService(serverName); + EntityManagementClient client = + new EntityManagementClient( + endpoints, + new CommonGrpcClientProperties(), + new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive) { + return channel; + } + }, + BlockingGrpcStubCustomizer.noop(), + mock(GameplaySessionAttestationService.class)); + try { + client.init(); + + // Both calls represent one durable namespace before and after runtime replacement. The + // current API cannot carry that namespace, so neither positive runtime ID is dispatchable. + ListCharactersByAccountResponse currentInstance = + client.listCharactersByAccount( + "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + ListCharactersByAccountResponse replacementInstance = + client.listCharactersByAccount( + "22", "123", "42", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + assertThat(currentInstance.getError().getCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + assertThat(replacementInstance.getError().getCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + assertThat(rosterRpcCalls).hasValue(0); + } finally { + client.close(); + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + private static EntityManagementClient newClient() { GameplaySessionAttestationService attestationService = mock(GameplaySessionAttestationService.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 97f047cb80..505124815d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -388,7 +388,7 @@ void playRejectsAmbiguousCharacterEvidenceBeforeBinding() { } @Test - void playRejectsCharacterRosterErrorBeforeBinding() { + void playRejectsNamespaceUnqualifiedRosterBeforeAdmissionOrBindingSideEffects() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -407,6 +407,10 @@ void playRejectsCharacterRosterErrorBeforeBinding() { assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + assertThat(((ErrorOutput) result.outputs().getFirst().payload()).code()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + Mockito.verify(moderationPolicyClient, Mockito.never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong()); verifyNoGameplayBindingSideEffects(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 70353dafaf..904b798fe8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -473,6 +473,39 @@ void browseCharactersReturnsStructuredCharacterList() { .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } + @Test + void browseCharactersFailsClosedWhenNamespaceQualifiedRosterAuthorityIsUnavailable() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("demo", 22L, 1L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + ListCharactersByAccountResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("CHARACTER_LIST_UNAVAILABLE") + .setMessage("Character list unavailable")) + .build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + @Test void browseCharactersUsesIsolatedStateRealmRoster() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); From 125378d02c301368f771964f0cb184aa699abea8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:11:45 +1300 Subject: [PATCH 040/105] Describe JOIN membership without claiming gameplay readiness --- .../command/text/HelpCommandHandler.java | 3 ++- .../text/WorldsTextCommandDispatchHandler.java | 2 +- .../resources/presentation-messages.properties | 2 +- .../resources/presentation-messages_fr.properties | 2 +- .../command/text/HelpCommandHandlerTest.java | 14 +++++++++++++- .../text/WorldsTextCommandDispatchHandlerTest.java | 9 +++++++-- 6 files changed, 25 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index 5311bf6cd2..cd07448647 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -88,7 +88,8 @@ public TextCommandInterpretationResult handle( success( "JOIN \n" + "Join the public-production membership for a world after LOGIN.\n" - + "Use REALMS first, then JOIN before CHARS and PLAY."); + + "Use REALMS first, then JOIN to confirm membership.\n" + + "Character browsing and gameplay entry are currently unavailable."); case "REALMS" -> success( "REALMS \n" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index ede8ed3609..fbfed45226 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -123,7 +123,7 @@ private TextCommandInterpretationResult handleJoinResponse( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.notice( - "Membership is ready. Continue with CHARS and PLAY.", + "Membership confirmed. Character browsing and gameplay entry are currently unavailable.", "notice.join.success", java.util.Map.of()))); } diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index ff488d4eb3..e6bb43eee7 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -34,7 +34,7 @@ error.join.entitlement-unavailable=Join policy could not be checked. Retry the s error.join.login-required=Log in before joining a world. error.join.invalid-request=JOIN requires a world selector after LOGIN. error.join.failed=The selected world could not be joined. -notice.join.success=Membership is ready. Continue with CHARS and PLAY. +notice.join.success=Membership confirmed. Character browsing and gameplay entry are currently unavailable. error.look.room-not-found=Room not found. error.look.world-unavailable=World data is temporarily unavailable. error.look.entity-unavailable=Nearby entity state is temporarily unavailable. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index e37962acac..b388a2570f 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -34,7 +34,7 @@ error.join.entitlement-unavailable=La politique d’adhésion n’a pas pu être error.join.login-required=Connectez-vous avant de rejoindre un monde. error.join.invalid-request=JOIN requiert un sélecteur de monde après LOGIN. error.join.failed=Le monde sélectionné n’a pas pu être rejoint. -notice.join.success=L’adhésion est prête. Continuez avec CHARS et PLAY. +notice.join.success=Adhésion confirmée. La consultation des personnages et l’accès au jeu sont actuellement indisponibles. error.look.room-not-found=Salle introuvable. error.look.world-unavailable=Les donnees du monde sont temporairement indisponibles. error.look.entity-unavailable=L’état des entités proches est temporairement indisponible. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 5fe1d19882..ccaa28bfe0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -70,7 +70,19 @@ void helpJoinExplainsTheExplicitPublicMembershipStep() { assertTrue(result.commandResult().accepted()); assertTrue(result.outputs().get(0).text().contains("JOIN ")); assertTrue(result.outputs().get(0).text().contains("public-production membership")); - assertTrue(result.outputs().get(0).text().contains("Use REALMS first")); + assertTrue( + result + .outputs() + .get(0) + .text() + .contains("Use REALMS first, then JOIN to confirm membership.")); + assertTrue( + result + .outputs() + .get(0) + .text() + .contains("Character browsing and gameplay entry are currently unavailable.")); + assertFalse(result.outputs().get(0).text().contains("CHARS and PLAY")); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index c330a86bb4..a0f814b6a8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -741,6 +741,11 @@ void joinDispatchOutputsRenderLocalizedGuidanceAndEnglishFallback( assertThat(error.message()).isEqualTo(expectedEnglish); } + assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "en")) + .isEqualTo( + success + ? "OK JOIN " + expectedEnglish + : "ERROR " + expectedCode + " " + expectedEnglish); assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "fr")) .isEqualTo(expectedFrench); assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "de")) @@ -816,8 +821,8 @@ private static Stream joinPresentationCases() { "", true, null, - "Membership is ready. Continue with CHARS and PLAY.", - "OK JOIN L’adhésion est prête. Continuez avec CHARS et PLAY.")); + "Membership confirmed. Character browsing and gameplay entry are currently unavailable.", + "OK JOIN Adhésion confirmée. La consultation des personnages et l’accès au jeu sont actuellement indisponibles.")); } private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, boolean success) { From 7438fa6b99b12a2242329a2fc1e5470dc2b71529 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 06:34:36 +1300 Subject: [PATCH 041/105] Contain non-public realm metadata until exact grant authority --- .../game-session-service/protocols.md | 2 + .../player-access-and-session.md | 2 +- .../realm-routing-and-playable-state.md | 2 +- .../command/text/WorldsCommandHandler.java | 270 ++---- .../text/WorldsCommandHandlerTest.java | 892 ++++++++---------- .../WorldsTextCommandDispatchHandlerTest.java | 132 ++- 6 files changed, 584 insertions(+), 716 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 5c776b932e..c385962f79 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -20,6 +20,8 @@ Target communication framing uses terminated sender `OK ` response fram Current production `CHARS` and `PLAY` roster access is contained at the shared Entity client because the live `ListCharactersByAccount` request and `Character` response do not establish the stable playable-state namespace. A positive `gameInstanceId` is only a replaceable runtime fence and cannot stand in for durable actor identity. The client preserves the existing `CHARACTER_LIST_UNAVAILABLE` failure without dispatching the legacy RPC; `CHARS` remains unavailable and `PLAY` retains its existing identity-unavailable outcome. Positive handler fixtures are offline-only evidence for mapping and error behavior, not runtime namespace proof. This containment follows [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity API contract](../entity-management-service/api-contracts.md); it does not alter separate `WORLDS` or `REALMS` discovery. +Current direct-text `REALMS` deliberately omits non-public entries because Account's runtime grant reader is slug-only and cannot prove the lifecycle-qualified target. Game Session skips those entries before membership, grant, entitlement, or scope dispatch and preserves public-production discovery and scope issuance. Guessed or unbound private character selectors retain the existing unknown-target projection; only a fresh caller-bound prior REALMS snapshot that resolves to the exact current private target reaches retryable `AUTH_UNAVAILABLE`, without Account or Entity dispatch. This containment does not change public `WORLDS`/`REALMS` or public character admission. The lifecycle-qualified grant contract remains owned by [Authentication](../../system-architecture-authentication.md#playtest-grant-admission-consequence). + ### Reset and Recovery Consequence The canonical [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model) policy applies to Game Session coordination state. Any target region- or tenant-scoped reset must carry exactly one explicit gameplay-session policy, `--preserve-sessions` or `--invalidate-sessions`; no preserve default is allowed. Cluster-scoped reset requires `--invalidate-sessions`, and `sessionctx:*` pre-auth transport context is always invalidated or rebuilt and never preserved. The current runtime has no supported scoped-reset protocol; current clients therefore follow the existing fail-closed pause/status and reconnect behavior rather than treating reset as implicit session preservation. 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 36ab84554e..7eb03f3a85 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,7 +32,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure. Game Session text JOIN dispatch is implemented locally under #2898; first-party Join & Play remains unavailable. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure. Game Session text JOIN dispatch is implemented locally under #2898; first-party Join & Play remains unavailable. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target gets retryable `AUTH_UNAVAILABLE`, while unbound private selectors keep the generic hidden projection. Text `PLAY` still requires admitting membership before its applicable Account-owned realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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`. | 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 3b2b8e5c1d..d3234d9141 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 @@ -20,7 +20,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The current pointer carries no `tenantSlug`, so the stable `tenantSlug/worldSlug` selector is not implemented; current bare world slugs are usable only when the catalog resolves them uniquely, while exact browse ordinals are snapshot-bound. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows; canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | -| `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | +| `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority now uses a row-locked expected `{pointerVersion, catalogRevision}` check, a conditional existing-row update, separate route/catalog revisions, and one pointer-plus-audit transaction. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Public pointer mutation/cutover RPCs remain fail-closed, so the full target cutover operation is not live. Explicit `CLOSED`, repository addressing by the canonical `{tenantId, realmId}` key and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index cbc28bad7d..3c5bc2b91f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -12,7 +12,6 @@ import java.util.Set; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; -import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; @@ -141,58 +140,48 @@ public RealmBrowseResult browseRealms( String requestId = sessionContext.sessionId() + ":" + UUID.randomUUID(); for (GameplayWorldCatalog.RealmView realm : worldCatalog.visibleRealms(world)) { if (!realm.publicProductionRealm()) { - NonPublicRealmAuthorization authorization = - authorizeNonPublicRealm(sessionContext, world, realm, requestId); - if (authorization == NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE) { - return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); - } - if (authorization == NonPublicRealmAuthorization.ENTITLEMENT_UNAVAILABLE) { - return RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE"); - } - if (authorization != NonPublicRealmAuthorization.AUTHORIZED) { - continue; - } + // The runtime grant reader is slug-only and cannot bind authority to this target's + // lifecycle. Do not disclose or scope non-public entries until that proof is available. + continue; } - if (realm.publicProductionRealm()) { - if (accountClient == null) { - return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); - } - DirectTextConnectScopeTarget target = connectScopeTarget(world, realm); - if (target == null) { - return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); - } - PlayerExecutionContext playerContext = playerContext(sessionContext, realm, requestId); - IssueDirectTextConnectScopeResponse scopeResponse = - accountClient.issueDirectTextConnectScope(playerContext, target); - if (scopeResponse.hasError()) { - String errorCode = scopeResponse.getError().getCode(); - if ("REALM_UNAVAILABLE".equals(errorCode)) { - return RealmBrowseResult.failure("REALM_UNAVAILABLE"); - } - return RealmBrowseResult.failure(errorCode.isBlank() ? "AUTH_UNAVAILABLE" : errorCode); - } - if (scopeResponse.getConnectScopeId().isBlank()) { - return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); - } - Instant expiresAt; - try { - expiresAt = Instant.parse(scopeResponse.getConnectScopeExpiresAt()); - } catch (DateTimeParseException ex) { - return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); - } - if (!expiresAt.isAfter(Instant.now())) { - return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + if (accountClient == null) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } + DirectTextConnectScopeTarget target = connectScopeTarget(world, realm); + if (target == null) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + PlayerExecutionContext playerContext = playerContext(sessionContext, realm, requestId); + IssueDirectTextConnectScopeResponse scopeResponse = + accountClient.issueDirectTextConnectScope(playerContext, target); + if (scopeResponse.hasError()) { + String errorCode = scopeResponse.getError().getCode(); + if ("REALM_UNAVAILABLE".equals(errorCode)) { + return RealmBrowseResult.failure("REALM_UNAVAILABLE"); } - issuedScopes.add( - new DirectTextConnectScopeSessionStore.ScopedRealm( - realm.slug(), true, scopeResponse.getConnectScopeId(), expiresAt, playerContext)); + return RealmBrowseResult.failure(errorCode.isBlank() ? "AUTH_UNAVAILABLE" : errorCode); + } + if (scopeResponse.getConnectScopeId().isBlank()) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } + Instant expiresAt; + try { + expiresAt = Instant.parse(scopeResponse.getConnectScopeExpiresAt()); + } catch (DateTimeParseException ex) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + if (!expiresAt.isAfter(Instant.now())) { + return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); + } + issuedScopes.add( + new DirectTextConnectScopeSessionStore.ScopedRealm( + realm.slug(), true, scopeResponse.getConnectScopeId(), expiresAt, playerContext)); visibleEntries.add(realmEntry(visibleEntries.size() + 1, realm)); responseRealms.add(realm); } - // A private-only world is retained for granted admission, but a denied selector must be - // indistinguishable from an unknown world and must not write lobby scope state. + // A world without a supported visible realm is indistinguishable from an unknown world and + // must not write lobby scope state. if (responseRealms.isEmpty() && !worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { return RealmBrowseResult.invalidSelector(); } @@ -403,6 +392,43 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( : new RealmSelectorResolution.RequiresSelection(); } + private boolean isBoundToCurrentRealmSnapshot( + SessionContext caller, + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog, + GameplayWorldCatalog.RealmView realm) { + if (connectScopeSessionStore == null) { + return false; + } + Optional maybeSnapshot; + try { + maybeSnapshot = + connectScopeSessionStore.realmsSnapshot( + caller, worldTenantId(world), world.slug(), Instant.now()); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return false; + } + if (maybeSnapshot.isEmpty()) { + return false; + } + DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); + if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) + || snapshot.tenantId() != worldTenantId(world) + || !snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + return false; + } + return snapshot.ordinalTargets().stream() + .filter(target -> target.tenantId() == realm.tenantId()) + .filter(target -> target.realmSlug().equalsIgnoreCase(realm.slug())) + .anyMatch( + target -> + worldCatalog + .resolveRealmSnapshotOrdinal(world, currentCatalog, target) + .filter(realm::equals) + .isPresent()); + } + private enum RealmSelectorStaleReason { UNBOUND_SELECTOR, SNAPSHOT_MISMATCH @@ -438,92 +464,6 @@ record Stale() implements WorldSelectorResolution {} record Unavailable() implements WorldSelectorResolution {} } - private NonPublicRealmAuthorization authorizeNonPublicRealm( - SessionContext sessionContext, - GameplayWorldCatalog.WorldView world, - GameplayWorldCatalog.RealmView realm, - String requestId) { - if (accountClient == null) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - GetTenantMembershipForRuntimeResponse membershipResponse = - accountClient.getTenantMembershipForRuntime( - Long.toString(sessionContext.accountId()), Long.toString(realm.tenantId()), requestId); - if (membershipResponse == null) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - if (membershipResponse.hasError()) { - if (!StringUtils.hasText(membershipResponse.getError().getCode())) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - return isAuthorityUnavailable(membershipResponse.getError().getCode()) - ? NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE - : NonPublicRealmAuthorization.DENIED; - } - if (!isValidMembershipAuthoritySnapshot(membershipResponse, sessionContext, realm)) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - if (!membershipResponse.getMembershipExists() - || "INACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { - return NonPublicRealmAuthorization.ENROLLMENT_REQUIRED; - } - if (!membershipResponse.getGameplayAdmissionAllowed()) { - return NonPublicRealmAuthorization.MEMBERSHIP_DENIED; - } - if (!isValidActiveMembership(membershipResponse, sessionContext, realm)) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - - GetRealmAccessGrantForRuntimeResponse grantResponse = - accountClient.getRealmAccessGrantForRuntime( - Long.toString(sessionContext.accountId()), - Long.toString(realm.tenantId()), - world.slug(), - realm.slug(), - requestId); - if (grantResponse == null) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - if (grantResponse.hasError()) { - if (!StringUtils.hasText(grantResponse.getError().getCode())) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - return isAuthorityUnavailable(grantResponse.getError().getCode()) - ? NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE - : NonPublicRealmAuthorization.DENIED; - } - if (!grantResponse.getGranted()) { - return NonPublicRealmAuthorization.DENIED; - } - if (!isValidGrant(grantResponse, sessionContext, world, realm)) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - - GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime(Long.toString(realm.tenantId()), requestId); - if (entitlementResponse == null) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - if (entitlementResponse.hasError()) { - String errorCode = entitlementResponse.getError().getCode(); - if (!StringUtils.hasText(errorCode)) { - return NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE; - } - if (GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE.equalsIgnoreCase(errorCode)) { - return NonPublicRealmAuthorization.ENTITLEMENT_UNAVAILABLE; - } - return isAuthorityUnavailable(errorCode) - ? NonPublicRealmAuthorization.AUTHORITY_UNAVAILABLE - : NonPublicRealmAuthorization.DENIED; - } - if (!isValidEntitlement(entitlementResponse, realm)) { - return NonPublicRealmAuthorization.ENTITLEMENT_UNAVAILABLE; - } - return entitlementResponse.getGameplayAvailable() - ? NonPublicRealmAuthorization.AUTHORIZED - : NonPublicRealmAuthorization.DENIED; - } - private boolean isValidEntitlement( GetTenantEntitlementsForRuntimeResponse response, GameplayWorldCatalog.RealmView realm) { return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) @@ -568,22 +508,6 @@ && hasMatchingAuthorityIdentity( && isFreshAuthorityEvaluation(response.getEvaluatedAt()); } - private boolean isValidGrant( - GetRealmAccessGrantForRuntimeResponse response, - SessionContext sessionContext, - GameplayWorldCatalog.WorldView world, - GameplayWorldCatalog.RealmView realm) { - return response.getGrantVersion() > 0L - && hasMatchingAuthorityIdentity( - response.getAccountId(), - response.getTenantId(), - sessionContext.accountId(), - realm.tenantId()) - && world.slug().equals(response.getWorldSlug()) - && realm.slug().equals(response.getRealmSlug()) - && isFreshAuthorityEvaluation(response.getEvaluatedAt()); - } - private boolean hasMatchingAuthorityIdentity( String accountId, String tenantId, long expectedAccountId, long expectedTenantId) { try { @@ -599,15 +523,6 @@ private boolean isAuthorityUnavailable(String code) { || "UNAVAILABLE".equalsIgnoreCase(code); } - private enum NonPublicRealmAuthorization { - AUTHORIZED, - DENIED, - MEMBERSHIP_DENIED, - ENROLLMENT_REQUIRED, - AUTHORITY_UNAVAILABLE, - ENTITLEMENT_UNAVAILABLE - } - public JoinMembershipResult joinPublicProductionMembership( SessionContext sessionContext, String worldSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); @@ -882,6 +797,15 @@ public CharacterBrowseResult browseCharacters( GameplayWorldCatalog.RealmView realm = ((RealmSelectorResolution.Selected) realmSelection).realm(); + if (!realm.publicProductionRealm() + && !isBoundToCurrentRealmSnapshot(sessionContext, world, currentRealmCatalog, realm)) { + // An unbound private slug must project exactly like an unknown realm. A fresh caller-bound + // snapshot may establish that the caller already knows this target, but it is not grant + // authority for the target. + return worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) + ? CharacterBrowseResult.invalidRealm(world.slug()) + : CharacterBrowseResult.invalidWorld(); + } boolean currentPointerMatches; try { currentPointerMatches = worldCatalog.matchesCurrentAdmissionPointer(world, realm); @@ -894,18 +818,14 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } + if (!realm.publicProductionRealm()) { + return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } + String requestId = sessionContext.sessionId() + ":" + UUID.randomUUID(); CharacterBrowseAuthorization authorization = - realm.publicProductionRealm() - ? authorizePublicCharacterBrowse(sessionContext, realm, requestId) - : mapNonPublicCharacterAuthorization( - authorizeNonPublicRealm(sessionContext, world, realm, requestId)); + authorizePublicCharacterBrowse(sessionContext, realm, requestId); if (authorization != CharacterBrowseAuthorization.AUTHORIZED) { - if (!realm.publicProductionRealm() && authorization.isDefinitiveAccessDenial()) { - return worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) - ? CharacterBrowseResult.invalidRealm(world.slug()) - : CharacterBrowseResult.invalidWorld(); - } return CharacterBrowseResult.failure(authorization.code()); } @@ -1030,17 +950,6 @@ private PublicEntitlementAuthorization authorizePublicCharacterEntitlement( CharacterBrowseAuthorization.AUTHORIZED, entitlementResponse.getAllowPublicJoin()); } - private CharacterBrowseAuthorization mapNonPublicCharacterAuthorization( - NonPublicRealmAuthorization authorization) { - return switch (authorization) { - case AUTHORIZED -> CharacterBrowseAuthorization.AUTHORIZED; - case DENIED, MEMBERSHIP_DENIED -> CharacterBrowseAuthorization.DENIED; - case ENROLLMENT_REQUIRED -> CharacterBrowseAuthorization.NON_PUBLIC_ENROLLMENT_REQUIRED; - case AUTHORITY_UNAVAILABLE -> CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - case ENTITLEMENT_UNAVAILABLE -> CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE; - }; - } - private boolean isValidMembershipAuthoritySnapshot( GetTenantMembershipForRuntimeResponse response, SessionContext sessionContext, @@ -1087,7 +996,6 @@ private enum CharacterBrowseAuthorization { JOIN_REQUIRED("JOIN_REQUIRED"), DENIED("WORLD_ACCESS_DENIED"), PUBLIC_PRODUCTION_ADMISSION_DENIED("PUBLIC_PRODUCTION_ADMISSION_DENIED"), - NON_PUBLIC_ENROLLMENT_REQUIRED("NON_PUBLIC_ENROLLMENT_REQUIRED"), TENANT_BILLING_BLOCKED("TENANT_BILLING_BLOCKED"), AUTH_UNAVAILABLE("AUTH_UNAVAILABLE"), ENTITLEMENT_UNAVAILABLE("ENTITLEMENT_UNAVAILABLE"); @@ -1101,12 +1009,6 @@ private enum CharacterBrowseAuthorization { private String code() { return code; } - - private boolean isDefinitiveAccessDenial() { - return this == DENIED - || this == PUBLIC_PRODUCTION_ADMISSION_DENIED - || this == NON_PUBLIC_ENROLLMENT_REQUIRED; - } } private record PublicEntitlementAuthorization( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 904b798fe8..4c7d470bd1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -356,15 +357,6 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() AtomicReference> worlds = new AtomicReference<>(List.of(original)); AccountClient accountClient = Mockito.mock(AccountClient.class); - stubActivePrivateAuthorization(accountClient, "demo"); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("preview"), - Mockito.anyString())) - .thenReturn(grant("demo", "preview", true)); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() @@ -381,7 +373,10 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) .isInstanceOfSatisfying( WorldsCommandHandler.RealmBrowseResult.Success.class, - success -> assertThat(success.output().realms()).hasSize(2)); + success -> + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production")); Mockito.clearInvocations(accountClient, entityManagementClient); worlds.set( List.of( @@ -423,16 +418,27 @@ void browseCharactersReturnsStructuredCharacterList() { .getFirst() .getRealms() .getFirst() - .setPublicProductionRealm(false); + .setPublicProductionRealm(true); gameplayCatalogProperties .getWorlds() .get(1) .getRealms() .getFirst() .setPublicProductionRealm(false); - addPublicProductionAuthority(gameplayCatalogProperties); AccountClient accountClient = Mockito.mock(AccountClient.class); - stubActivePrivateAuthorization(accountClient, "demo"); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("public-scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); Mockito.when( entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -530,45 +536,33 @@ void browseCharactersUsesIsolatedStateRealmRoster() { gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); addPublicProductionAuthority(gameplayCatalogProperties); AccountClient accountClient = Mockito.mock(AccountClient.class); - stubActivePrivateAuthorization(accountClient, "demo"); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("8001") - .setTenantId("22") - .setAccountId("123") - .setName("Forkline") - .setLevel(5) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) - .build()) - .build()); - WorldsCommandHandler localHandler = - authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); - assertThat(localHandler.browseRealms(session, "demo")) - .isInstanceOfSatisfying( - WorldsCommandHandler.RealmBrowseResult.Success.class, - success -> assertThat(success.output().realms()).hasSize(1)); + GameplayWorldCatalog catalog = + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); + GameplayWorldCatalog.WorldView selectedWorld = catalog.resolveWorld("demo").orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + catalog.readRealmDiscoverySnapshot(selectedWorld); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + scopeStore.replaceRealmSnapshot( + session, + "demo", + 22L, + "demo", + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + List.of(), + Instant.now()); + WorldsCommandHandler localHandler = + new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore); WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(session, "demo", null); + localHandler.browseCharacters(session, "demo", "production"); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.stateScope()).isEqualTo("ISOLATED"); - assertThat(output.characterCreationPolicy()).isEqualTo("COPIED_ONLY"); - assertThat(output.characters()) - .extracting(CharacterBrowseViewOutput.CharacterEntry::characterName) - .containsExactly("Forkline"); - Mockito.verify(entityManagementClient) - .listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); + assertThat(result) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -803,74 +797,95 @@ void browseCharactersReturnsUnavailableEntitlementBeforeReadingPublicEntityRoste } @Test - void browseCharactersDeniesRevokedPrivateMembershipBeforeReadingEntityRoster() { + void privateOnlyCharacterSelectionMatchesUnknownWithoutLegacyAuthorizationReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); addPublicProductionAuthority(properties); AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - activeMembership().toBuilder() - .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("INACTIVE") - .build()); + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant(true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void browseRealmsOmitsActivePrivateMembershipWithoutAdmissionWhileCharactersDeny() { + void legacyAuthorityVariantsNeverExposePrivateOnlyRealm() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); addPublicProductionAuthority(properties); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(true, false, 1L, 1L, "ACTIVE")); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + List memberships = + List.of( + activeMembership(), + publicMembership(false, false, 0L, 0L, "MISSING"), + publicMembership(true, false, 1L, 1L, "INACTIVE"), + activeMembership().toBuilder().setEvaluatedAt("not-an-instant").build(), + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE")) + .build()); + List grants = + List.of( + grant("preview", "production", true), + grant("preview", "production", false), + grant("preview", "production", true).toBuilder() + .setEvaluatedAt(Instant.now().minusSeconds(60).toString()) + .build(), + GetRealmAccessGrantForRuntimeResponse.getDefaultInstance(), + grant("preview", "other", true)); + List entitlements = + List.of( + publicEntitlement(false), + publicEntitlement(false).toBuilder().setGameplayAvailable(false).build(), + publicEntitlement(false).toBuilder().setTenantId("23").build(), + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("ENTITLEMENT_UNAVAILABLE")) + .build(), + GetTenantEntitlementsForRuntimeResponse.getDefaultInstance()); - assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); - assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + for (int index = 0; index < memberships.size(); index++) { + AccountClient accountClient = Mockito.mock(AccountClient.class); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(memberships.get(index)); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grants.get(index)); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime( + Mockito.anyString(), Mockito.anyString())) + .thenReturn(entitlements.get(index)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } } @Test void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - publicMembership(false, false, 0L, 0L, "MISSING"), - publicMembership(true, false, 1L, 1L, "INACTIVE"), - activeMembership()); Mockito.when( accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -878,7 +893,7 @@ void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { Mockito.eq("demo"), Mockito.eq("playtest"), Mockito.anyString())) - .thenReturn(grant("demo", "playtest", false)); + .thenReturn(grant("demo", "playtest", true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult unknownRealm = @@ -888,22 +903,7 @@ void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) .isEqualTo(unknownRealm); - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) - .isEqualTo(unknownRealm); - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) - .isEqualTo(unknownRealm); - - Mockito.verify(accountClient, Mockito.times(3)) - .getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(accountClient, Mockito.times(1)) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString()); - Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -913,25 +913,13 @@ void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoste properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); addPublicProductionAuthority(properties); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(false)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -940,10 +928,30 @@ void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); AccountClient accountClient = Mockito.mock(AccountClient.class); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + SessionContext session = authenticatedSession(); + GameplayWorldCatalog catalog = TestGameplayWorldCatalogs.fromProperties(properties); + GameplayWorldCatalog.WorldView selectedWorld = catalog.resolveWorld("preview").orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + catalog.readRealmDiscoverySnapshot(selectedWorld); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + WorldsCommandHandler localHandler = + new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore); + + assertThat(localHandler.browseCharacters(session, "preview", "unknown")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + scopeStore.replaceRealmSnapshot( + session, + "preview", + 22L, + "preview", + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + List.of(), + Instant.now()); WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "preview", "production"); + localHandler.browseCharacters(session, "preview", "production"); assertThat(result) .isEqualTo( @@ -1126,52 +1134,73 @@ void browseCharactersRejectsInvalidPublicMembershipBeforeReadingRoster() { } @Test - void browseRealmsAndCharactersRejectInvalidPrivateMembership() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); + void freshBoundSnapshotKeepsPrivateSelectionRetryableWithoutLegacyAuthority() { + GameplayWorldCatalog.WorldView world = + mixedWorld(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + GameplayWorldCatalog catalog = snapshotCatalog(world); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + catalog.realmDiscoverySnapshot(world, catalog.visibleRealms(world)); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + scopeStore.replaceRealmSnapshot( + authenticatedSession(), + "demo", + 22L, + "demo", + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + List.of(), + Instant.now()); AccountClient accountClient = Mockito.mock(AccountClient.class); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - for (String evaluatedAt : invalidEvaluationTimes()) { - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership().toBuilder().setEvaluatedAt(evaluatedAt).build()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant("demo", "preview", true)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore); - assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); - assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); - } - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "preview")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void browseRealmsAndCharactersRejectInvalidPrivateGrant() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - for (String evaluatedAt : invalidEvaluationTimes()) { + void staleOrExpiredPrivateSnapshotCannotBindCurrentSameSlugTarget() { + UUID productionRealmId = UUID.randomUUID(); + UUID productionNamespaceId = UUID.randomUUID(); + GameplayWorldCatalog.WorldView previousWorld = + mixedWorld(UUID.randomUUID(), UUID.randomUUID(), productionRealmId, productionNamespaceId); + GameplayWorldCatalog previousCatalog = snapshotCatalog(previousWorld); + GameplayWorldCatalog.RealmDiscoverySnapshot previousSnapshot = + previousCatalog.realmDiscoverySnapshot( + previousWorld, previousCatalog.visibleRealms(previousWorld)); + + for (boolean expireSnapshot : List.of(false, true)) { + GameplayWorldCatalog.WorldView currentWorld = + expireSnapshot + ? previousWorld + : mixedWorld( + UUID.randomUUID(), UUID.randomUUID(), productionRealmId, productionNamespaceId); + AtomicReference> currentWorlds = + new AtomicReference<>(List.of(currentWorld)); + GameplayWorldCatalog changingCatalog = + GameplayWorldCatalog.forWorldSupplier(currentWorlds::get); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + scopeStore.replaceRealmSnapshot( + authenticatedSession(), + "demo", + 22L, + "demo", + previousSnapshot.catalogFingerprint(), + previousSnapshot.ordinalTargets(), + List.of(), + expireSnapshot ? Instant.now().minus(Duration.ofDays(2)) : Instant.now()); + AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1179,16 +1208,64 @@ void browseRealmsAndCharactersRejectInvalidPrivateGrant() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(grant(true).toBuilder().setEvaluatedAt(evaluatedAt).build()); - - assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); - assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + .thenReturn(grant("demo", "preview", true)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + changingCatalog, entityManagementClient, accountClient, scopeStore); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "preview")) + .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.InvalidRealm("demo")); + if (expireSnapshot) { + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + } else { + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("public-scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production")); + assertThat( + scopeStore + .realmsSnapshot(authenticatedSession(), 22L, "demo", Instant.now()) + .orElseThrow() + .ordinalTargets()) + .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) + .containsExactly("production"); + assertThat( + scopeStore.publicProductionScope( + authenticatedSession(), 22L, "demo", Instant.now())) + .hasValueSatisfying( + scopedRealm -> + assertThat(scopedRealm.playerContext().getRealmId()) + .isEqualTo(currentWorld.realms().getFirst().realmId().toString())); + org.mockito.ArgumentCaptor issuedContexts = + org.mockito.ArgumentCaptor.forClass(PlayerExecutionContext.class); + Mockito.verify(accountClient) + .issueDirectTextConnectScope(issuedContexts.capture(), Mockito.any()); + assertThat(issuedContexts.getValue().getRealmId()) + .isEqualTo(currentWorld.realms().getFirst().realmId().toString()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + } } - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); } @Test @@ -1258,21 +1335,12 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { AccountClient accountClient = Mockito.mock(AccountClient.class); DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership(), publicMembership(false, false, 0L, 0L, "MISSING")); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("private-only"), - Mockito.eq("preview"), - Mockito.anyString())) - .thenReturn(grant("private-only", "preview", true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("public-scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(properties), @@ -1280,29 +1348,34 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { accountClient, scopeStore); - assertThat(localHandler.browseRealms(authenticatedSession(), "private-only")) + assertThat(localHandler.browseRealms(authenticatedSession(), "public")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - Optional grantedSnapshot = - scopeStore.realmsSnapshot(authenticatedSession(), 22L, "private-only", Instant.now()); - assertThat(grantedSnapshot).isPresent(); + Optional publicSnapshot = + scopeStore.realmsSnapshot(authenticatedSession(), 22L, "public", Instant.now()); + assertThat(publicSnapshot).isPresent(); assertThat(localHandler.browseRealms(authenticatedSession(), "private-only")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); assertThat(localHandler.browseRealms(authenticatedSession(), "unknown")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); - assertThat( - scopeStore.realmsSnapshot(authenticatedSession(), 22L, "private-only", Instant.now())) - .hasValue(grantedSnapshot.orElseThrow()); + assertThat(scopeStore.realmsSnapshot(authenticatedSession(), 22L, "public", Instant.now())) + .hasValue(publicSnapshot.orElseThrow()); + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(accountClient, Mockito.times(1)) + .issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); } @Test - void privateOnlyCharacterSelectorMatchesUnknownWhenDeniedAndRemainsReachableWhenGranted() { + void privateOnlyCharacterSelectorMatchesUnknownDespitePositiveLegacyGrantFixture() { GameplayCatalogProperties properties = privateOnlyWorldProperties(); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING"), activeMembership()); Mockito.when( accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1311,23 +1384,13 @@ void privateOnlyCharacterSelectorMatchesUnknownWhenDeniedAndRemainsReachableWhen Mockito.eq("preview"), Mockito.anyString())) .thenReturn(grant("private-only", "preview", true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "preview")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); assertThat(localHandler.browseCharacters(authenticatedSession(), "unknown", "preview")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "preview")) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -1404,42 +1467,11 @@ void omittedCharactersIgnoreHiddenPrivateRealmCardinalityForPublicDefault() { } @Test - void omittedCharactersRequireChoiceAmongCallerVisibleRealmsAndKeepOrdinalBinding() { + void omittedCharactersInPrivateOnlyWorldRemainIndistinguishableFromUnknown() { GameplayCatalogProperties properties = privateOnlyWorldProperties(); - GameplayCatalogProperties.World privateWorld = properties.getWorlds().get(1); - GameplayCatalogProperties.Realm staff = - world("private-only", 22L, 3L, false).getRealms().getFirst(); - staff.setSlug("staff"); - staff.setDisplayName("Staff Realm"); - staff.setPublicProductionRealm(false); - privateWorld.setRealms(List.of(privateWorld.getRealms().getFirst(), staff)); - AccountClient accountClient = Mockito.mock(AccountClient.class); DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("private-only"), - Mockito.anyString(), - Mockito.anyString())) - .thenAnswer( - invocation -> grant("private-only", invocation.getArgument(3, String.class), true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - Mockito.eq("22"), - Mockito.eq("123"), - Mockito.anyString(), - Mockito.eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED))) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(properties), @@ -1450,26 +1482,14 @@ void omittedCharactersRequireChoiceAmongCallerVisibleRealmsAndKeepOrdinalBinding assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); assertThat(localHandler.browseRealms(authenticatedSession(), "PRIVATE-ONLY")) - .isInstanceOfSatisfying( - WorldsCommandHandler.RealmBrowseResult.Success.class, - success -> assertThat(success.output().realms()).hasSize(2)); - assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) - .isEqualTo( - WorldsCommandHandler.CharacterBrowseResult.realmSelectionRequired("private-only")); - - WorldsCommandHandler.CharacterBrowseResult ordinalSelection = - localHandler.browseCharacters(authenticatedSession(), "PRIVATE-ONLY", "1"); - - assertThat(ordinalSelection) - .isInstanceOfSatisfying( - WorldsCommandHandler.CharacterBrowseResult.Success.class, - success -> assertThat(success.output().realmSlug()).isEqualTo("preview")); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void omittedCharactersRequireExplicitRealmWhenPublicAndPrivateChoicesWereDiscovered() { + void mixedRealmDiscoveryAndOmittedCharacterSelectionKeepOnlyPublicProductionTarget() { AccountClient accountClient = Mockito.mock(AccountClient.class); DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); @@ -1477,14 +1497,6 @@ void omittedCharactersRequireExplicitRealmWhenPublicAndPrivateChoicesWereDiscove accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString())) - .thenReturn(grant("demo", "playtest", true)); Mockito.when( accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(false)); @@ -1504,191 +1516,41 @@ void omittedCharactersRequireExplicitRealmWhenPublicAndPrivateChoicesWereDiscove assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOfSatisfying( WorldsCommandHandler.RealmBrowseResult.Success.class, - success -> assertThat(success.output().realms()).hasSize(2)); + success -> + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production")); Mockito.clearInvocations(accountClient, entityManagementClient); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", null)) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.realmSelectionRequired("demo")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); - } - - @Test - void authenticatedBrowseOmitsPrivateRealmWithoutExactGrant() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(false)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.RealmBrowseResult result = - localHandler.browseRealms(authenticatedSession(), "preview"); - - assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); - } - - @Test - void authenticatedBrowseFailsClosedWhenMembershipAuthorityUnavailable() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); - AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("AUTH_UNAVAILABLE") - .build()) - .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.RealmBrowseResult result = - localHandler.browseRealms(authenticatedSession(), "preview"); - - assertThat(result) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); - } - - @Test - void authenticatedBrowseIncludesPrivateRealmForActiveMemberWithExactGrant() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.RealmBrowseResult result = - localHandler.browseRealms(authenticatedSession(), "preview"); - - assertThat(result).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - assertThat(((WorldsCommandHandler.RealmBrowseResult.Success) result).output().realms()) - .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) - .containsExactly("production"); - } - - @Test - void authenticatedBrowseRejectsPrivateRealmWhenEntitlementTenantDoesNotMatch() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("23") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.RealmBrowseResult result = - localHandler.browseRealms(authenticatedSession(), "preview"); + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); - assertThat(result) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", null)) + .isInstanceOfSatisfying( + WorldsCommandHandler.CharacterBrowseResult.Success.class, + success -> assertThat(success.output().realmSlug()).isEqualTo("production")); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); } @Test - void authenticatedBrowseOmitsPrivateRealmWhenGameplayEntitlementIsUnavailable() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); + void authenticatedBrowseOmitsPrivateRealmDespitePositiveLegacyGrant() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(false) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.RealmBrowseResult result = - localHandler.browseRealms(authenticatedSession(), "preview"); - - assertThat(result).isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); - Mockito.verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); - } - - @Test - void authenticatedBrowseFailsClosedWhenGameplayEntitlementIsUnavailable() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("preview", 22L, 2L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); - addPublicProductionAuthority(properties); - AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1700,30 +1562,39 @@ void authenticatedBrowseFailsClosedWhenGameplayEntitlementIsUnavailable() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(grant(true)); + .thenReturn(grant("demo", "playtest", true)); Mockito.when( accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("ENTITLEMENT_UNAVAILABLE") - .setMessage("Entitlement authority unavailable") - .build()) - .build()); + .thenReturn(publicEntitlement(false)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.RealmBrowseResult result = - localHandler.browseRealms(authenticatedSession(), "preview"); + localHandler.browseRealms(authenticatedSession(), "demo"); assertThat(result) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); - Mockito.verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production")); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); } @Test - void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembership() { + void authenticatedBrowseKeepsPublicScopeAndOrdinalWhileOmittingPrivateMetadata() { UUID realmId = UUID.randomUUID(); UUID namespaceId = UUID.randomUUID(); GameplayWorldCatalog.RealmView realm = @@ -1741,6 +1612,21 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh 1L, realmId, namespaceId); + GameplayWorldCatalog.RealmView privateRealm = + new GameplayWorldCatalog.RealmView( + "playtest", + "Private Playtest", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()); AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( @@ -1748,13 +1634,17 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh .setConnectScopeId("scope-1") .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( - List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo", List.of(realm, privateRealm)))), entityManagementClient, accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + scopeStore); WorldsCommandHandler.RealmBrowseResult result = localHandler.browseRealms(authenticatedSession(), "demo"); @@ -1764,9 +1654,28 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) .containsExactly("production"); Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Optional snapshot = + scopeStore.realmsSnapshot(authenticatedSession(), 22L, "demo", Instant.now()); + assertThat(snapshot).isPresent(); + assertThat(snapshot.orElseThrow().ordinalTargets()) + .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) + .containsExactly("production"); + assertThat(scopeStore.publicProductionScope(authenticatedSession(), 22L, "demo", Instant.now())) + .hasValueSatisfying( + scopedRealm -> + assertThat(scopedRealm.playerContext().getRealmId()).isEqualTo(realmId.toString())); Mockito.verify(accountClient, Mockito.never()) .getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); } @Test @@ -2175,6 +2084,48 @@ private GameplayAdmissionPointerSnapshot admissionPointer(long gameInstanceId) { ADMISSION_NAMESPACE_ID); } + private GameplayWorldCatalog.WorldView mixedWorld( + UUID privateRealmId, + UUID privateNamespaceId, + UUID productionRealmId, + UUID productionNamespaceId) { + GameplayWorldCatalog.RealmView production = + new GameplayWorldCatalog.RealmView( + "production", + "Production", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + productionRealmId, + productionNamespaceId); + GameplayWorldCatalog.RealmView preview = + new GameplayWorldCatalog.RealmView( + "preview", + "Private Preview", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW", + 1L, + privateRealmId, + privateNamespaceId); + return new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(production, preview)); + } + + private GameplayWorldCatalog snapshotCatalog(GameplayWorldCatalog.WorldView world) { + return GameplayWorldCatalog.forWorldViews(List.of(world)); + } + private GameplayWorldCatalog.WorldView worldView( String worldSlug, String displayName, long tenantId, long gameInstanceId) { GameplayWorldCatalog.RealmView realm = @@ -2309,31 +2260,6 @@ private GameplayCatalogProperties privateOnlyWorldProperties() { return properties; } - private void stubActivePrivateAuthorization(AccountClient accountClient, String worldSlug) { - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq(worldSlug), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(worldSlug, true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - } - private List invalidEvaluationTimes() { return List.of( Instant.now().minusSeconds(16).toString(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index a0f814b6a8..2271c98774 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -81,59 +81,104 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { @Test void publishesCommandEventForGameplayScopedRealmsBrowse() { - gameplayCatalogProperties.setWorlds( - List.of(world("sandbox", 1L, 2L, false), world("authority", 1L, 1L, false))); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setPublicProductionRealm(false); - gameplayCatalogProperties - .getWorlds() - .get(1) - .getRealms() - .getFirst() - .setPublicProductionRealm(true); + gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 22L, 2L, false))); AccountClient accountClient = Mockito.mock(AccountClient.class); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("41") - .setTenantId("1") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setMembershipLifecycleState("ACTIVE") - .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt(Instant.now().toString()) + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-sandbox") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); - when(accountClient.getRealmAccessGrantForRuntime( + GameplayWorldCatalog catalog = + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); + GameplayWorldCatalog.WorldView sandbox = catalog.resolveWorld("sandbox").orElseThrow(); + GameplayWorldCatalog.RealmView currentRealm = catalog.visibleRealms(sandbox).getFirst(); + DirectTextConnectScopeTarget expectedTarget = + new DirectTextConnectScopeTarget( + Long.toString(currentRealm.tenantId()), + sandbox.slug(), + currentRealm.slug(), + currentRealm.realmId().toString(), + currentRealm.playableStateNamespaceId().toString(), + currentRealm.stateScope(), + Long.toString(currentRealm.gameInstanceId()), + currentRealm.catalogRevision(), + currentRealm.pointerVersion()); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + catalog, + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); + SessionContext context = + new SessionContext( + 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + + TextCommandInterpretationResult result = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.REALMS, List.of("sandbox"), "REALMS sandbox"), + false, + Optional.of(context))); + + assertThat(result.commandResult().accepted()).isTrue(); + assertThat(result.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isInstanceOf(RealmBrowseViewOutput.class); + org.mockito.ArgumentCaptor targetCaptor = + org.mockito.ArgumentCaptor.forClass(DirectTextConnectScopeTarget.class); + Mockito.verify(accountClient) + .issueDirectTextConnectScope(Mockito.any(), targetCaptor.capture()); + assertThat(targetCaptor.getValue()).isEqualTo(expectedTarget); + Mockito.verify(accountClient, Mockito.never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verify(scriptEventPublisher) + .publishCommandEvent( + Mockito.eq(context), + Mockito.argThat( + gameplayCommand -> + "REALMS".equals(gameplayCommand.getCommandName()) + && "REALMS sandbox".equals(gameplayCommand.getCommandText()))); + } + + @Test + void privateRealmsBrowseDoesNotPublishDespitePositiveLegacyGrant() { + GameplayCatalogProperties.World sandbox = world("sandbox", 22L, 2L, false); + sandbox.getRealms().getFirst().setPublicProductionRealm(false); + GameplayCatalogProperties.World authority = world("authority", 22L, 1L, false); + gameplayCatalogProperties.setWorlds(List.of(sandbox, authority)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), + Mockito.eq("sandbox"), + Mockito.eq("production"), Mockito.anyString())) .thenReturn( GetRealmAccessGrantForRuntimeResponse.newBuilder() .setAccountId("41") - .setTenantId("1") + .setTenantId("22") .setWorldSlug("sandbox") .setRealmSlug("production") .setGranted(true) .setGrantVersion(1L) .setEvaluatedAt(Instant.now().toString()) .build()); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("1") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( @@ -154,18 +199,11 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { false, Optional.of(context))); - assertThat(result.commandResult().accepted()).isTrue(); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(result.outputs()) - .singleElement() - .extracting(output -> output.payload()) - .isInstanceOf(RealmBrowseViewOutput.class); - Mockito.verify(scriptEventPublisher) - .publishCommandEvent( - Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "REALMS".equals(gameplayCommand.getCommandName()) - && "REALMS sandbox".equals(gameplayCommand.getCommandText()))); + .noneMatch(output -> output.payload() instanceof RealmBrowseViewOutput); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); } @Test From 46450c3db9d1022f22da2b7e6866c260169169a3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 06:39:29 +1300 Subject: [PATCH 042/105] Reconcile direct-text discovery with scoped pointer authority --- .../command/text/GameplayWorldCatalog.java | 179 +++++++++++++----- .../command/text/WorldsCommandHandler.java | 10 + .../command/text/PlayCommandHandlerTest.java | 20 +- .../text/SessionResumptionFlowTest.java | 2 +- .../text/TextCommandInterpreterTest.java | 2 +- .../text/WorldsCommandHandlerTest.java | 11 +- .../impl/GameSessionGrpcServiceTest.java | 6 +- .../support/TestGameplayWorldCatalogs.java | 2 +- 8 files changed, 162 insertions(+), 70 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 33c7c70aa0..17e89920fd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -156,7 +156,18 @@ public Optional browseRealms(String worldSelector) { return Optional.empty(); } return resolveWorld(worldSelector) - .map(world -> new RealmBrowseViewOutput(world.slug(), realmEntries(world))); + .filter(world -> visibleRealms(world).stream().anyMatch(RealmView::publicProductionRealm)) + .map( + world -> + new RealmBrowseViewOutput( + world.slug(), + realmEntries( + new WorldView( + world.slug(), + world.displayName(), + visibleRealms(world).stream() + .filter(RealmView::publicProductionRealm) + .toList())))); } /** Reads the current realm catalog and records the exact response-local ordinal targets. */ @@ -243,29 +254,40 @@ public Optional resolveWorldFromAuthoritySnapshot(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - if (authorityPointerSupplier == null) { - List worlds = visibleWorldsFromAuthoritySnapshot(); - CatalogState state = new CatalogState(worlds, publicProductionCounts(worlds)); - return resolveWorld(selector, worlds, worlds) - .filter(world -> hasValidPublicProductionRealm(world, state)); - } - List pointers = readAuthorityPointers(); - for (GameplayAdmissionPointerSnapshot pointer : pointers) { - if (!hasCompleteAuthorityPointer(pointer)) { - throw new AuthorityPointerUnavailableException( - "Authoritative gameplay pointer is incomplete"); + CatalogState state; + if (authorityPointerSupplier != null && !isOrdinalSelector(selector)) { + List pointers = loadAuthorityPointers(); + Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); + String selectedWorld = selectorKey(selector); + boolean selectedInvalidTenant = + pointers.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .filter(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))) + .anyMatch(pointer -> invalidTenantIds.contains(pointer.tenantId())); + if (!selectedInvalidTenant && !invalidTenantIds.isEmpty()) { + boolean selectorExists = + pointers.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .anyMatch(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))); + if (!selectorExists) { + requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); + } } + state = catalogStateFromPointers(healthyTenantPointers(pointers)); + } else if (authorityPointerSupplier != null) { + state = catalogStateFromPointers(healthyTenantPointers(loadAuthorityPointers())); + } else { + state = loadAuthorityWorldSnapshot(); } - requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); - CatalogState state = catalogStateFromPointers(pointers); - List worlds = state.worlds().stream().filter(this::hasVisibleRealmEntries).toList(); - return resolveWorld(selector, worlds, worlds) - .filter(world -> hasValidPublicProductionRealm(world, state)); + List worlds = visibleWorlds(state); + return resolveWorld(selector, worlds, discoverableWorlds(worlds, state)); } /** Builds the no-caller discovery projection from one validated authority snapshot. */ public List publicWorldsFromAuthoritySnapshot() { - return publicDiscoveryWorlds(loadAuthorityWorldSnapshot()); + return unambiguousTenantWorlds(publicDiscoveryWorlds(loadAuthorityWorldSnapshot())); } /** Resolves only worlds exposed by the no-caller public discovery surface. */ @@ -273,7 +295,26 @@ public Optional resolvePublicWorldFromAuthoritySnapshot(String select if (selector == null || selector.isBlank()) { return Optional.empty(); } - return resolveWorld(selector, publicWorldsFromAuthoritySnapshot()); + if (authorityPointerSupplier == null) { + return resolveWorld(selector, publicWorldsFromAuthoritySnapshot()); + } + List pointers = loadAuthorityPointers(); + if (!isOrdinalSelector(selector)) { + Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); + String selectedWorld = selectorKey(selector); + boolean selectedUnhealthyTenant = + pointers.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .filter(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))) + .anyMatch(pointer -> invalidTenantIds.contains(pointer.tenantId())); + if (selectedUnhealthyTenant) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm count is invalid for selected world"); + } + } + CatalogState snapshot = catalogStateFromPointers(healthyTenantPointers(pointers)); + return resolveWorld(selector, unambiguousTenantWorlds(publicDiscoveryWorlds(snapshot))); } private Optional resolveWorld( @@ -505,6 +546,10 @@ public PublicProductionRealmCardinality publicProductionRealmCardinality(long te if (tenantId <= 0L) { return PublicProductionRealmCardinality.ZERO; } + if (authorityPointerSupplier != null) { + return cardinality( + publicProductionCountsFromPointers(loadAuthorityPointers()).getOrDefault(tenantId, 0L)); + } return cardinality(readCatalogState().publicProductionCounts().getOrDefault(tenantId, 0L)); } @@ -637,7 +682,7 @@ public List visibleWorldsFromAuthoritySnapshot() { if (authorityPointerSupplier == null) { return visibleWorlds(); } - return visibleWorlds(loadAuthorityWorldSnapshot()); + return unambiguousTenantWorlds(visibleWorlds(loadAuthorityWorldSnapshot())); } /** @@ -789,9 +834,17 @@ private static void requireCollisionSafeVisiblePointer( } private List loadAuthorityPointersForTenant(long tenantId) { - List pointers = tenantAuthorityPointerSupplier.apply(tenantId); + List pointers; + try { + pointers = tenantAuthorityPointerSupplier.apply(tenantId); + } catch (AuthorityPointerReadUnavailableException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new AuthorityPointerReadUnavailableException( + "Authoritative tenant gameplay pointer list is unavailable", ex); + } if (pointers == null) { - throw new AuthorityPointerUnavailableException( + throw new AuthorityPointerReadUnavailableException( "Authoritative tenant gameplay pointer list is unavailable"); } for (GameplayAdmissionPointerSnapshot pointer : pointers) { @@ -873,14 +926,32 @@ private List publicDiscoveryWorlds(CatalogState snapshot) { .filter( realm -> cardinality( - snapshot.publicProductionCounts() - .getOrDefault(realm.tenantId(), 0L)) + snapshot + .publicProductionCounts() + .getOrDefault(realm.tenantId(), 0L)) == PublicProductionRealmCardinality.EXACTLY_ONE) .toList())) .filter(world -> world.realms().size() == 1) .toList(); } + private static List unambiguousTenantWorlds(List worlds) { + Map> tenantsBySelector = new HashMap<>(); + for (WorldView world : worlds) { + tenantsBySelector + .computeIfAbsent(selectorKey(world.slug()), ignored -> new HashSet<>()) + .add(worldTenantId(world)); + } + Set ambiguousSelectors = + tenantsBySelector.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + return worlds.stream() + .filter(world -> !ambiguousSelectors.contains(selectorKey(world.slug()))) + .toList(); + } + private static boolean isPlayerAddressable(RealmView realm) { return realm != null && realm.visible() @@ -898,7 +969,7 @@ private CatalogState readCatalogState() { List worlds = normalizeWorlds(worldSupplier.get()); return new CatalogState(worlds, publicProductionCounts(worlds)); } - return catalogStateFromPointers(readAuthorityPointers()); + return catalogStateFromPointers(healthyTenantPointers(readAuthorityPointers())); } private static CatalogState catalogStateFromPointers( @@ -988,22 +1059,22 @@ private static List normalizeWorlds(List worlds) { .filter(world -> world.slug() != null && !world.slug().isBlank()) .map(GameplayWorldCatalog::copyWorldView) .toList(); - Map worldCounts = new HashMap<>(); - Map> tenantsByWorld = new HashMap<>(); + Map worldCounts = new HashMap<>(); + Map> worldSpellings = new HashMap<>(); for (WorldView world : normalizedWorlds) { - String key = selectorKey(world.slug()); + WorldIdentity key = worldIdentity(world); worldCounts.merge(key, 1, Integer::sum); - Set tenantIds = tenantsByWorld.computeIfAbsent(key, ignored -> new HashSet<>()); - world.realms().stream().map(RealmView::tenantId).forEach(tenantIds::add); - } - Set ambiguousWorlds = new HashSet<>(); - for (Map.Entry entry : worldCounts.entrySet()) { - if (entry.getValue() > 1 || tenantsByWorld.get(entry.getKey()).size() > 1) { - ambiguousWorlds.add(entry.getKey()); - } - } + worldSpellings.computeIfAbsent(key, ignored -> new HashSet<>()).add(world.slug()); + } + Set ambiguousWorlds = new HashSet<>(); + worldCounts.forEach( + (key, count) -> { + if (count > 1 || worldSpellings.get(key).size() > 1 || key.tenantId() <= 0L) { + ambiguousWorlds.add(key); + } + }); return normalizedWorlds.stream() - .filter(world -> !ambiguousWorlds.contains(selectorKey(world.slug()))) + .filter(world -> !ambiguousWorlds.contains(worldIdentity(world))) .toList(); } @@ -1018,38 +1089,36 @@ private record CatalogState(List worlds, Map publicProduc } private static List toWorlds(List pointers) { - Map> tenantsByWorldSlug = new HashMap<>(); + Map> worldSpellings = new HashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { if (hasCompleteAuthorityPointer(pointer)) { - tenantsByWorldSlug - .computeIfAbsent( - selectorKey(pointer.worldSlug()), ignored -> new HashSet<>()) - .add(pointer.tenantId()); + WorldIdentity identity = worldIdentity(pointer); + worldSpellings + .computeIfAbsent(identity, ignored -> new HashSet<>()) + .add(pointer.worldSlug()); } } - Set ambiguousWorldSlugs = - tenantsByWorldSlug.entrySet().stream() + Set ambiguousWorldSlugs = + worldSpellings.entrySet().stream() .filter(entry -> entry.getValue().size() > 1) .map(Map.Entry::getKey) - .collect(Collectors.toUnmodifiableSet()); + .collect(Collectors.toSet()); Map worlds = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { if (!hasCompleteAuthorityPointer(pointer) - || ambiguousWorldSlugs.contains(selectorKey(pointer.worldSlug()))) { + || ambiguousWorldSlugs.contains(worldIdentity(pointer))) { continue; } MutableWorldAccumulator world = worlds.computeIfAbsent( - new WorldIdentity( - pointer.tenantId(), pointer.worldSlug().trim().toLowerCase(Locale.ROOT)), + worldIdentity(pointer), ignored -> new MutableWorldAccumulator(pointer.worldSlug(), pointer.worldDisplayName())); world.tenantIds.add(pointer.tenantId()); world .realmsBySlug - .computeIfAbsent( - selectorKey(pointer.realmSlug()), ignored -> new ArrayList<>()) + .computeIfAbsent(selectorKey(pointer.realmSlug()), ignored -> new ArrayList<>()) .add(pointer); } return normalizeWorlds( @@ -1067,11 +1136,19 @@ private static List toWorlds(List p .toList()); } + private static WorldIdentity worldIdentity(GameplayAdmissionPointerSnapshot pointer) { + return new WorldIdentity(pointer.tenantId(), selectorKey(pointer.worldSlug())); + } + private static long worldTenantId(WorldView world) { List tenantIds = world.realms().stream().map(RealmView::tenantId).distinct().toList(); return tenantIds.size() == 1 ? tenantIds.getFirst() : -1L; } + private static WorldIdentity worldIdentity(WorldView world) { + return new WorldIdentity(worldTenantId(world), selectorKey(world.slug())); + } + private static Set tenantsWithoutExactlyOneVisiblePublicProductionRealm( List pointers) { Set tenantIds = new java.util.HashSet<>(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index cbc28bad7d..75f38e290b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -122,6 +122,16 @@ public RealmBrowseResult browseRealms( WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); if (selection instanceof WorldSelectorResolution.Invalid) { + try { + // A tenant with invalid public-production cardinality is intentionally omitted from the + // discovery snapshot. Recheck the no-caller public projection to distinguish that + // fail-closed state from an ordinary unknown selector before returning INVALID_SELECTOR. + worldCatalog.resolvePublicWorldFromAuthoritySnapshot(worldSelector); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } return RealmBrowseResult.invalidSelector(); } if (selection instanceof WorldSelectorResolution.Stale) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 6c3293d76f..4c950236d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -774,10 +774,13 @@ void playRejectsPointerRevisionCutoverBeforeAdmissionReads() { GameplayAdmissionPointerSnapshot pointerA = admissionPointer(1L); GameplayAdmissionPointerSnapshot pointerB = admissionPointer(2L); AtomicInteger pointerReads = new AtomicInteger(); - when(authorityService.listPointers()) + when(authorityService.listPointers()).thenReturn(List.of(pointerA)); + when(authorityService.listPointersByTenant(22L)) .thenAnswer( - invocation -> - pointerReads.getAndIncrement() == 0 ? List.of(pointerA) : List.of(pointerB)); + invocation -> { + pointerReads.incrementAndGet(); + return List.of(pointerB); + }); GameplayWorldCatalog authorityBackedCatalog = new GameplayWorldCatalog(authorityService); PlayCommandHandler authorityBackedHandler = new PlayCommandHandler( @@ -804,7 +807,7 @@ void playRejectsPointerRevisionCutoverBeforeAdmissionReads() { TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); - assertThat(pointerReads).hasValue(2); + assertThat(pointerReads).hasValue(1); Mockito.verifyNoInteractions( accountClient, entityManagementClient, @@ -821,12 +824,11 @@ void playMapsFinalPointerReadOutageToAuthUnavailableWithoutAdmissionSideEffects( GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); AtomicInteger pointerReads = new AtomicInteger(); - when(authorityService.listPointers()) + when(authorityService.listPointers()).thenReturn(List.of(admissionPointer(1L))); + when(authorityService.listPointersByTenant(22L)) .thenAnswer( invocation -> { - if (pointerReads.getAndIncrement() == 0) { - return List.of(admissionPointer(1L)); - } + pointerReads.incrementAndGet(); if ("throw".equals(failureMode)) { throw new IllegalStateException("authority down on final read"); } @@ -862,7 +864,7 @@ void playMapsFinalPointerReadOutageToAuthUnavailableWithoutAdmissionSideEffects( .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE); assertThat(((ErrorOutput) result.outputs().getFirst().payload()).messageKey()) .isEqualTo("error.play.authority-unavailable"); - assertThat(pointerReads).hasValue(2); + assertThat(pointerReads).hasValue(1); Mockito.verifyNoInteractions( accountClient, entityManagementClient, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 02c2a98b41..a426cebb22 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -10,8 +10,8 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.time.Instant; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 560d7f1278..fc03667f16 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -12,8 +12,8 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.time.Instant; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 908f28a9c5..5a07e766cd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -989,10 +989,13 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads GameplayAdmissionPointerSnapshot pointerA = admissionPointer(1L); GameplayAdmissionPointerSnapshot pointerB = admissionPointer(2L); AtomicInteger pointerReads = new AtomicInteger(); - Mockito.when(authorityService.listPointers()) + Mockito.when(authorityService.listPointers()).thenReturn(List.of(pointerA)); + Mockito.when(authorityService.listPointersByTenant(22L)) .thenAnswer( - invocation -> - pointerReads.getAndIncrement() == 0 ? List.of(pointerA) : List.of(pointerB)); + invocation -> { + pointerReads.incrementAndGet(); + return List.of(pointerB); + }); WorldsCommandHandler localHandler = new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), @@ -1006,7 +1009,7 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads assertThat(result) .isEqualTo( WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); - assertThat(pointerReads).hasValue(2); + assertThat(pointerReads).hasValue(1); Mockito.verifyNoInteractions(entityManagementClient); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 9441eda08b..7050d596dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -691,7 +691,7 @@ void gameplayDiscoverySuppressesTenantWithPublicRealmsAcrossDifferentWorlds() { assertFalse(worlds.hasError()); assertEquals(0, worlds.getWorldsCount()); - assertEquals("INVALID_ARGUMENT", realms.getError().getCode()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realms.getError().getCode()); assertEquals(0, realms.getRealmsCount()); Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); } @@ -1097,7 +1097,7 @@ public void onError(Throwable t) { public void onCompleted() {} }); - assertEquals("INVALID_ARGUMENT", realmsRef.get().getError().getCode()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realmsRef.get().getError().getCode()); assertEquals(0, realmsRef.get().getRealmsCount()); AtomicReference pointerRef = new AtomicReference<>(); @@ -1249,7 +1249,7 @@ public void onError(Throwable t) { public void onCompleted() {} }); - assertEquals("INVALID_ARGUMENT", response.get().getError().getCode()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); assertEquals(0, response.get().getRealmsCount()); AtomicReference pointerResponse = new AtomicReference<>(); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index b4b9c55ce8..60f7c66661 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -9,8 +9,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.UUID; import java.util.Set; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; From 34401da03ba1d41f319b2aedf1aa3af6ccc6cbc5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 08:22:29 +1300 Subject: [PATCH 043/105] fix(gameplay): keep scoped snapshots valid and unify strict authority freshness --- .../account-service/runtime-and-data.md | 2 +- .../tcp-proxy-service/protocols.md | 6 +- .../system-architecture-frontend.md | 6 +- .../system-architecture-protocol-bridging.md | 2 +- .../player-access-and-session.md | 4 +- .../text/AuthorityEvaluationFreshness.java | 28 +++++++ .../command/text/PlayCommandHandler.java | 21 +---- .../command/text/WorldsCommandHandler.java | 20 +---- .../DirectTextConnectScopeSessionStore.java | 10 +-- .../AuthorityEvaluationFreshnessTest.java | 37 +++++++++ .../text/GameplayWorldCatalogTest.java | 59 ++++++++++++++ .../text/TextCommandInterpreterTest.java | 2 +- ...irectTextConnectScopeSessionStoreTest.java | 79 +++++++++++++++---- .../support/TestGameplayWorldCatalogs.java | 9 +-- 14 files changed, 213 insertions(+), 72 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshness.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshnessTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index eca0c30e52..4468084325 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -184,7 +184,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation, but current runtime callers do not enforce either field. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation. Older Account issuance and character-discovery consumers still omit checks for those fields; text `PLAY` validates lifecycle state and authority generation against the fresh response. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index fbf7fca997..6f9507708b 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -8,11 +8,11 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof, and the target independent issuance baseline/generation/version reread remains unproved. Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for public-production missing or non-admitting membership it evaluates fresh entitlement/public policy before `JOIN_REQUIRED`, and for private/playtest targets it performs the applicable current realm-grant check. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. +The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof, and the target independent issuance baseline/generation/version reread remains unproved. Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for eligible public-production targets, only missing or `INACTIVE` membership can reach `JOIN_REQUIRED`, after fresh entitlement/public policy permits joining. Existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` remains denied. Private/playtest targets perform the applicable current realm-grant check. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` always performs fresh membership and applicable private/playtest grant checks, regardless of any connect-token replay-cache state. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). The Telnet credential form is `LOGIN [secret]`. `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. -The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but the target independent issuance baseline/reread and private/playtest grant check remain implementation and proof gaps. For an eligible public-production target with missing or non-admitting membership, text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or policy denial wins. These local gaps do not change the Authentication-owned admission outcomes. -The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients have a local `LOGIN` -> `PLAY` -> `LOOK` path for existing admitting members; when `PLAY` returns `JOIN_REQUIRED`, the client can issue `JOIN` and retry `PLAY` before `LOOK`. Focused local JOIN proof exists, while full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Missing or existing non-admitting eligible public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement/public policy permits joining, and direct text can invoke the Account-backed writer. Missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. +The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but the target independent issuance baseline/reread and private/playtest grant check remain implementation and proof gaps. For an eligible public-production target with missing or `INACTIVE` membership, text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or policy denial wins. An existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` is denied. These local gaps do not change the Authentication-owned admission outcomes. +The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients have a local `LOGIN` -> `PLAY` -> `LOOK` path for existing admitting members; when `PLAY` returns `JOIN_REQUIRED`, the client can issue `JOIN` and retry `PLAY` before `LOOK`. Focused local JOIN proof exists, while full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Missing or `INACTIVE` eligible public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement/public policy permits joining; existing `ACTIVE` membership with gameplay admission disabled remains denied. Direct text can invoke the Account-backed writer. Missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. ## Cross-Path Connectivity Contract diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index eea3577924..1785ee6c8f 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -20,9 +20,9 @@ The first-party browser consumes the existing Account/Gateway APIs and the versi The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output, but the independently released static host, public-site routing and delivery (including the target `/auth/**` rewrite), health/security/cache behavior, rollback, and bounded end-to-end browser proof are not implemented or proved. Those gaps remain target implementation obligations rather than evidence that the supported frontend boundary is live. -Direct-text `JOIN` is implemented locally through the Account-owned `JoinPublicProductionMembership` writer; first-party `Join & Play` remains target-only and the complete browser/Telnet flow is not proved. In the target, the writer creates missing membership or restores `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current Account membership response exposes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. Current text `PLAY` validates the fresh lifecycle/version/generation evidence; for an otherwise eligible public-production missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`, while entitlement outage or public policy denial wins. Current connect-token issuance receives the lifecycle/version/generation fields on its fresh path, but replay-cache hits can bypass fresh reads and the target independent issuance baseline/generation reread remains a proof gap. Direct-text JOIN has focused local coverage, while complete Telnet discovery/bridge, PostgreSQL/recovery, and first-party `Join & Play` proof remain open. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership/grant/entitlement/routing checks pass; current connect-token private/playtest grant validation remains incomplete. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. +Direct-text `JOIN` is implemented locally through the Account-owned `JoinPublicProductionMembership` writer; first-party `Join & Play` remains target-only and the complete browser/Telnet flow is not proved. In the target, the writer creates missing membership or restores `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current Account membership response exposes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. Current text `PLAY` validates the fresh lifecycle/version/generation evidence; for an otherwise eligible public-production target, only missing or `INACTIVE` membership can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks pass. An existing `ACTIVE` membership with gameplay admission disabled remains denied. Current connect-token issuance receives the lifecycle/version/generation fields on its fresh path, but replay-cache hits can bypass fresh reads and the target independent issuance baseline/generation reread remains a proof gap. Direct-text JOIN has focused local coverage, while complete Telnet discovery/bridge, PostgreSQL/recovery, and first-party `Join & Play` proof remain open. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership/grant/entitlement/routing checks pass; current connect-token private/playtest grant validation remains incomplete. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. -The direct-text `JOIN` action is implemented, but first-party `Join & Play` and the independent issuance-time membership baseline/generation reread remain unimplemented or unproved. The frontend must keep the complete first-party browser join flow unavailable until that route, its post-join snapshot, and its token-issuance proof are complete; direct-text clients may use the implemented join writer. Current text `PLAY` and the fresh connect-token path receive lifecycle, version, generation, and evaluation-time fields; existing-member admission requires `ACTIVE`, while an eligible public-production missing or non-admitting response reaches `JOIN_REQUIRED` only after fresh entitlement permits public joining. Returning members and private/playtest callers remain eligible only when the other current membership, grant, entitlement, and routing checks pass. Complete Telnet/browser end-to-end, PostgreSQL/recovery, replay-cache revalidation, and issuance-baseline proof remain open. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). +The direct-text `JOIN` action is implemented, but first-party `Join & Play` and the independent issuance-time membership baseline/generation reread remain unimplemented or unproved. The frontend must keep the complete first-party browser join flow unavailable until that route, its post-join snapshot, and its token-issuance proof are complete; direct-text clients may use the implemented join writer. Current text `PLAY` and the fresh connect-token path receive lifecycle, version, generation, and evaluation-time fields; existing-member admission requires `ACTIVE`, while only eligible public-production missing or `INACTIVE` membership reaches `JOIN_REQUIRED` after fresh entitlement permits public joining. An existing `ACTIVE` member with gameplay admission disabled remains denied. Returning members and private/playtest callers remain eligible only when the other current membership, grant, entitlement, and routing checks pass. Complete Telnet/browser end-to-end, PostgreSQL/recovery, replay-cache revalidation, and issuance-baseline proof remain open. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). ### Persisted actor entry UX boundary (PLAYER-01) @@ -98,7 +98,7 @@ Frontend flows are split between **player gameplay sessions** and **admin/creato - Target first-party clients use one of two explicit gameplay flows: - **Returning member:** `POST /auth/player-bootstrap` -> bootstrap discovery -> bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with the discovery-provided `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This flow requires the selected existing caller-bound membership and does not call `/auth/bootstrap/join`. - **First join:** `POST /auth/player-bootstrap` -> public-production discovery -> `POST /auth/bootstrap/join` -> rerun public-production realm discovery -> use the new complete `{connectScopeId, tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` snapshot for bootstrap-authenticated character discovery/creation -> `POST /auth/connect-token` with that new snapshot's `connectScopeId` -> `/ws/game/**` -> bare `LOGIN` -> `PLAY`. This public-production, non-grant snapshot intentionally omits both `playtestLifecycleId` and `playtestStateGeneration`; private/playtest snapshots include both fields. `/auth/bootstrap/join` may create missing membership or restore `INACTIVE` membership and must commit it against the exact `{catalogRevision, pointerVersion}` pair before the post-join discovery, character discovery, character creation, or connect-token issuance; no later step may create membership implicitly. The join transition emits one audit/outbox event for create or restore; an `ACTIVE` retry is event-free. - - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not confirmed complete current supported behavior. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` and fresh connect-token issuance receive `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; text `PLAY` requires fresh lifecycle/version/generation evidence and, for eligible public-production missing or non-admitting membership, fresh entitlement with `allowPublicJoin=true` before `JOIN_REQUIRED`. Current returning-member behavior may proceed when the existing live membership/character checks pass, but the target exact issuance baseline/generation/version reread and durable replay revalidation remain unproved. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Returning members and private/playtest callers with existing membership plus the current grant remain eligible only when their current runtime checks pass. Complete first-party browser, Telnet, PostgreSQL/recovery, and downstream proof remain open. The target descriptions remain the behavior to implement. + - The first-join, returning-player, reconnect, resume, grant-backed private/playtest, and related gameplay-admission descriptions in this section are target-state contracts, not confirmed complete current supported behavior. Direct-text `JOIN` is implemented through the Account-owned writer, while first-party `Join & Play` remains unavailable. Current text `PLAY` and fresh connect-token issuance receive `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; text `PLAY` requires fresh lifecycle/version/generation evidence and, for eligible public-production missing or `INACTIVE` membership, fresh entitlement with `allowPublicJoin=true` before `JOIN_REQUIRED`. Existing `ACTIVE` membership with gameplay admission disabled remains denied. Current returning-member behavior may proceed when the existing live membership/character checks pass, but the target exact issuance baseline/generation/version reread and durable replay revalidation remain unproved. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`; the separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. Returning members and private/playtest callers with existing membership plus the current grant remain eligible only when their current runtime checks pass. Complete first-party browser, Telnet, PostgreSQL/recovery, and downstream proof remain open. The target descriptions remain the behavior to implement. - For every `POST /auth/connect-token` issuance, including the first issuance immediately after explicit join and both returning-member and grant-backed private/playtest flows, the service must independently validate the scalar `membershipVersion` returned by `GetTenantMembershipForRuntime` for the selected `{accountId, tenantId}` and the `membershipAuthorityGeneration` from that same authoritative membership snapshot. It must compare both values independently with the selected admission baseline, bind the scalar `membershipVersion` and generation into the connect-token issuance/binding evidence, and fail closed when either value is missing, stale, mismatched, unavailable, or assembled from another snapshot; a current grant never substitutes for the membership-version validation. - Browser and mobile-browser clients receive the short-lived `Firemud-Connect-Token` HttpOnly cookie used by the `/ws/game/**` handshake; first-party native-mobile clients using a cookie jar remain cookie-only. This protected-cookie path is the current supported path to bare `LOGIN`. Explicitly classified non-first-party/public non-browser clients are target-only and unavailable until their dedicated issuance route is fully registered and proven; the conditional target carrier is protected secure storage plus `X-Firemud-Connect-Token`, not a fallback for the current cookie path. The client then opens `/ws/game/**` and completes gameplay authentication by issuing `LOGIN` over the WebSocket channel using the already-verified bootstrap/connect context; Game Session must validate the complete context, including the direct `realmId`, before using any field for `LOGIN`, `PLAY`, or scope comparison. The browser never prompts for or replays Telnet-style `LOGIN [secret]` credentials, as described in [Authentication & Authorization](./system-architecture-authentication.md#login-and-session-flow). - Browser transport constraints matter: a browser WebSocket cannot set arbitrary custom handshake headers the way Telnet smart clients, Mudlet integrations, or server-side clients can. The first-party browser flow therefore uses the `Firemud-Connect-Token` cookie set by `POST /auth/connect-token` with `HttpOnly`, `Secure`, `SameSite=Strict`, `Path=/ws/game`, and `Max-Age` no longer than the connect-token TTL. The React client must not read or persist the connect token itself; it only consumes non-secret response metadata such as `expiresAt`, `tenantId`, `realmId`, `realmSlug`, and `gameInstanceId`. Query parameters must never carry connect tokens or other authentication credentials; non-secret bootstrap discovery selectors such as `connectScopeId` may be sent as query parameters. Clients must obtain a fresh token after any failed attempt that may have consumed it. After Account has durably committed an issuance result or Gateway has consumed its token, any new token issuance requires a new `requestId`; the old `requestId` may only reconcile that same request while its outcome is `PENDING` or otherwise indeterminate and never mints a replacement token. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 7a0bac0995..8a9d243f50 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence remains unproved end to end: current focused smoke proof is still limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path, with focused local JOIN coverage but no complete Telnet discovery/bridge, PostgreSQL/recovery, or first-party `Join & Play` proof. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unavailable as a distinct browser action. The Account membership response now exposes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. Current text `PLAY` validates the fresh identity, lifecycle, version, authority-generation, and evaluation-time evidence; for an otherwise eligible public-production target whose membership is missing or non-admitting, it obtains fresh tenant entitlement and requires `allowPublicJoin=true` before returning `JOIN_REQUIRED`, while entitlement outage or public policy denial takes precedence. Current private/playtest text `PLAY` uses `WORLD_ACCESS_DENIED` for missing or non-admitting membership and also checks the current realm grant. Current connect-token issuance has the same Account fields available on its fresh path, but a replay/result-cache hit can bypass fresh entitlement, membership, and pointer reads, and the target's independent issuance-time generation/version baseline reread and durable replay revalidation remain gaps. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; its private/playtest grant check also remains incomplete. A connect token or returning shortcut must not be treated as authorization proof. Target fresh admission still requires applicable entitlement, exact routing, and the target lifecycle/generation/version snapshot; the bounded last-known-good exception remains limited to unchanged public-production binding continuity during an entitlement-only outage after the other resume predicates pass. These implementation and proof gaps do not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. +Current implementation capability and proof status for player access, admission, and reconnect flows is tracked in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#current-status). The target protocol flow, carriage, ordering, admission, authentication, reconnect, and delivery requirements below remain normative. --- 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 7eb03f3a85..7a11fad0cd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -105,9 +105,9 @@ The lifecycle classes are deliberately distinct: - Unexpected disconnect may mark the session suspended/reconnect-eligible, preserve bounded replay state, and allow later `PLAY` to request recovery. - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. -- Target deliberate `LOGOUT` is termination, not suspension. Once its durable episode fence exists, it deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Current `LOGOUT_UNAVAILABLE` performs none of those terminal mutations; logout before login is a bounded in-band failure. +- Current deliberate `LOGOUT` returns `LOGOUT_UNAVAILABLE` without terminal mutations; logout before login is a bounded in-band failure. The target lifecycle and teardown contract is owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript). -Replay projection is separate from retained transcript storage. Current Game Session suppresses private retained-context reads on reconnect and renders fresh `LOOK` after accepted `PLAY`; unexpected transport loss remains reconnect-eligible for fresh authority checks, not private replay. Deliberate `LOGOUT` currently fails closed with `LOGOUT_UNAVAILABLE` and does not clear an active binding because durable terminal `resumeContextGeneration` evidence is absent. Target successful logout terminates that episode before acknowledgement; retaining transcript rows never makes them replay-eligible. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Current private replay suppression does not read retained output from partial shells. +Current Game Session suppresses private retained-context reads on reconnect and after attempted `LOGOUT`, and renders fresh `LOOK` after accepted `PLAY`; unexpected transport loss remains reconnect-eligible for fresh authority checks. `LOGOUT_UNAVAILABLE` does not clear an active binding because durable terminal `resumeContextGeneration` evidence is absent. Strict-fence enforcement and live recovery proof remain incomplete. The canonical logout and resume-context contracts are owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript), [Reconnection](../../architecture/system-architecture-reconnection.md#canonical-durable-resume-context-policy), [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md), and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Partial gameplay shells are not authoritative: current private replay suppression does not read retained output from them. ### Reconnect and Continuity diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshness.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshness.java new file mode 100644 index 0000000000..e25af38114 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshness.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.command.text; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.Objects; + +/** Shared freshness policy for Account authority evaluations used by text commands. */ +public final class AuthorityEvaluationFreshness { + private static final Duration MAX_AGE = Duration.ofSeconds(15); + + private AuthorityEvaluationFreshness() {} + + public static boolean isFresh(String evaluatedAt, Clock clock) { + Objects.requireNonNull(clock, "clock must not be null"); + if (evaluatedAt == null || evaluatedAt.isBlank()) { + return false; + } + try { + Instant evaluated = Instant.parse(evaluatedAt); + Instant now = clock.instant(); + return !evaluated.isAfter(now) && !evaluated.isBefore(now.minus(MAX_AGE)); + } catch (DateTimeParseException ex) { + return false; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 4ea0800612..2d79450635 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -3,8 +3,8 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Clock; import java.time.Instant; -import java.time.format.DateTimeParseException; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -1117,7 +1117,7 @@ private boolean isSafeMembershipAuthorityResponse( response.getTenantId(), context.accountId(), selectedRealm.tenantId()) - || !isFreshAuthorityEvaluation(response.getEvaluatedAt())) { + || !AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC())) { return false; } if (!response.getMembershipExists()) { @@ -1147,7 +1147,7 @@ && hasMatchingAuthorityIdentity( response.getAccountId(), response.getTenantId(), context.accountId(), realm.tenantId()) && world.slug().equals(response.getWorldSlug()) && realm.slug().equals(response.getRealmSlug()) - && isFreshAuthorityEvaluation(response.getEvaluatedAt()); + && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); } private boolean isValidEntitlement( @@ -1155,20 +1155,7 @@ private boolean isValidEntitlement( return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) && response.getEntitlementVersion() > 0L && response.getTenantBillingSequence() > 0L - && isFreshAuthorityEvaluation(response.getEvaluatedAt()); - } - - private boolean isFreshAuthorityEvaluation(String evaluatedAt) { - if (!StringUtils.hasText(evaluatedAt)) { - return false; - } - try { - Instant evaluated = Instant.parse(evaluatedAt); - Instant now = Instant.now(); - return !evaluated.isAfter(now) && !evaluated.isBefore(now.minusSeconds(15)); - } catch (DateTimeParseException ex) { - return false; - } + && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); } private boolean hasMatchingAuthorityIdentity( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index c764bcc422..a7ae0d9ada 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.command.text; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.ArrayList; @@ -479,20 +480,7 @@ private boolean isValidEntitlement( return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) && response.getEntitlementVersion() > 0L && response.getTenantBillingSequence() > 0L - && isFreshAuthorityEvaluation(response.getEvaluatedAt()); - } - - private boolean isFreshAuthorityEvaluation(String evaluatedAt) { - if (!StringUtils.hasText(evaluatedAt)) { - return false; - } - try { - Instant evaluated = Instant.parse(evaluatedAt); - Instant now = Instant.now(); - return !evaluated.isAfter(now) && !evaluated.isBefore(now.minusSeconds(15)); - } catch (DateTimeParseException ex) { - return false; - } + && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); } private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { @@ -515,7 +503,7 @@ && hasMatchingAuthorityIdentity( response.getTenantId(), sessionContext.accountId(), realm.tenantId()) - && isFreshAuthorityEvaluation(response.getEvaluatedAt()); + && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); } private boolean hasMatchingAuthorityIdentity( @@ -969,7 +957,7 @@ private boolean isValidMembershipAuthoritySnapshot( response.getTenantId(), sessionContext.accountId(), realm.tenantId()) - || !isFreshAuthorityEvaluation(response.getEvaluatedAt())) { + || !AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC())) { return false; } if (!response.getMembershipExists()) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index b9a7b0fc57..88d3dcf0bc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -158,11 +158,6 @@ public void replaceWorldScopes( .filter(scope -> scope.expiresAt().toEpochMilli() > nowMillis) .map(scope -> storeScope(scope, nowMillis)) .toList(); - long expiresAt = - storedScopes.stream() - .mapToLong(StoredScopedRealm::expiresAtEpochMs) - .max() - .orElse(now.plus(WORLDS_SNAPSHOT_TTL).toEpochMilli()); String key = worldIdentityKey(tenantId, worldSlug); mutate( caller.sessionId(), @@ -175,10 +170,7 @@ public void replaceWorldScopes( byWorld.put(key, storedScopes); } Map realmsByWorld = new HashMap<>(record.realmsByWorld()); - realmsByWorld.put( - key, - new StoredRealmsSnapshot( - tenantId, worldSlug, requestedSelector, "", expiresAt, List.of())); + realmsByWorld.remove(key); return new LobbyRecord( caller.sessionId(), caller.accountId(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshnessTest.java new file mode 100644 index 0000000000..5580ecc165 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthorityEvaluationFreshnessTest.java @@ -0,0 +1,37 @@ +package unit.net.firedevops.firemud.gamesession.command.text; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import net.firedevops.firemud.gamesession.command.text.AuthorityEvaluationFreshness; +import org.junit.jupiter.api.Test; + +class AuthorityEvaluationFreshnessTest { + private static final Instant NOW = Instant.parse("2026-10-03T12:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + + @Test + void acceptsCurrentAndExactlyFifteenSecondOldEvaluations() { + assertThat(AuthorityEvaluationFreshness.isFresh(NOW.toString(), CLOCK)).isTrue(); + assertThat(AuthorityEvaluationFreshness.isFresh(NOW.minusSeconds(15).toString(), CLOCK)) + .isTrue(); + } + + @Test + void rejectsOlderAndFutureEvaluations() { + assertThat( + AuthorityEvaluationFreshness.isFresh( + NOW.minusSeconds(15).minusNanos(1).toString(), CLOCK)) + .isFalse(); + assertThat(AuthorityEvaluationFreshness.isFresh(NOW.plusNanos(1).toString(), CLOCK)).isFalse(); + } + + @Test + void rejectsMissingBlankAndMalformedEvaluations() { + assertThat(AuthorityEvaluationFreshness.isFresh(null, CLOCK)).isFalse(); + assertThat(AuthorityEvaluationFreshness.isFresh(" ", CLOCK)).isFalse(); + assertThat(AuthorityEvaluationFreshness.isFresh("not-an-instant", CLOCK)).isFalse(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index c137ec589b..c815ffdffd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -12,10 +12,12 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; +import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -1008,6 +1010,63 @@ private static GameplayWorldCatalog.WorldView worldWithTargetRealm( "ALLOW_NEW"))); } + @Test + void propertyCatalogRealmIdsIncludeWorldAndRemainDeterministic() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds( + List.of( + propertyWorld("world-one", 7L, 11L, true), propertyWorld("world-two", 7L, 12L, false))); + + GameplayWorldCatalog catalog = TestGameplayWorldCatalogs.fromProperties(properties); + GameplayWorldCatalog.RealmView firstRealm = + catalog + .resolveRealm(catalog.resolveWorld("world-one").orElseThrow(), "shared") + .orElseThrow(); + GameplayWorldCatalog.RealmView secondRealm = + catalog + .resolveRealm(catalog.resolveWorld("world-two").orElseThrow(), "shared") + .orElseThrow(); + GameplayWorldCatalog repeatedCatalog = TestGameplayWorldCatalogs.fromProperties(properties); + GameplayWorldCatalog.RealmView repeatedFirstRealm = + repeatedCatalog + .resolveRealm(repeatedCatalog.resolveWorld("world-one").orElseThrow(), "shared") + .orElseThrow(); + GameplayCatalogProperties otherTenantProperties = new GameplayCatalogProperties(); + otherTenantProperties.setWorlds(List.of(propertyWorld("world-one", 8L, 11L, true))); + GameplayWorldCatalog tenantCatalog = + TestGameplayWorldCatalogs.fromProperties(otherTenantProperties); + GameplayWorldCatalog.RealmView otherTenantRealm = + tenantCatalog + .resolveRealm(tenantCatalog.resolveWorld("world-one").orElseThrow(), "shared") + .orElseThrow(); + + assertThat(firstRealm.realmId()).isNotEqualTo(secondRealm.realmId()); + assertThat(otherTenantRealm.realmId()).isNotEqualTo(firstRealm.realmId()); + assertThat(repeatedFirstRealm.realmId()).isEqualTo(firstRealm.realmId()); + assertThat(repeatedFirstRealm.playableStateNamespaceId()) + .isEqualTo(firstRealm.playableStateNamespaceId()); + } + + private static GameplayCatalogProperties.World propertyWorld( + String worldSlug, long tenantId, long gameInstanceId, boolean publicProductionRealm) { + GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); + realm.setSlug("shared"); + realm.setDisplayName("Shared Realm"); + realm.setTenantId(tenantId); + realm.setGameInstanceId(gameInstanceId); + realm.setPointerVersion(1L); + realm.setVisible(true); + realm.setPublicProductionRealm(publicProductionRealm); + realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); + realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); + + GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); + world.setSlug(worldSlug); + world.setDisplayName(worldSlug); + world.setRealms(List.of(realm)); + return world; + } + private static GameplayWorldCatalog.WorldView worldWithRealm( String worldSlug, String realmSlug, long tenantId, boolean publicProduction) { return new GameplayWorldCatalog.WorldView( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index fc03667f16..59a266fb3e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -538,7 +538,7 @@ void worldsAreVisibleBeforeLogin() { } @Test - void privateRealmsAreNotDisclosedWithoutAuthority() { + void realmsBrowseFailsClosedWhenScopeAuthorityIsUnavailable() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); TextCommandInterpretationResult interpretation = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 04a35ffb96..1069e27344 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -85,12 +85,15 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { SessionContext caller = session(7L, 41L); Instant now = Instant.now(); Instant expiry = now.plusSeconds(3600); - store.replaceWorldScopes( + store.replaceRealmSnapshot( caller, "demo-world", 22L, "demo-world", - List.of(scopedRealm(caller, "production", "scope-first", expiry))); + "realms-catalog", + List.of(), + List.of(scopedRealm(caller, "production", "scope-first", expiry)), + now); DirectTextConnectScopeSessionStore.JoinScope firstAttempt = store @@ -106,12 +109,15 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { .isEqualTo(retryAttempt.scope().connectScopeId()); store.clearWorldScopes(caller, 22L, "demo-world"); - store.replaceWorldScopes( + store.replaceRealmSnapshot( caller, "demo-world", 22L, "demo-world", - List.of(scopedRealm(caller, "production", "scope-second", expiry))); + "realms-catalog", + List.of(), + List.of(scopedRealm(caller, "production", "scope-second", expiry)), + now); DirectTextConnectScopeSessionStore.JoinScope newAttempt = store .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) @@ -125,12 +131,15 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { void clearingTransportLobbyRemovesScopeAndBoundJoinIdentityBeforeReuse() { SessionContext caller = session(7L, 41L); Instant now = Instant.now(); - store.replaceWorldScopes( + store.replaceRealmSnapshot( caller, "demo-world", 22L, "demo-world", - List.of(scopedRealm(caller, "production", "old-scope", now.plusSeconds(600)))); + "realms-catalog", + List.of(), + List.of(scopedRealm(caller, "production", "old-scope", now.plusSeconds(600))), + now); String oldRequestId = store .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) @@ -142,12 +151,15 @@ void clearingTransportLobbyRemovesScopeAndBoundJoinIdentityBeforeReuse() { assertThat(store.publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now)) .isEmpty(); assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); - store.replaceWorldScopes( + store.replaceRealmSnapshot( caller, "demo-world", 22L, "demo-world", - List.of(scopedRealm(caller, "production", "new-scope", now.plusSeconds(600)))); + "realms-catalog", + List.of(), + List.of(scopedRealm(caller, "production", "new-scope", now.plusSeconds(600))), + now); DirectTextConnectScopeSessionStore.JoinScope newAttempt = store .publicProductionScopeForJoin(caller, "demo-world", 22L, "demo-world", now) @@ -173,12 +185,15 @@ void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { assertThat(snapshot.expiresAt()).isBeforeOrEqualTo(now.plusSeconds(301)); }); - store.replaceWorldScopes( + store.replaceRealmSnapshot( caller, "1", 22L, "demo-world", - List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(86_400)))); + "realms-catalog", + List.of(), + List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(86_400))), + now); DirectTextConnectScopeSessionStore.JoinScope selected = store.publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now).orElseThrow(); @@ -311,18 +326,24 @@ void sameWorldSlugInDifferentTenantsKeepsOrdinalScopesIsolated() { new DirectTextConnectScopeSessionStore.WorldOrdinalTarget( 2, "DEMO", 33L, 4L, "tenant-33-target")), now); - store.replaceWorldScopes( + store.replaceRealmSnapshot( caller, "1", 22L, "demo", - List.of(scopedRealm(caller, 22L, "production", "tenant-22-scope", now.plusSeconds(60)))); - store.replaceWorldScopes( + "tenant-22-catalog", + List.of(), + List.of(scopedRealm(caller, 22L, "production", "tenant-22-scope", now.plusSeconds(60))), + now); + store.replaceRealmSnapshot( caller, "2", 33L, "demo", - List.of(scopedRealm(caller, 33L, "production", "tenant-33-scope", now.plusSeconds(60)))); + "tenant-33-catalog", + List.of(), + List.of(scopedRealm(caller, 33L, "production", "tenant-33-scope", now.plusSeconds(60))), + now); assertThat(store.publicProductionScopeForJoin(caller, "1", 22L, "demo", now)) .hasValueSatisfying( @@ -366,6 +387,36 @@ void storesRealmsResponseSnapshotOnlyForTheIssuingAccountAndBeforeExpiry() { assertThat(store.realmsSnapshot(caller, 22L, "demo", now.plusSeconds(301))).isEmpty(); } + @Test + void replacingWorldScopesClearsOnlyThatWorldsRealmsSnapshotAndKeepsJoinScopes() { + SessionContext caller = session(41L, 7L); + Instant now = Instant.now(); + store.replaceRealmSnapshot( + caller, "demo", 22L, "demo", "demo-catalog", List.of(), List.of(), now); + store.replaceRealmSnapshot( + caller, "secondary", 22L, "secondary", "secondary-catalog", List.of(), List.of(), now); + store.replaceRealmSnapshot( + caller, "demo", 33L, "demo", "other-tenant-catalog", List.of(), List.of(), now); + store.replaceWorldScopes( + caller, + "demo", + 22L, + "demo", + List.of(scopedRealm(caller, 22L, "production", "join-scope", now.plusSeconds(60)))); + + assertThat(store.realmsSnapshot(caller, 22L, "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(caller, 22L, "secondary", now)) + .hasValueSatisfying( + snapshot -> assertThat(snapshot.catalogFingerprint()).isEqualTo("secondary-catalog")); + assertThat(store.realmsSnapshot(caller, 33L, "demo", now)) + .hasValueSatisfying( + snapshot -> + assertThat(snapshot.catalogFingerprint()).isEqualTo("other-tenant-catalog")); + assertThat(store.publicProductionScopeForJoin(caller, "demo", 22L, "demo", now)).isEmpty(); + assertThat(store.publicProductionScope(caller, 22L, "demo", now)) + .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("join-scope")); + } + @Test void rejectsInvalidTransportIdsAndScopesBoundToAnotherIdentity() { assertThatThrownBy(() -> store.clearSession(0L)).isInstanceOf(IllegalArgumentException.class); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index 60f7c66661..d9ca3000ed 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -208,14 +208,15 @@ private static GameplayWorldCatalog.WorldView toWorldView(GameplayCatalogPropert if (input.getRealms() != null) { for (GameplayCatalogProperties.Realm realm : input.getRealms()) { if (realm != null) { - realms.add(toRealmView(realm)); + realms.add(toRealmView(input.getSlug(), realm)); } } } return new GameplayWorldCatalog.WorldView(input.getSlug(), input.getDisplayName(), realms); } - private static GameplayWorldCatalog.RealmView toRealmView(GameplayCatalogProperties.Realm input) { + private static GameplayWorldCatalog.RealmView toRealmView( + String worldSlug, GameplayCatalogProperties.Realm input) { String stateScope = input.getStateScope() == null ? "UNSPECIFIED" : input.getStateScope().name(); String characterCreationPolicy = @@ -234,9 +235,7 @@ private static GameplayWorldCatalog.RealmView toRealmView(GameplayCatalogPropert stateScope, characterCreationPolicy, 1L, - UUID.nameUUIDFromBytes( - ("test-realm:" + input.getTenantId() + ":" + input.getSlug()) - .getBytes(StandardCharsets.UTF_8)), + stableId("realm", input.getTenantId(), worldSlug, input.getSlug()), UUID.nameUUIDFromBytes( ("test-namespace:" + input.getTenantId() + ":" + input.getGameInstanceId()) .getBytes(StandardCharsets.UTF_8))); From cfd77a85e09b1c91abe53dcb54abb2f9e336d4ff Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 09:01:15 +1300 Subject: [PATCH 044/105] fix(gameplay): isolate lobby callers and preserve authority failure boundaries --- .../game-session-service/protocols.md | 4 +- .../tcp-proxy-service/protocols.md | 4 +- .../system-architecture-authentication.md | 2 +- .../system-architecture-authz-route-matrix.md | 2 +- ...ystem-architecture-authz-route-matrix.yaml | 4 +- .../player-access-and-session.md | 4 +- .../realm-routing-and-playable-state.md | 2 +- .../test_check_authz_route_matrix.py | 10 ++ .../command/text/GameplayWorldCatalog.java | 41 ++++-- .../command/text/PlayCommandHandler.java | 45 +++++- .../command/text/TextCommandInterpreter.java | 16 +- .../command/text/WorldsCommandHandler.java | 6 + .../DirectTextConnectScopeSessionStore.java | 6 + ...irectTextConnectScopeSessionStoreTest.java | 27 +++- .../text/GameplayWorldCatalogTest.java | 80 ++++++++++ .../command/text/PlayCommandHandlerTest.java | 137 ++++++++++++++++++ .../text/SessionResumptionFlowTest.java | 9 +- .../text/TextCommandInterpreterTest.java | 46 +++++- .../text/WorldsCommandHandlerTest.java | 9 ++ ...irectTextConnectScopeSessionStoreTest.java | 41 ++++++ 20 files changed, 442 insertions(+), 53 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index c385962f79..7f3d80ff74 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`. For a public-production target with fresh `MISSING` or non-admitting `INACTIVE` membership, it evaluates fresh tenant entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public-policy denial takes precedence. Current two-token `PLAY ` shorthand recognizes only visible realm names and otherwise treats the name as a character selector; an explicit `PLAY ` retains its realm selector even when unresolved or hidden. Non-public missing or non-admitting membership is first classified as `WORLD_ACCESS_DENIED`; a definitive denial for a selected realm that is not both visible and public-production returns generic `PLAY_SELECTION_REQUIRED`, even when its containing world is publicly discoverable. For a discoverable world, this projection matches the unresolved-realm result; the existing generic projection for a non-discoverable world is retained. A visible public-production target retains its canonical `WORLD_ACCESS_DENIED` outcome, and unavailable authority is not masked. This is current implementation behavior, not a target-contract change; canonical error ownership and discovery policy remain in [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries) and [ADR 0168](../../decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md). Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. Its fresh membership response now carries lifecycle, authority-generation, version, and evaluation-time fields, but the target independent issuance-time generation/version baseline reread and durable replay revalidation remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while a fresh existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. Direct-text `JOIN` is implemented as an explicit Game Session command translated to Account's `JoinPublicProductionMembership`; first-party `Join & Play` remains unimplemented as a distinct action. Current text `PLAY` validates membership identity, lifecycle, version, authority generation, and evaluation time; positive admission requires `ACTIVE`. For a public-production target with fresh `MISSING` or non-admitting `INACTIVE` membership, it evaluates fresh tenant entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or public-policy denial takes precedence. Current two-token `PLAY ` shorthand recognizes only visible realm names and otherwise treats the name as a character selector; an explicit `PLAY ` retains its realm selector even when unresolved or hidden. Non-public missing or non-admitting membership is first classified as `WORLD_ACCESS_DENIED`; a definitive denial for a selected realm that is not both visible and public-production returns generic `PLAY_SELECTION_REQUIRED`, even when its containing world is publicly discoverable. For a discoverable world, this projection matches the unresolved-realm result; the existing generic projection for a non-discoverable world is retained. A visible public-production target retains its canonical `WORLD_ACCESS_DENIED` outcome, and unavailable authority is not masked. This is current implementation behavior, not a target-contract change; canonical error ownership and discovery policy remain in [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries) and [ADR 0168](../../decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md). Positive non-public grant and entitlement snapshots must match their exact account/tenant/world/realm scope as applicable, include positive versions and billing sequence, and have an evaluation time no more than 15 seconds old and not in the future; invalid positive evidence fails with retryable authority or entitlement unavailable without changing the binding. Direct-text clients can then issue `JOIN` where required without `PLAY` creating or restoring membership implicitly. Current connect-token issuance does not validate the non-public realm grant and retains its existing Account rejection mapping. Account owns the target independent issuance-time reread of `membershipVersion` and `membershipAuthorityGeneration`; current proof for that baseline and target validation of connect-token grants for private/playtest scopes remain incomplete (see [Account Runtime and Data](../account-service/runtime-and-data.md#membership-and-entitlement-authority)). For logout and retained private semantic context, [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) owns the binding termination fence and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) owns namespace-scoped `resumeContextGeneration` and replay eligibility. Current player text handling rejects `LOGOUT` before side effects, and first-party private semantic transcript replay is gated when durable episode/binding termination proof is unavailable; fresh authoritative `LOOK` remains available. This fail-closed child behavior does not establish the durable successor protocol or complete either ADR. @@ -120,7 +120,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` now validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; for a public-production missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`. A valid non-public missing or non-admitting membership is classified as `WORLD_ACCESS_DENIED`, with the current player-facing result projected to generic selection guidance when its world is absent from public `WORLDS` discovery (see [Implementation Status](#implementation-status)). Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. The target independent membership-authority-generation/version reread at connect-token issuance and connect-token grant validation remain gaps. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` now validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; for a public-production missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`. A valid non-public missing or non-admitting membership is classified as `WORLD_ACCESS_DENIED`, with the current player-facing result projected to generic selection guidance when its world is absent from public `WORLDS` discovery (see [Implementation Status](#implementation-status)). Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. Account owns the required independent issuance-time reread of both membership version and authority generation; the baseline proof and connect-token grant validation for private/playtest scopes remain incomplete under the [Account runtime contract](../account-service/runtime-and-data.md#membership-and-entitlement-authority). If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 6f9507708b..1354314eaf 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -8,10 +8,10 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof, and the target independent issuance baseline/generation/version reread remains unproved. Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for eligible public-production targets, only missing or `INACTIVE` membership can reach `JOIN_REQUIRED`, after fresh entitlement/public policy permits joining. Existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` remains denied. Private/playtest targets perform the applicable current realm-grant check. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. +The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof. The target requires an independent issuance-time Account reread of `membershipVersion` and `membershipAuthorityGeneration`; the current baseline and replay-revalidation proof remains incomplete under [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for eligible public-production targets, only missing or `INACTIVE` membership can reach `JOIN_REQUIRED`, after fresh entitlement/public policy permits joining. Existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` remains denied. Private/playtest targets perform the applicable current realm-grant check. The separate target connect-token grant-validation contract for private/playtest targets also remains unimplemented. The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` always performs fresh membership and applicable private/playtest grant checks, regardless of any connect-token replay-cache state. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). The Telnet credential form is `LOGIN [secret]`. `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. -The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but the target independent issuance baseline/reread and private/playtest grant check remain implementation and proof gaps. For an eligible public-production target with missing or `INACTIVE` membership, text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or policy denial wins. An existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` is denied. These local gaps do not change the Authentication-owned admission outcomes. +The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but does not establish the target-required independent issuance-time reread of membership version and authority generation. Its baseline proof remains incomplete, and target private/playtest connect-token grant validation is a separate gap. For an eligible public-production target with missing or `INACTIVE` membership, text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or policy denial wins. An existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` is denied. These local gaps do not change the Authentication-owned admission outcomes. The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients have a local `LOGIN` -> `PLAY` -> `LOOK` path for existing admitting members; when `PLAY` returns `JOIN_REQUIRED`, the client can issue `JOIN` and retry `PLAY` before `LOOK`. Focused local JOIN proof exists, while full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Missing or `INACTIVE` eligible public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement/public policy permits joining; existing `ACTIVE` membership with gameplay admission disabled remains denied. Direct text can invoke the Account-backed writer. Missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. ## Cross-Path Connectivity Contract diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 4476096c35..81949a723a 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the target independent membership-version and authority-generation baseline reread at connect-token issuance remains a proof gap. On a connect-token cache miss, current issuance consumes its implemented membership evidence; a `session:connect-token:*` replay hit can return cached success before fresh entitlement, membership, and pointer rereads. The exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` does not use that replay cache: each attempt reads current Account membership and validates exact `accountId`/`tenantId`, lifecycle, membership version, authority generation, admission state, and a fresh evaluation time before binding. Existing-member admission requires `membershipLifecycleState=ACTIVE` and `gameplayAdmissionAllowed=true`. For public production, only a fresh `MISSING` or `INACTIVE` membership can return `JOIN_REQUIRED`, and only after fresh tenant entitlement and `allowPublicJoin=true` checks; invalid or unavailable membership evidence fails closed, while public-policy denial remains a distinct denial. Text `PLAY` separately reads the current realm grant for private/playtest targets; its internal non-public missing or non-admitting membership classification is `WORLD_ACCESS_DENIED`. Definitive denial for an explicitly selected hidden or non-public-production realm projects the same selection-required response as an unresolved realm within a publicly discoverable world; a non-discoverable world retains the generic selection-required response without target metadata. Visible public-production denial and unavailable authority retain their distinct outcomes. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. The Account runtime response now includes lifecycle and authority-generation fields, but connect-token issuance does not establish the target independent issuance-time baseline or durable replay revalidation. The complete first-party browser/mobile sequence remains partial, with PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof gaps. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`. Target connect-token issuance requires an independent issuance-time Account reread that captures `membershipVersion` and `membershipAuthorityGeneration` from the same authoritative membership snapshot; this baseline requirement is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). On a connect-token cache miss, current issuance consumes its implemented membership evidence; a `session:connect-token:*` replay hit can return cached success before fresh entitlement, membership, and pointer rereads. The exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` does not use that replay cache: each attempt reads current Account membership and validates exact `accountId`/`tenantId`, lifecycle, membership version, authority generation, admission state, and a fresh evaluation time before binding. Existing-member admission requires `membershipLifecycleState=ACTIVE` and `gameplayAdmissionAllowed=true`. For public production, only a fresh `MISSING` or `INACTIVE` membership can return `JOIN_REQUIRED`, and only after fresh tenant entitlement and `allowPublicJoin=true` checks; invalid or unavailable membership evidence fails closed, while public-policy denial remains a distinct denial. Text `PLAY` separately reads the current realm grant for private/playtest targets; its internal non-public missing or non-admitting membership classification is `WORLD_ACCESS_DENIED`. Definitive denial for an explicitly selected hidden or non-public-production realm projects the same selection-required response as an unresolved realm within a publicly discoverable world; a non-discoverable world retains the generic selection-required response without target metadata. Visible public-production denial and unavailable authority retain their distinct outcomes. Current connect-token issuance retains its Account-owned rejection mapping; its separate private/playtest grant validation remains incomplete. Current issuance has not implemented or proved the required independent membership baseline reread or durable replay revalidation. The complete first-party browser/mobile sequence remains partial, with PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof gaps. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index f9fe0e367a..c7807388e6 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -26,7 +26,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status - Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` validates fresh Account membership identity, lifecycle, version, authority generation, and evaluation time. Missing or `INACTIVE` public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement and `allowPublicJoin` permit joining; an `ACTIVE` but non-admitting member is denied without JOIN advice because Account's explicit JOIN writer cannot repair that state. Policy denial and unavailable/invalid authority remain distinct outcomes. Direct-text `JOIN` is implemented locally through Account's explicit writer; first-party `Join & Play`, durable unknown-outcome recovery, and end-to-end proof remain incomplete. -- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. +- `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy declared for these methods in the normative [machine-readable route matrix](./system-architecture-authz-route-matrix.yaml). Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. - The `platformAdmin` privileged-control predicate applies to the exact internal-workload `account-service/IssueHumanOperatorAuthorizationReference` issuance route in addition to its declared route-class allowlist. This exact route identity does not add `internal_workload` to the support or billing-safe classification scopes; the separate automation issuance path prohibits privileged control. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 0964c877bf..3f7731cac0 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1938,7 +1938,7 @@ routes: membership_authority_generation_applies: false required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, connect_scope_match, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, MEMBERSHIP_RECONCILIATION_REQUIRED, TENANT_BILLING_BLOCKED] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation route_status: target_not_currently_routable @@ -1994,7 +1994,7 @@ routes: membership_authority_generation_applies: false required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, connect_scope_match, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_MISMATCH, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, MEMBERSHIP_RECONCILIATION_REQUIRED, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE, IDEMPOTENCY_CONFLICT] mutation_contract: explicit_public_membership_atomic exact_scope_revalidation: required: true 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 7a11fad0cd..017dd67973 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN writing and direct text dispatch, durable Account audit outbox handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `POST /auth/bootstrap/join` controller/operation exists locally, but the Gateway guard still blocks its external exposure. Logging & Admin receipt persistence/readback is separate #2848 work, not part of the Account core. First-party `Join & Play`, recovery after an unknown JOIN commit outcome, PostgreSQL runtime proof, and direct text-client end-to-end proof remain unavailable or unclaimed; the membership-version and authority-generation baseline reread at connect-token issuance also remains incomplete. Current `PLAY` and connect-token issuance remain partial, with membership and realm-grant authorities separately owned by Account. Namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN writing and direct text dispatch, durable Account audit outbox handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `POST /auth/bootstrap/join` controller/operation exists locally, but the Gateway guard still blocks its external exposure. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receipt receiver persistence/readback remains unproved under #2940. First-party `Join & Play`, recovery after an unknown JOIN commit outcome, PostgreSQL runtime proof, and direct text-client end-to-end proof remain unavailable or unclaimed; the membership-version and authority-generation baseline reread at connect-token issuance also remains incomplete. Current `PLAY` and connect-token issuance remain partial, with membership and realm-grant authorities separately owned by Account. Namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and the terminal post-logout `resumeContextGeneration` fence remain incomplete; current private replay is suppressed fail-closed. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -175,7 +175,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs, including the implemented `/auth/bootstrap/join` controller and local JOIN RPC; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs, including the implemented `/auth/bootstrap/join` controller and local JOIN RPC; public Gateway exposure remains blocked, leave remains target-only, and Game Session direct-text JOIN dispatch is implemented locally while first-party `Join & Play` remains unavailable | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted proxy/first-party handshake validation, signed connect context, stable edge socket/session id, upstream gameplay bridge and rebind | `/ws/game/**`; `TrustedTcpProxyIdentity`; connect-token and first-party context headers | 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 d1e4ca1761..7c400efb58 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 @@ -123,7 +123,7 @@ No competing implementation is recorded for visible realm addressing, world-qual | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | | Game Session | Persisted realm catalog and admission pointers; internal row-locked dual-revision CAS with atomic pointer/audit persistence; catalog projection; session normalization; runtime, tick, command, remote, and operator projections. Public pointer-mutation and cutover RPCs remain fail-closed. | World-qualified admission-pointer gRPC/control-plane APIs; persisted pointer authority; normalized session helpers | -| Account Service | Tenant membership/grants; bootstrap worlds/realms/characters; membership exit; membership-required connect-token issuance; target explicit public-production join | Bootstrap/auth REST and gRPC APIs; runtime membership/grant/entitlement reads; target explicit-join behavior | +| Account Service | Tenant membership/grants; bootstrap worlds/realms/characters; membership exit; membership-required connect-token issuance; locally implemented `JoinPublicProductionMembership` writer | Bootstrap/auth REST and gRPC APIs; runtime membership/grant/entitlement reads; direct-text JOIN invokes the local writer, while first-party `Join & Play` remains unavailable and complete activation proof remains open | | Gateway and TCP Proxy | Trusted first-party/Telnet routing propagation; explicit disconnect runtime metadata; authenticated callbacks | Connect context; all-or-none routing headers; `gameInstanceId` disconnect envelope | | Entity Management | Scoped character, roster, item, friend, progression, resource, condition, and playable-state persistence | `{tenantId, gameInstanceId, playableStateScope}` APIs and attested gameplay calls | | Automation Scripting | Scope- and routing-aware ingress, scheduling, durable work, handoff, dead-letter, and control-plane reads | Gameplay trigger/handoff contracts; normalized routing metadata | diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index 7dd8e8df5f..74e84db384 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -6154,6 +6154,16 @@ def test_direct_text_join_matrix_includes_account_terminal_outcomes(self): self.assertIn("CONNECT_SCOPE_INVALID", outcomes) self.assertIn("MEMBERSHIP_RECONCILIATION_REQUIRED", outcomes) + for route_name in ( + "POST /auth/bootstrap/join", + "JoinPublicProductionMembership", + ): + with self.subTest(route_name=route_name): + account_route = route_for(document, "account-service", route_name) + account_outcomes = account_route["canonical_errors"]["any_of"] + self.assertIn("CONNECT_SCOPE_INVALID", account_outcomes) + self.assertIn("MEMBERSHIP_RECONCILIATION_REQUIRED", account_outcomes) + def test_privileged_control_cardinality_error_uses_shared_set(self): document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) routes = [ diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 17e89920fd..38e7250054 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -548,7 +548,8 @@ public PublicProductionRealmCardinality publicProductionRealmCardinality(long te } if (authorityPointerSupplier != null) { return cardinality( - publicProductionCountsFromPointers(loadAuthorityPointers()).getOrDefault(tenantId, 0L)); + publicProductionCountsFromPointers(validateAuthoritySnapshot(readAuthorityPointers())) + .getOrDefault(tenantId, 0L)); } return cardinality(readCatalogState().publicProductionCounts().getOrDefault(tenantId, 0L)); } @@ -733,20 +734,26 @@ public boolean matchesCurrentAdmissionPointer(WorldView expectedWorld, RealmView return false; } if (tenantAuthorityPointerSupplier != null) { - List pointers = - loadAuthorityPointersForTenant(expectedRealm.tenantId()); - if (!tenantHasValidPublicProductionAuthority(pointers, expectedRealm.tenantId())) { - return false; - } - List selected = - pointers.stream() - .filter(pointer -> matchesExpectedTarget(expectedWorld, expectedRealm, pointer)) - .toList(); - if (selected.size() != 1) { + try { + List pointers = + loadAuthorityPointersForTenant(expectedRealm.tenantId()); + if (!tenantHasValidPublicProductionAuthority(pointers, expectedRealm.tenantId())) { + return false; + } + List selected = + pointers.stream() + .filter(pointer -> matchesExpectedTarget(expectedWorld, expectedRealm, pointer)) + .toList(); + if (selected.size() != 1) { + return false; + } + requireCollisionSafeVisiblePointer(pointers, selected.getFirst()); + return true; + } catch (AuthorityPointerReadUnavailableException ex) { + throw ex; + } catch (AuthorityPointerUnavailableException ex) { return false; } - requireCollisionSafeVisiblePointer(pointers, selected.getFirst()); - return true; } if (authorityPointerSupplier != null) { List pointers = readAuthorityPointers(); @@ -839,6 +846,8 @@ private List loadAuthorityPointersForTenant(lo pointers = tenantAuthorityPointerSupplier.apply(tenantId); } catch (AuthorityPointerReadUnavailableException ex) { throw ex; + } catch (AuthorityPointerUnavailableException ex) { + throw ex; } catch (RuntimeException ex) { throw new AuthorityPointerReadUnavailableException( "Authoritative tenant gameplay pointer list is unavailable", ex); @@ -991,6 +1000,8 @@ private List readAuthorityPointers() { return pointers; } catch (AuthorityPointerReadUnavailableException ex) { throw ex; + } catch (AuthorityPointerUnavailableException ex) { + throw ex; } catch (RuntimeException ex) { throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable", ex); @@ -1203,6 +1214,10 @@ private static List loadAuthorityPointers( GameplayAdmissionPointerAuthorityService authorityService) { Objects.requireNonNull(authorityService, "authorityService must not be null"); List pointers = authorityService.listPointers(); + if (pointers == null) { + throw new AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } return validateAuthoritySnapshot(pointers); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 2d79450635..8b4368d059 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -77,6 +77,7 @@ public class PlayCommandHandler { private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; private final ScriptEventPublisher scriptEventPublisher; private final MeterRegistry meterRegistry; + private final Clock authorityEvaluationClock; private final Counter takeoverCounter; private final Counter resumeCounter; @@ -95,6 +96,38 @@ public PlayCommandHandler( ScriptEventPublisher scriptEventPublisher, MeterRegistry meterRegistry, DirectTextConnectScopeSessionStore connectScopeSessionStore) { + this( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + gameplayWorldCatalog, + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + connectScopeSessionStore, + Clock.systemUTC()); + } + + PlayCommandHandler( + SessionAuthenticationService sessionAuthenticationService, + SessionContextService sessionContextService, + SessionRoutingNormalizationService sessionRoutingNormalizationService, + GameplayWorldCatalog gameplayWorldCatalog, + GameLogicProperties gameLogicProperties, + AccountClient accountClient, + EntityManagementClient entityManagementClient, + ModerationPolicyClient moderationPolicyClient, + FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, + GameplayPresenceLifecycleService gameplayPresenceLifecycleService, + ScriptEventPublisher scriptEventPublisher, + MeterRegistry meterRegistry, + DirectTextConnectScopeSessionStore connectScopeSessionStore, + Clock authorityEvaluationClock) { this.sessionAuthenticationService = Objects.requireNonNull( sessionAuthenticationService, "sessionAuthenticationService must not be null"); @@ -125,6 +158,9 @@ public PlayCommandHandler( this.scriptEventPublisher = Objects.requireNonNull(scriptEventPublisher, "scriptEventPublisher must not be null"); this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry must not be null"); + this.authorityEvaluationClock = + Objects.requireNonNull( + authorityEvaluationClock, "authorityEvaluationClock must not be null"); this.takeoverCounter = this.meterRegistry.counter(TAKEOVER_METRIC); this.resumeCounter = this.meterRegistry.counter(RESUME_METRIC); } @@ -1117,7 +1153,8 @@ private boolean isSafeMembershipAuthorityResponse( response.getTenantId(), context.accountId(), selectedRealm.tenantId()) - || !AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC())) { + || !AuthorityEvaluationFreshness.isFresh( + response.getEvaluatedAt(), authorityEvaluationClock)) { return false; } if (!response.getMembershipExists()) { @@ -1147,7 +1184,8 @@ && hasMatchingAuthorityIdentity( response.getAccountId(), response.getTenantId(), context.accountId(), realm.tenantId()) && world.slug().equals(response.getWorldSlug()) && realm.slug().equals(response.getRealmSlug()) - && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); + && AuthorityEvaluationFreshness.isFresh( + response.getEvaluatedAt(), authorityEvaluationClock); } private boolean isValidEntitlement( @@ -1155,7 +1193,8 @@ private boolean isValidEntitlement( return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) && response.getEntitlementVersion() > 0L && response.getTenantBillingSequence() > 0L - && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); + && AuthorityEvaluationFreshness.isFresh( + response.getEvaluatedAt(), authorityEvaluationClock); } private boolean hasMatchingAuthorityIdentity( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java index 60f2cb4e39..f2b6f50c85 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java @@ -235,20 +235,16 @@ public TextCommandInterpreter( public TextCommandInterpretationResult interpret( String sessionId, String rawLine, boolean requiresSoloTick) { - String firstToken = rawLine == null ? "" : rawLine.trim().split("\\s+", 2)[0]; - if (TextCommandType.fromToken(firstToken) == TextCommandType.LOGOUT) { - return interpretLogoutWithoutNormalization( - sessionId, parser.parse(rawLine, registry), requiresSoloTick); + TextCommand baseCommand = parser.parse(rawLine, registry); + if (baseCommand.type() == TextCommandType.LOGOUT) { + return interpretLogoutWithoutNormalization(sessionId, baseCommand, requiresSoloTick); } Optional context = sessionAuthenticationService.resolveSessionContext(sessionId); TextCommandRegistry activeRegistry = registryFor(context); - return interpret( - sessionId, - parser.parse(rawLine, activeRegistry), - requiresSoloTick, - context, - activeRegistry); + TextCommand activeCommand = + admittedRegistryResolver == null ? baseCommand : parser.parse(rawLine, activeRegistry); + return interpret(sessionId, activeCommand, requiresSoloTick, context, activeRegistry); } public TextCommandInterpretationResult interpret( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index a7ae0d9ada..0136969fb4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -546,6 +546,8 @@ public JoinMembershipResult joinPublicProductionMembership( catalogSnapshot = worldCatalog.readDiscoverySnapshot(); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); @@ -562,6 +564,8 @@ public JoinMembershipResult joinPublicProductionMembership( currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } Optional maybeRealmSnapshot; try { @@ -609,6 +613,8 @@ public JoinMembershipResult joinPublicProductionMembership( hasPublicProductionRealm = worldCatalog.hasValidPublicProductionRealm(tenantId); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } if (!hasPublicProductionRealm) { return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index 88d3dcf0bc..b9d3eb75aa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -164,6 +164,12 @@ public void replaceWorldScopes( nowMillis, current -> { LobbyRecord record = current == null ? LobbyRecord.empty(caller.sessionId()) : current; + if (record.sessionId() != caller.sessionId()) { + throw new ConflictingIdentityException("lobby record transport session did not match"); + } + if (record.accountId() > 0L && record.accountId() != caller.accountId()) { + record = LobbyRecord.empty(caller.sessionId()); + } Map> byWorld = new HashMap<>(record.scopesByWorld()); byWorld.remove(key); if (!storedScopes.isEmpty()) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java index 1b01202029..340451eeb0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java @@ -70,30 +70,40 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws firstInstance.replaceWorldSnapshot( SESSION_ID, 0L, "catalog-fingerprint-v13", List.of(target), now); - firstInstance.replaceWorldScopes( + firstInstance.replaceRealmSnapshot( caller, "1", 22L, "demo-world", + "realm-catalog-fingerprint-v13", + List.of( + new DirectTextConnectScopeSessionStore.RealmOrdinalTarget( + 1, "production", 22L, 9L, 1L, "realm-target-fingerprint-v13")), List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( "production", true, "account-connect-scope-17", now.plusSeconds(600), - playerContext(caller)))); - firstInstance.replaceWorldScopes( + playerContext(caller))), + now); + firstInstance.replaceRealmSnapshot( caller, "2", 33L, "demo-world", + "tenant-33-realm-catalog-v13", + List.of( + new DirectTextConnectScopeSessionStore.RealmOrdinalTarget( + 1, "production", 33L, 9L, 1L, "tenant-33-realm-target-v13")), List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( "production", true, "account-connect-scope-33", now.plusSeconds(600), - playerContext(caller, 33L)))); + playerContext(caller, 33L))), + now); assertThat( replacementJoinScope(newStoreInstance(), caller, "2", 33L, "demo-world", Instant.now())) .satisfies( @@ -143,18 +153,23 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws caller, "1", 22L, "demo-world", Instant.now())) .isEmpty(); - replacement.replaceWorldScopes( + replacement.replaceRealmSnapshot( caller, "1", 22L, "demo-world", + "realm-catalog-fingerprint-v14", + List.of( + new DirectTextConnectScopeSessionStore.RealmOrdinalTarget( + 1, "production", 22L, 9L, 1L, "realm-target-fingerprint-v14")), List.of( new DirectTextConnectScopeSessionStore.ScopedRealm( "production", true, "account-connect-scope-18", Instant.now().plusSeconds(600), - playerContext(caller)))); + playerContext(caller))), + Instant.now()); String freshRequestId = firstInstance .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", Instant.now()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index c815ffdffd..19a3cff738 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -363,6 +363,71 @@ void pointerReadFailureIsDistinctFromMalformedOrAmbiguousAuthority() { .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); } + @Test + void publicProductionCardinalityKeepsReadOutageDistinctFromMalformedSnapshot() { + when(authorityService.listPointers()) + .thenThrow(new IllegalStateException("authority down")) + .thenReturn( + List.of(pointer("demo", "Demo World", "production", "Live Realm", 0L, 11L, 1L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(() -> catalog.publicProductionRealmCardinality(1L)) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); + assertThatThrownBy(() -> catalog.publicProductionRealmCardinality(1L)) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .isNotInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class) + .hasMessageContaining("tenant identity is unavailable"); + } + + @Test + void matchesCurrentAdmissionPointerReturnsFalseForMalformedTenantSnapshot() { + CurrentAdmissionTarget target = currentAdmissionTarget(); + when(authorityService.listPointersByTenant(1L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "live", + "Live Realm", + 1L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L))); + + assertThat(target.catalog().matchesCurrentAdmissionPointer(target.world(), target.realm())) + .isFalse(); + } + + @Test + void matchesCurrentAdmissionPointerReturnsFalseForSelectorCollision() { + CurrentAdmissionTarget target = currentAdmissionTarget(); + when(authorityService.listPointersByTenant(1L)) + .thenReturn( + List.of( + publicPointer("demo", "Demo World", 1L, 11L), + privatePointer("Demo", "Demo World Alias", "preview", "Preview Realm", 1L, 12L))); + + assertThat(target.catalog().matchesCurrentAdmissionPointer(target.world(), target.realm())) + .isFalse(); + } + + @Test + void matchesCurrentAdmissionPointerPropagatesTenantReadOutage() { + CurrentAdmissionTarget target = currentAdmissionTarget(); + when(authorityService.listPointersByTenant(1L)) + .thenThrow(new IllegalStateException("authority down")); + + assertThatThrownBy( + () -> target.catalog().matchesCurrentAdmissionPointer(target.world(), target.realm())) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); + } + @Test void reverseRuntimeLookupFailsClosedWhenMultipleVisibleRealmsShareRuntimeTarget() { when(authorityService.listPointers()) @@ -1067,6 +1132,21 @@ private static GameplayCatalogProperties.World propertyWorld( return world; } + private CurrentAdmissionTarget currentAdmissionTarget() { + when(authorityService.listPointers()) + .thenReturn(List.of(publicPointer("demo", "Demo World", 1L, 11L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + GameplayWorldCatalog.WorldView world = + catalog.resolveWorldFromAuthoritySnapshot("demo").orElseThrow(); + GameplayWorldCatalog.RealmView realm = catalog.resolveRealm(world, "live").orElseThrow(); + return new CurrentAdmissionTarget(catalog, world, realm); + } + + private record CurrentAdmissionTarget( + GameplayWorldCatalog catalog, + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmView realm) {} + private static GameplayWorldCatalog.WorldView worldWithRealm( String worldSlug, String realmSlug, long tenantId, boolean publicProduction) { return new GameplayWorldCatalog.WorldView( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 4c950236d9..2179abf7e9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -5,7 +5,9 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Clock; import java.time.Instant; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -2745,6 +2747,92 @@ void playPublicJoinRequiresFreshEntitlementEvidence(String evidence) { Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); } + @Test + void playAuthorityFreshnessUsesInjectedClockAtExactInclusiveBoundaries() { + Instant authorityNow = Instant.parse("2030-05-06T07:08:09Z"); + handler = handlerWithClock(Clock.fixed(authorityNow, ZoneOffset.UTC)); + List evaluatedAtValues = + List.of( + authorityNow.toString(), + authorityNow.minusSeconds(15).toString(), + authorityNow.minusSeconds(15).minusNanos(1).toString(), + authorityNow.plusNanos(1).toString()); + SessionContext unboundContext = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")) + .thenReturn(Optional.of(unboundContext)); + + for (int index = 0; index < evaluatedAtValues.size(); index++) { + String evaluatedAt = evaluatedAtValues.get(index); + Mockito.doReturn(missingMembershipAt(evaluatedAt)) + .when(accountClient) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(publicEntitlement(true, authorityNow.toString())) + .when(accountClient) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo( + index < 2 + ? GameplayStageCommandConstants.JOIN_REQUIRED_CODE + : GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + } + + for (int index = 0; index < evaluatedAtValues.size(); index++) { + String evaluatedAt = evaluatedAtValues.get(index); + Mockito.doReturn(missingMembershipAt(authorityNow.toString())) + .when(accountClient) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(publicEntitlement(true, evaluatedAt)) + .when(accountClient) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo( + index < 2 + ? GameplayStageCommandConstants.JOIN_REQUIRED_CODE + : GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + } + + when(sessionAuthenticationService.resolveSessionContext("1")) + .thenReturn(Optional.of(previewRealmContext())); + Mockito.doReturn(publicEntitlement(true, authorityNow.toString())) + .when(accountClient) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + for (int index = 0; index < evaluatedAtValues.size(); index++) { + String evaluatedAt = evaluatedAtValues.get(index); + Mockito.doReturn(activeMembershipAt(authorityNow.toString())) + .when(accountClient) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(validGrant().toBuilder().setEvaluatedAt(evaluatedAt).build()) + .when(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + if (index < 2) { + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + } else { + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + } + } + } + @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = @@ -3102,6 +3190,50 @@ private static String evaluatedAtNow() { return Instant.now().toString(); } + private PlayCommandHandler handlerWithClock(Clock clock) { + return new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + worldCatalog, + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + connectScopeSessionStore, + clock); + } + + private static GetTenantMembershipForRuntimeResponse missingMembershipAt(String evaluatedAt) { + return GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setMembershipVersion(0L) + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(evaluatedAt) + .build(); + } + + private static GetTenantMembershipForRuntimeResponse activeMembershipAt(String evaluatedAt) { + return GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAt) + .build(); + } + private static GetRealmAccessGrantForRuntimeResponse validGrant() { return validGrant("123", "22", "sandbox", "preview"); } @@ -3131,6 +3263,11 @@ private static GetTenantEntitlementsForRuntimeResponse publicEntitlement( .build(); } + private static GetTenantEntitlementsForRuntimeResponse publicEntitlement( + boolean allowPublicJoin, String evaluatedAt) { + return publicEntitlement(allowPublicJoin).toBuilder().setEvaluatedAt(evaluatedAt).build(); + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index a426cebb22..a39db7d5e3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -278,6 +278,8 @@ void setUp() { true, List.of(), List.of()))); + DirectTextConnectScopeSessionStore connectScopeSessionStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); playHandler = new PlayCommandHandler( sessionAuthenticationService, @@ -292,13 +294,10 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + connectScopeSessionStore); worldsHandler = new WorldsCommandHandler( - worldCatalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + worldCatalog, entityManagementClient, accountClient, connectScopeSessionStore); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); interpreter = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 59a266fb3e..c638608314 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -383,6 +383,8 @@ void setUp() { pointerAuthorityService, gameplayPresenceLifecycleService, meterRegistry); + DirectTextConnectScopeSessionStore connectScopeSessionStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); PlayCommandHandler playHandler = new PlayCommandHandler( sessionAuthenticationService, @@ -397,7 +399,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + connectScopeSessionStore); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); WhoCommandHandler whoHandler = @@ -435,10 +437,7 @@ void setUp() { .build()); WorldsCommandHandler worldsHandler = new WorldsCommandHandler( - worldCatalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + worldCatalog, entityManagementClient, accountClient, connectScopeSessionStore); LookResult lookResult = LookResult.newBuilder() @@ -537,6 +536,43 @@ void worldsAreVisibleBeforeLogin() { verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } + @Test + void logoutAliasDispatchesBeforeStaleBindingNormalization() { + SessionContext staleBinding = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); + sessionContextService.save(staleBinding); + gameplayPresenceService.registerConnected(staleBinding); + when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)).thenReturn(List.of()); + Mockito.clearInvocations(pointerAuthorityService); + + TextCommandInterpretationResult result = interpreter.interpret("1", "QUIT", false); + + assertThat(result.commandResult().errorCode()).isEqualTo("LOGOUT_UNAVAILABLE"); + assertThat(sessionContextService.findBySessionId(1L)).hasValue(staleBinding); + assertThat(gameplayPresenceService.findConnectedBySessionId(1L)) + .hasValueSatisfying( + presence -> { + assertThat(presence.accountId()).isEqualTo(staleBinding.accountId()); + assertThat(presence.gameInstanceId()).isEqualTo(staleBinding.gameInstanceId()); + }); + Mockito.verify(pointerAuthorityService, never()).listByRuntimeTarget(22L, 1L); + } + @Test void realmsBrowseFailsClosedWhenScopeAuthorityIsUnavailable() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index ed3d3c9c54..a96054e0ab 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2045,6 +2045,15 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("AUTH_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient, entityManagementClient); + + Mockito.doReturn(List.of(authorityPointer("demo", "production", 0L, 1L, true))) + .when(authorityService) + .listPointers(); + Mockito.clearInvocations(accountClient, entityManagementClient); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo( + WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } private WorldsCommandHandler authenticatedHandler( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 1069e27344..e258fa4074 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -417,6 +417,47 @@ void replacingWorldScopesClearsOnlyThatWorldsRealmsSnapshotAndKeepsJoinScopes() .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("join-scope")); } + @Test + void replacingWorldScopesForAnotherAccountClearsPriorLobbyAuthority() { + SessionContext previousCaller = session(41L, 7L); + SessionContext currentCaller = session(41L, 8L); + Instant now = Instant.now(); + Instant expiresAt = now.plusSeconds(60); + store.replaceRealmSnapshot( + previousCaller, + "demo", + 22L, + "demo", + "previous-demo-catalog", + List.of(), + List.of(scopedRealm(previousCaller, 22L, "production", "previous-demo-scope", expiresAt)), + now); + store.replaceRealmSnapshot( + previousCaller, + "secondary", + 22L, + "secondary", + "previous-secondary-catalog", + List.of(), + List.of( + scopedRealm(previousCaller, 22L, "production", "previous-secondary-scope", expiresAt)), + now); + + store.replaceWorldScopes( + currentCaller, + "demo", + 22L, + "demo", + List.of(scopedRealm(currentCaller, 22L, "production", "current-demo-scope", expiresAt))); + + assertThat(store.realmsSnapshot(currentCaller, 22L, "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(currentCaller, 22L, "secondary", now)).isEmpty(); + assertThat(store.publicProductionScope(currentCaller, 22L, "secondary", now)).isEmpty(); + assertThat(store.publicProductionScope(currentCaller, 22L, "demo", now)) + .hasValueSatisfying( + scope -> assertThat(scope.connectScopeId()).isEqualTo("current-demo-scope")); + } + @Test void rejectsInvalidTransportIdsAndScopesBoundToAnotherIdentity() { assertThatThrownBy(() -> store.clearSession(0L)).isInstanceOf(IllegalArgumentException.class); From 0ebba6229b5bbb945532549fb60d122f320954bc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 09:25:09 +1300 Subject: [PATCH 045/105] Classify malformed discovery authority and complete JOIN outcome proof --- ...ystem-architecture-authz-route-matrix.yaml | 2 +- .../test_check_authz_route_matrix.py | 2 + .../command/text/GameplayWorldCatalog.java | 20 +++---- .../command/text/PlayCommandHandler.java | 2 + .../command/text/WorldsCommandHandler.java | 4 ++ .../WorldsTextCommandDispatchHandler.java | 3 + .../text/GameplayWorldCatalogTest.java | 18 ++++++ .../command/text/PlayCommandHandlerTest.java | 58 ++++++++++++++++++ .../text/WorldsCommandHandlerTest.java | 8 +++ .../WorldsTextCommandDispatchHandlerTest.java | 59 +++++++++++++++++-- 10 files changed, 159 insertions(+), 17 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 3f7731cac0..bd64512786 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1938,7 +1938,7 @@ routes: membership_authority_generation_applies: false required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer, connect_scope_match, idempotency] canonical_errors: - any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, MEMBERSHIP_RECONCILIATION_REQUIRED, TENANT_BILLING_BLOCKED] + any_of: [PUBLIC_PRODUCTION_ADMISSION_DENIED, ADMISSION_POINTER_UNAVAILABLE, AUTH_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, ENTITLEMENT_UNAVAILABLE, MEMBERSHIP_RECONCILIATION_REQUIRED, TENANT_BILLING_BLOCKED] mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation route_status: target_not_currently_routable diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index 74e84db384..cfa3dd89ff 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -6163,6 +6163,8 @@ def test_direct_text_join_matrix_includes_account_terminal_outcomes(self): account_outcomes = account_route["canonical_errors"]["any_of"] self.assertIn("CONNECT_SCOPE_INVALID", account_outcomes) self.assertIn("MEMBERSHIP_RECONCILIATION_REQUIRED", account_outcomes) + self.assertIn("AUTH_UNAVAILABLE", account_outcomes) + self.assertIn("ENTITLEMENT_UNAVAILABLE", account_outcomes) def test_privileged_control_cardinality_error_uses_shared_set(self): document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 38e7250054..f9d0059c7e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -991,8 +991,13 @@ private List readAuthorityPointers() { throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); } + return readAuthorityPointers(authorityPointerSupplier); + } + + private static List readAuthorityPointers( + Supplier> pointerSupplier) { try { - List pointers = authorityPointerSupplier.get(); + List pointers = pointerSupplier.get(); if (pointers == null) { throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable"); @@ -1213,20 +1218,11 @@ private static boolean tenantHasValidPublicProductionAuthority( private static List loadAuthorityPointers( GameplayAdmissionPointerAuthorityService authorityService) { Objects.requireNonNull(authorityService, "authorityService must not be null"); - List pointers = authorityService.listPointers(); - if (pointers == null) { - throw new AuthorityPointerReadUnavailableException( - "Authoritative gameplay pointer list is unavailable"); - } - return validateAuthoritySnapshot(pointers); + return validateAuthoritySnapshot(readAuthorityPointers(authorityService::listPointers)); } private List loadAuthorityPointers() { - if (authorityPointerSupplier == null) { - throw new AuthorityPointerUnavailableException( - "Authoritative gameplay pointer list is unavailable"); - } - return validateAuthoritySnapshot(authorityPointerSupplier.get()); + return validateAuthoritySnapshot(readAuthorityPointers()); } private static List validateAuthoritySnapshot( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 8b4368d059..dd1167116a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -231,6 +231,8 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { null, null, ex); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return admissionPointerUnavailableFailure(tenantTag, null); } WorldSelectorResolution worldSelection = resolvePlayWorld(context, requestedSelection.worldSelector(), currentCatalog); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 0136969fb4..de7d3e6574 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -118,6 +118,8 @@ public RealmBrowseResult browseRealms( catalogSnapshot = worldCatalog.readDiscoverySnapshot(); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); @@ -755,6 +757,8 @@ public CharacterBrowseResult browseCharacters( catalogSnapshot = worldCatalog.readDiscoverySnapshot(); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index fbfed45226..e73d976359 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -61,6 +61,9 @@ private TextCommandInterpretationResult handleWorlds(TextCommandDispatchRequest "INVALID_ARGUMENT", "Transport session is unavailable. Reconnect and try again."); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return errorResult("AUTH_UNAVAILABLE", "World list is temporarily unavailable."); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return errorResult( + "ADMISSION_POINTER_UNAVAILABLE", "World routing is unavailable. Retry WORLDS."); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return errorResult("AUTH_UNAVAILABLE", "World list is temporarily unavailable."); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 19a3cff738..e7e975c4e4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -363,6 +363,24 @@ void pointerReadFailureIsDistinctFromMalformedOrAmbiguousAuthority() { .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); } + @Test + void authorityWorldResolutionUsesReadOutageClassificationBeforeSnapshotValidation() { + when(authorityService.listPointers()) + .thenThrow(new IllegalStateException("authority down")) + .thenReturn(null) + .thenReturn( + List.of(pointer("demo", "Demo World", "production", "Live Realm", 0L, 11L, 1L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(() -> catalog.resolveWorldFromAuthoritySnapshot("demo")) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); + assertThatThrownBy(() -> catalog.resolveWorldFromAuthoritySnapshot("demo")) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); + assertThatThrownBy(() -> catalog.resolveWorldFromAuthoritySnapshot("demo")) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .isNotInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); + } + @Test void publicProductionCardinalityKeepsReadOutageDistinctFromMalformedSnapshot() { when(authorityService.listPointers()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 2179abf7e9..fbae3ec005 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -919,6 +919,64 @@ void playMapsPointerAuthorityReadFailureBeforeAccountOrEntityAdmissionReads() { scriptEventPublisher); } + @Test + void playMapsMalformedDiscoveryPointerToAdmissionPointerUnavailableWithoutSideEffects() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 0L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()))); + PlayCommandHandler authorityBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authorityService), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + connectScopeSessionStore); + SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + authorityBackedHandler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @ParameterizedTest @ValueSource(strings = {"throw", "null"}) void playMapsDefaultRealmPointerReadFailureToAuthUnavailableWithoutAdmissionSideEffects( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index a96054e0ab..6a131d7e5f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2054,6 +2054,14 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti .isEqualTo( WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient, entityManagementClient); + + Mockito.clearInvocations(accountClient, entityManagementClient); + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } private WorldsCommandHandler authenticatedHandler( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 2271c98774..24b1d2344f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -24,6 +24,8 @@ import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; @@ -79,6 +81,55 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { && gameplayCommand.getCommandId().startsWith("worlds-"))); } + @Test + void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + when(authorityService.listPointers()) + .thenThrow(new IllegalStateException("pointer authority unavailable")) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 0L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.randomUUID(), + UUID.randomUUID()))); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + new GameplayWorldCatalog(authorityService), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); + TextCommandDispatchRequest request = + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), + false, + Optional.empty()); + + TextCommandInterpretationResult outageResult = scopedHandler.handle(request); + TextCommandInterpretationResult malformedResult = scopedHandler.handle(request); + + assertThat(outageResult.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(malformedResult.commandResult().errorCode()) + .isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + } + @Test void publishesCommandEventForGameplayScopedRealmsBrowse() { gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 22L, 2L, false))); @@ -490,7 +541,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() .setConnectScopeId("opaque-account-scope") - .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); when(accountClient.joinPublicProductionMembership( Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Instant.class))) @@ -644,11 +695,11 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() .setConnectScopeId("opaque-account-scope-1") - .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build(), IssueDirectTextConnectScopeResponse.newBuilder() .setConnectScopeId("opaque-account-scope-2") - .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); when(accountClient.joinPublicProductionMembership( Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Instant.class))) @@ -892,7 +943,7 @@ private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() .setConnectScopeId("opaque-account-scope") - .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); when(accountClient.joinPublicProductionMembership( Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Instant.class))) From 78c302758da67a9143d4c0669ca3ec4a4d638f7f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 09:30:56 +1300 Subject: [PATCH 046/105] Retain stable child catalog identities after owner-fixture reconciliation --- .../gamesession/support/TestGameplayWorldCatalogs.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index e790853544..197f70e66b 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -140,6 +140,12 @@ private static GameplayWorldCatalog.RealmView toRealmView( pointer.playableStateNamespaceId()); } + private static UUID stableId(String kind, long tenantId, String worldSlug, String realmSlug) { + return UUID.nameUUIDFromBytes( + ("firemud-test-catalog:" + kind + ":" + tenantId + ":" + worldSlug + ":" + realmSlug) + .getBytes(StandardCharsets.UTF_8)); + } + private static List toWorldViews( List worlds) { if (worlds == null) { From 6942e8d8b52bce1405467de40a39a8c973ec3fc9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 12:02:16 +1300 Subject: [PATCH 047/105] fix: bind gameplay discovery to public catalog and authority clock --- .../system-architecture-protocol-bridging.md | 4 +- .../command/text/GameplayWorldCatalog.java | 14 +- .../command/text/PlayCommandHandler.java | 7 +- .../text/GameplayWorldCatalogTest.java | 265 +++++++++++++++++- .../command/text/PlayCommandHandlerTest.java | 61 +++- .../text/WorldsCommandHandlerTest.java | 52 +++- .../support/TestGameplayWorldCatalogs.java | 15 +- 7 files changed, 387 insertions(+), 31 deletions(-) diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 8a9d243f50..53868c0ff9 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -277,7 +277,7 @@ Operators should interpret spikes in each layer’s metrics in this order when d - Buffers active input while the client remains connected and discards it if the TCP connection drops; the proxy never replays Telnet commands after a disconnect. - Telnet clients keep a sticky connection to the TCP Proxy Service; reconnection and session recovery are handled as described in [Reconnection Strategy](./system-architecture-reconnection.md). - Retained-edge upstream rebind is not an actual client-facing disconnect: Spring Cloud Gateway retains the client or proxy-facing gameplay WebSocket while performing ADR 0013's bounded rebind of a rebindable Game Session upstream, then closes with `1013/backend_unavailable` if recovery exhausts its window. Game Session revalidates the existing continuation binding, authorization, revocation, and target authority under the [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) contracts; it does not require fresh `LOGIN`, `JOIN`, or `PLAY`, and this hidden rebind does not trigger retained-context restoration or a fresh `LOOK`. -- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. Only after fresh admission completes, including current `LOGIN` identity checks and `PLAY` binding checks, does Game Session currently present/restore available retained semantic context on a binding-checked, best-effort basis in canonical order and perform a mandatory fresh authoritative `LOOK`; current post-`LOGOUT` suppression is not enforced, so this is not a complete restoration claim. Target restoration is unavailable after durable termination of the private context episode, character ownership/control transfer, or a missing, ambiguous, or not-exactly-current-and-non-terminated `resumeContextGeneration`; the target `LOGOUT` -> `LOGIN` -> `PLAY` path must durably fence the terminated binding before acknowledging `LOGOUT`, prove no private context replay, and then use the newer generation before any restoration. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical target contract, restoration status, and gaps. Structured status or optional semantic-extension state and any applicable prompt are additional projections, not alternatives to that `LOOK`. The Telnet path does not support hidden reattachment after its distinct Proxy -> Gateway gameplay WebSocket is lost: the proxy closes that Telnet connection rather than silently opening a fresh edge bridge behind the same client TCP socket. +- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. After fresh admission completes, including current `LOGIN` identity checks and `PLAY` binding checks, Game Session currently suppresses private retained-context reads on reconnect and after attempted `LOGOUT`, then renders a fresh authoritative `LOOK` after accepted `PLAY`; strict generation-fence enforcement and live recovery proof remain incomplete. Target restoration is unavailable after durable termination of the private context episode, character ownership/control transfer, or a missing, ambiguous, or not-exactly-current-and-non-terminated `resumeContextGeneration`; the target `LOGOUT` -> `LOGIN` -> `PLAY` path must durably fence the terminated binding before acknowledging `LOGOUT`, prove no private context replay, and then use the newer generation before any restoration. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical target contract, restoration status, and gaps. Structured status or optional semantic-extension state and any applicable prompt are additional projections, not alternatives to that `LOOK`. The Telnet path does not support hidden reattachment after its distinct Proxy -> Gateway gameplay WebSocket is lost: the proxy closes that Telnet connection rather than silently opening a fresh edge bridge behind the same client TCP socket. - The proxy defines a `NotifyDisconnect` gRPC event so the Game Session Service can react quickly when Telnet clients drop. This stream is best-effort and **at-least-once**, and Game Session treats it as an idempotent, advisory hint rather than a source of truth for session liveness. Consumers key handling off `{proxyConnectionId, disconnectSequence}` so late or duplicate events are safe to ignore. The behaviour-level contract for this stream is summarised in the **NotifyDisconnect Behavioral Contract** section of [Reconnection Strategy](./system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary), while the TCP Proxy Service design’s **Service Interactions** section remains canonical for message fields, retry windows, and envelope context. - Metrics are exported at `/actuator/prometheus` and tracing data is sent to the collector configured by `OTEL_ENDPOINT`. See [Logging & Monitoring](./system-architecture-logging-monitoring.md). - Environment-specific tuning guidance for the TCP Proxy Service (connection caps, envelope budgets, and production hardening) is documented in the TCP Proxy Service design under **Tuning TCP Proxy for Different Environments**. @@ -287,7 +287,7 @@ Operators should interpret spikes in each layer’s metrics in this order when d Resume affects gameplay identity and session binding, not transport continuity: - Neither the TCP Proxy nor Gateway replays prior outbound text or optional semantic-extension traffic onto a newly reconnected client transport. -- After a successful reconnect and `PLAY`, Game Session currently presents/restores an available bounded retained-context window using its available binding checks on a best-effort basis in canonical order, followed by a mandatory fresh authoritative `LOOK` derived from current state for the new transport. The current generation-qualified proof is incomplete. Target replay eligibility is restricted to the exact private semantic-context episode `{tenantId, playableStateNamespaceId, characterId, resumeContextGeneration}`. `bindingGeneration` remains the independent controller-ownership fence: an authorized reconnect, controller takeover, or runtime replacement carries the same `resumeContextGeneration` even when `bindingGeneration` advances. Durable termination for explicit logout, character ownership transfer, or lost replay authority occurs before any character-transfer acknowledgement and prevents restoration under that generation; a later authorized episode uses a newer generation. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the target contract, restoration status, and gaps. An applicable prompt, structured status, or newly generated optional extension state is an additional projection, not an alternative to `LOOK`; no transport backlog or exact-delivery replay is permitted. Empty or expired context produces no context output. +- After a successful reconnect and `PLAY`, current Game Session suppresses private retained-context replay on reconnect and after attempted `LOGOUT`, then renders a fresh authoritative `LOOK` derived from current state for the new transport. Strict generation-fence enforcement and live recovery proof remain incomplete. Target replay eligibility is restricted to the exact private semantic-context episode `{tenantId, playableStateNamespaceId, characterId, resumeContextGeneration}`. `bindingGeneration` remains the independent controller-ownership fence: an authorized reconnect, controller takeover, or runtime replacement carries the same `resumeContextGeneration` even when `bindingGeneration` advances. Durable termination for explicit logout, character ownership transfer, or lost replay authority occurs before any character-transfer acknowledgement and prevents restoration under that generation; a later authorized episode uses a newer generation. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the target contract, restoration status, and gaps. An applicable prompt, structured status, or newly generated optional extension state is an additional projection, not an alternative to `LOOK`; no transport backlog or exact-delivery replay is permitted. Empty or expired context produces no context output. - Allowed reconstruction output must be re-derived from current state at resume time; it must not be a byte-for-byte replay of previously queued outbound payloads from the old transport. - If previously delivered content and newly derived reconstruction happen to look similar to a human reader, that is acceptable only because the content was regenerated from current state, not because the transport backlog was replayed. - Prompt/status output remains a special output class rather than ordinary transcript text. Prompt lines should be coalesced after bursts of gameplay output and regenerated fresh for the new transport rather than copied into the reconnect transcript buffer. Current operator-default prompt behavior is surfaced in Game Session through `firemud.presentation.prompt.enabled`, `firemud.presentation.prompt.emit-after-reconnect-restore`, and `firemud.presentation.prompt.coalesce-window-ms`. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index f9d0059c7e..0e24d2d7ea 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -173,7 +173,7 @@ public Optional browseRealms(String worldSelector) { /** Reads the current realm catalog and records the exact response-local ordinal targets. */ public RealmDiscoverySnapshot readRealmDiscoverySnapshot(WorldView world) { Objects.requireNonNull(world, "world must not be null"); - return realmDiscoverySnapshot(world, visibleRealms(world)); + return realmDiscoverySnapshot(world, publicProductionRealms(world)); } /** Builds a REALMS snapshot whose ordinals match the filtered response entries. */ @@ -181,6 +181,8 @@ public RealmDiscoverySnapshot realmDiscoverySnapshot( WorldView world, List responseRealms) { Objects.requireNonNull(world, "world must not be null"); List visibleCatalogRealms = visibleRealms(world); + List publicCatalogRealms = + visibleCatalogRealms.stream().filter(RealmView::publicProductionRealm).toList(); List safeResponseRealms = List.copyOf(Objects.requireNonNull(responseRealms, "responseRealms must not be null")); if (safeResponseRealms.stream().anyMatch(realm -> !visibleCatalogRealms.contains(realm))) { @@ -198,9 +200,9 @@ public RealmDiscoverySnapshot realmDiscoverySnapshot( realm.pointerVersion(), realmTargetFingerprint(world, realm))); } - List catalogTargets = new ArrayList<>(visibleCatalogRealms.size()); - for (int index = 0; index < visibleCatalogRealms.size(); index++) { - RealmView realm = visibleCatalogRealms.get(index); + List catalogTargets = new ArrayList<>(publicCatalogRealms.size()); + for (int index = 0; index < publicCatalogRealms.size(); index++) { + RealmView realm = publicCatalogRealms.get(index); catalogTargets.add( new RealmOrdinalTarget( index + 1, @@ -674,6 +676,10 @@ public List visibleRealms(WorldView world) { return world.realms().stream().filter(RealmView::visible).toList(); } + private List publicProductionRealms(WorldView world) { + return visibleRealms(world).stream().filter(RealmView::publicProductionRealm).toList(); + } + public List visibleWorlds() { return readCatalogState().worlds().stream().filter(this::hasVisibleRealmEntries).toList(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index dd1167116a..3d08365390 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -4,7 +4,6 @@ import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import java.time.Clock; -import java.time.Instant; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -1259,7 +1258,8 @@ private WorldSelectorResolution resolvePlayWorld( } Optional maybeSnapshot; try { - maybeSnapshot = connectScopeSessionStore.worldsSnapshot(context, Instant.now()); + maybeSnapshot = + connectScopeSessionStore.worldsSnapshot(context, authorityEvaluationClock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new WorldSelectorResolution.Unavailable(); @@ -1308,7 +1308,8 @@ private RealmSelectorResolution resolvePlayRealm( Optional maybeSnapshot; try { maybeSnapshot = - connectScopeSessionStore.realmsSnapshot(context, tenantId, world.slug(), Instant.now()); + connectScopeSessionStore.realmsSnapshot( + context, tenantId, world.slug(), authorityEvaluationClock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new RealmSelectorResolution.Unavailable(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index e7e975c4e4..c98b95181b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -1024,7 +1024,7 @@ void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { } @Test - void realmSnapshotResolvesByExactTargetIdentityAfterResponseOrdinalChanges() { + void realmSnapshotFingerprintsPublicCatalogAndPreservesVisibleResponseTargets() { GameplayWorldCatalog.RealmView production = new GameplayWorldCatalog.RealmView( "production", @@ -1055,21 +1055,150 @@ void realmSnapshotResolvesByExactTargetIdentityAfterResponseOrdinalChanges() { 30L, UUID.fromString("a11df0f1-1b57-465e-9c4b-bb34f8153d31"), UUID.fromString("b2a958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.RealmView privateChanged = + new GameplayWorldCatalog.RealmView( + "preview", + "Preview Realm", + 7L, + 99L, + 99L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW", + 99L, + UUID.fromString("a11df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("b2a958e0-13a2-41d0-9c39-59a96cf31412")); GameplayWorldCatalog.WorldView original = new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(production, preview)); GameplayWorldCatalog.WorldView reordered = new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(preview, production)); + GameplayWorldCatalog.WorldView changedPrivateAndReordered = + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(privateChanged, production)); + GameplayWorldCatalog originalCatalog = GameplayWorldCatalog.forWorldViews(List.of(original)); GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(List.of(reordered)); GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = - GameplayWorldCatalog.forWorldViews(List.of(original)) - .realmDiscoverySnapshot(original, List.of(production, preview)); + originalCatalog.realmDiscoverySnapshot(original, List.of(production, preview)); + assertThat(snapshot.ordinalTargets()) + .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) + .containsExactly("production", "preview"); + assertThat(catalog.readRealmDiscoverySnapshot(reordered).catalogFingerprint()) + .isEqualTo(snapshot.catalogFingerprint()); + assertThat(catalog.readRealmDiscoverySnapshot(reordered).ordinalTargets()) + .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) + .containsExactly("production"); assertThat( catalog.resolveRealmSnapshotOrdinal( reordered, snapshot, snapshot.ordinalTargets().get(0))) .contains(production); - assertThat(catalog.readRealmDiscoverySnapshot(reordered).catalogFingerprint()) + assertThat( + catalog.resolveRealmSnapshotOrdinal( + reordered, snapshot, snapshot.ordinalTargets().get(1))) + .contains(preview); + + GameplayWorldCatalog changedPrivateCatalog = + GameplayWorldCatalog.forWorldViews(List.of(changedPrivateAndReordered)); + assertThat( + changedPrivateCatalog + .readRealmDiscoverySnapshot(changedPrivateAndReordered) + .catalogFingerprint()) + .isEqualTo(snapshot.catalogFingerprint()); + assertThat( + changedPrivateCatalog.resolveRealmSnapshotOrdinal( + changedPrivateAndReordered, snapshot, snapshot.ordinalTargets().get(1))) + .isEmpty(); + + GameplayWorldCatalog.RealmView hidden = + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 7L, + 13L, + 1L, + false, + false, + false, + "ISOLATED", + "ALLOW_NEW", + 31L, + UUID.randomUUID(), + UUID.randomUUID()); + assertThatThrownBy(() -> catalog.realmDiscoverySnapshot(original, List.of(hidden))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-visible"); + + GameplayWorldCatalog.RealmView reroutedProduction = + new GameplayWorldCatalog.RealmView( + production.slug(), + production.displayName(), + production.tenantId(), + production.gameInstanceId() + 1L, + production.pointerVersion() + 1L, + production.visible(), + production.publicProductionRealm(), + production.requiresCharacterSelection(), + production.stateScope(), + production.characterCreationPolicy(), + production.catalogRevision() + 1L, + production.realmId(), + production.playableStateNamespaceId()); + GameplayWorldCatalog.WorldView reroutedWorld = + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(reroutedProduction, preview)); + assertThat( + GameplayWorldCatalog.forWorldViews(List.of(reroutedWorld)) + .readRealmDiscoverySnapshot(reroutedWorld) + .catalogFingerprint()) .isNotEqualTo(snapshot.catalogFingerprint()); + + GameplayWorldCatalog.RealmView noLongerPublic = + new GameplayWorldCatalog.RealmView( + production.slug(), + production.displayName(), + production.tenantId(), + production.gameInstanceId(), + production.pointerVersion(), + production.visible(), + false, + production.requiresCharacterSelection(), + production.stateScope(), + production.characterCreationPolicy(), + production.catalogRevision() + 1L, + production.realmId(), + production.playableStateNamespaceId()); + GameplayWorldCatalog.WorldView policyChangedWorld = + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(noLongerPublic, preview)); + assertThat( + GameplayWorldCatalog.forWorldViews(List.of(policyChangedWorld)) + .readRealmDiscoverySnapshot(policyChangedWorld) + .catalogFingerprint()) + .isNotEqualTo(snapshot.catalogFingerprint()); + + GameplayWorldCatalog.RealmView otherTenantProduction = + new GameplayWorldCatalog.RealmView( + "other-live", + "Other Live Realm", + 8L, + 18L, + 2L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 31L, + UUID.fromString("c11df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("d2a958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.WorldView responseWorld = + new GameplayWorldCatalog.WorldView( + "demo", "Demo", List.of(production, otherTenantProduction, preview)); + GameplayWorldCatalog.RealmDiscoverySnapshot responseSnapshot = + GameplayWorldCatalog.forWorldViews(List.of(responseWorld)) + .realmDiscoverySnapshot(responseWorld, List.of(otherTenantProduction, production)); + assertThat(responseSnapshot.ordinalTargets()) + .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) + .containsExactly("other-live", "production"); } private static GameplayWorldCatalog.WorldView worldWithTargetRealm( @@ -1096,9 +1225,29 @@ private static GameplayWorldCatalog.WorldView worldWithTargetRealm( @Test void propertyCatalogRealmIdsIncludeWorldAndRemainDeterministic() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds( + GameplayCatalogProperties.World worldOne = propertyWorld("world-one", 7L, 11L, true); + worldOne.setRealms( List.of( - propertyWorld("world-one", 7L, 11L, true), propertyWorld("world-two", 7L, 12L, false))); + worldOne.getRealms().getFirst(), + propertyRealm( + "preview-one", 7L, 13L, false, GameplayCatalogProperties.RealmStateScope.ISOLATED), + propertyRealm( + "preview-two", + 7L, + 14L, + false, + GameplayCatalogProperties.RealmStateScope.ISOLATED))); + GameplayCatalogProperties.World worldTwo = propertyWorld("world-two", 7L, 12L, false); + worldTwo.setRealms( + List.of( + worldTwo.getRealms().getFirst(), + propertyRealm( + "preview-one", + 7L, + 15L, + false, + GameplayCatalogProperties.RealmStateScope.ISOLATED))); + properties.setWorlds(List.of(worldOne, worldTwo)); GameplayWorldCatalog catalog = TestGameplayWorldCatalogs.fromProperties(properties); GameplayWorldCatalog.RealmView firstRealm = @@ -1122,32 +1271,120 @@ void propertyCatalogRealmIdsIncludeWorldAndRemainDeterministic() { tenantCatalog .resolveRealm(tenantCatalog.resolveWorld("world-one").orElseThrow(), "shared") .orElseThrow(); + GameplayWorldCatalog.RealmView firstIsolatedRealm = + catalog + .resolveRealm(catalog.resolveWorld("world-one").orElseThrow(), "preview-one") + .orElseThrow(); + GameplayWorldCatalog.RealmView secondIsolatedRealm = + catalog + .resolveRealm(catalog.resolveWorld("world-one").orElseThrow(), "preview-two") + .orElseThrow(); + GameplayWorldCatalog.RealmView otherWorldIsolatedRealm = + catalog + .resolveRealm(catalog.resolveWorld("world-two").orElseThrow(), "preview-one") + .orElseThrow(); + GameplayCatalogProperties.World otherTenantIsolatedWorld = + propertyWorld("world-one", 8L, 16L, true); + otherTenantIsolatedWorld.getRealms().getFirst().setSlug("preview-one"); + otherTenantIsolatedWorld + .getRealms() + .getFirst() + .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); + GameplayWorldCatalog otherTenantIsolatedCatalog = + TestGameplayWorldCatalogs.fromProperties( + propertiesWithWorlds(List.of(otherTenantIsolatedWorld))); + GameplayWorldCatalog.RealmView otherTenantIsolatedRealm = + otherTenantIsolatedCatalog + .resolveRealm( + otherTenantIsolatedCatalog.resolveWorld("world-one").orElseThrow(), "preview-one") + .orElseThrow(); + GameplayCatalogProperties.World replacedSharedWorld = + propertyWorld("world-one", 7L, 111L, true); + GameplayWorldCatalog replacedSharedCatalog = + TestGameplayWorldCatalogs.fromProperties( + propertiesWithWorlds(List.of(replacedSharedWorld))); + GameplayCatalogProperties.World replacedIsolatedWorld = + propertyWorld("world-one", 7L, 112L, false); + replacedIsolatedWorld.getRealms().getFirst().setSlug("preview-one"); + replacedIsolatedWorld + .getRealms() + .getFirst() + .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); + GameplayWorldCatalog replacedIsolatedCatalog = + TestGameplayWorldCatalogs.fromProperties( + propertiesWithWorlds(List.of(replacedIsolatedWorld))); assertThat(firstRealm.realmId()).isNotEqualTo(secondRealm.realmId()); assertThat(otherTenantRealm.realmId()).isNotEqualTo(firstRealm.realmId()); assertThat(repeatedFirstRealm.realmId()).isEqualTo(firstRealm.realmId()); + assertThat(firstRealm.playableStateNamespaceId()) + .isEqualTo(secondRealm.playableStateNamespaceId()); + assertThat(firstRealm.playableStateNamespaceId()) + .isNotEqualTo(otherTenantRealm.playableStateNamespaceId()); assertThat(repeatedFirstRealm.playableStateNamespaceId()) .isEqualTo(firstRealm.playableStateNamespaceId()); + assertThat(firstIsolatedRealm.playableStateNamespaceId()) + .isNotEqualTo(firstRealm.playableStateNamespaceId()) + .isNotEqualTo(secondIsolatedRealm.playableStateNamespaceId()) + .isNotEqualTo(otherWorldIsolatedRealm.playableStateNamespaceId()) + .isNotEqualTo(otherTenantIsolatedRealm.playableStateNamespaceId()); + assertThat( + replacedSharedCatalog + .resolveRealm( + replacedSharedCatalog.resolveWorld("world-one").orElseThrow(), "shared") + .orElseThrow() + .playableStateNamespaceId()) + .isEqualTo(firstRealm.playableStateNamespaceId()); + assertThat( + replacedIsolatedCatalog + .resolveRealm( + replacedIsolatedCatalog.resolveWorld("world-one").orElseThrow(), "preview-one") + .orElseThrow() + .playableStateNamespaceId()) + .isEqualTo(firstIsolatedRealm.playableStateNamespaceId()); } private static GameplayCatalogProperties.World propertyWorld( String worldSlug, long tenantId, long gameInstanceId, boolean publicProductionRealm) { + GameplayCatalogProperties.Realm realm = + propertyRealm( + "shared", + tenantId, + gameInstanceId, + publicProductionRealm, + GameplayCatalogProperties.RealmStateScope.SHARED); + + GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); + world.setSlug(worldSlug); + world.setDisplayName(worldSlug); + world.setRealms(List.of(realm)); + return world; + } + + private static GameplayCatalogProperties.Realm propertyRealm( + String realmSlug, + long tenantId, + long gameInstanceId, + boolean publicProductionRealm, + GameplayCatalogProperties.RealmStateScope stateScope) { GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); - realm.setSlug("shared"); - realm.setDisplayName("Shared Realm"); + realm.setSlug(realmSlug); + realm.setDisplayName(realmSlug); realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setPointerVersion(1L); realm.setVisible(true); realm.setPublicProductionRealm(publicProductionRealm); - realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); + realm.setStateScope(stateScope); realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); + return realm; + } - GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); - world.setSlug(worldSlug); - world.setDisplayName(worldSlug); - world.setRealms(List.of(realm)); - return world; + private static GameplayCatalogProperties propertiesWithWorlds( + List worlds) { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(worlds); + return properties; } private CurrentAdmissionTarget currentAdmissionTarget() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index fbae3ec005..c9302dd45b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -453,6 +453,60 @@ void numericWorldPlayRejectsReorderedWorldSnapshotBeforeAdmissionSideEffects() { scriptEventPublisher); } + @Test + void numericWorldSelectorUsesInjectedAuthorityClockForSnapshotLookup() { + Instant authorityNow = Instant.parse("2000-01-02T03:04:05Z"); + Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); + DirectTextConnectScopeSessionStore scopeStore = + Mockito.spy(DirectTextConnectScopeSessionStore.inMemoryForTest()); + scopeStore.replaceWorldSnapshot( + context.sessionId(), + context.accountId(), + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + authorityNow); + PlayCommandHandler clockHandler = handlerWithClock(authorityClock, scopeStore); + + PlayCommandHandlingResult result = + clockHandler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("1"), "PLAY 1")); + + assertThat(result.commandResult().errorCode()).isNotEqualTo("CONNECT_SCOPE_MISMATCH"); + Mockito.verify(scopeStore).worldsSnapshot(context, authorityNow); + } + + @Test + void numericRealmSelectorUsesInjectedAuthorityClockForSnapshotLookup() { + Instant authorityNow = Instant.parse("2000-01-02T03:04:05Z"); + Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + worldCatalog.readRealmDiscoverySnapshot(world); + DirectTextConnectScopeSessionStore scopeStore = + Mockito.spy(DirectTextConnectScopeSessionStore.inMemoryForTest()); + scopeStore.replaceRealmSnapshot( + context, + "demo", + 22L, + "demo", + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + List.of(), + authorityNow); + PlayCommandHandler clockHandler = handlerWithClock(authorityClock, scopeStore); + + clockHandler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "999"), "PLAY demo 999")); + + Mockito.verify(scopeStore).realmsSnapshot(context, 22L, "demo", authorityNow); + } + @Test void numericWorldPlayTreatsUnrecognizedSecondSelectorAsCharacterWhenDefaultRealmIsUnambiguous() { SessionContext context = @@ -3249,6 +3303,11 @@ private static String evaluatedAtNow() { } private PlayCommandHandler handlerWithClock(Clock clock) { + return handlerWithClock(clock, connectScopeSessionStore); + } + + private PlayCommandHandler handlerWithClock( + Clock clock, DirectTextConnectScopeSessionStore scopeStore) { return new PlayCommandHandler( sessionAuthenticationService, sessionContextService, @@ -3262,7 +3321,7 @@ private PlayCommandHandler handlerWithClock(Clock clock) { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry, - connectScopeSessionStore, + scopeStore, clock); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 6a131d7e5f..e48aa6f2e8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -333,7 +333,7 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { } @Test - void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() { + void numericRealmSnapshotIgnoresPrivateReorderingButRejectsPublicRoutingChanges() { GameplayWorldCatalog.RealmView production = new GameplayWorldCatalog.RealmView( "production", @@ -375,12 +375,25 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() .setConnectScopeId("scope") .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(false)); + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), entityManagementClient, accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + scopeStore); assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) .isInstanceOfSatisfying( @@ -395,6 +408,37 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() new GameplayWorldCatalog.WorldView( "demo", "Demo World", List.of(preview, production)))); + assertThat(localHandler.browseCharacters("7", authenticatedSession(), "demo", "1")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + + Mockito.clearInvocations(accountClient, entityManagementClient); + GameplayWorldCatalog.RealmView reroutedProduction = + new GameplayWorldCatalog.RealmView( + production.slug(), + production.displayName(), + production.tenantId(), + production.gameInstanceId() + 1L, + production.pointerVersion() + 1L, + production.visible(), + production.publicProductionRealm(), + production.requiresCharacterSelection(), + production.stateScope(), + production.characterCreationPolicy(), + production.catalogRevision(), + production.realmId(), + production.playableStateNamespaceId()); + worlds.set( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(preview, reroutedProduction)))); + assertThat(localHandler.browseCharacters("7", authenticatedSession(), "demo", "1")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); Mockito.verifyNoInteractions(accountClient, entityManagementClient); @@ -554,7 +598,7 @@ void browseCharactersUsesIsolatedStateRealmRoster() { TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); GameplayWorldCatalog.WorldView selectedWorld = catalog.resolveWorld("demo").orElseThrow(); GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = - catalog.readRealmDiscoverySnapshot(selectedWorld); + catalog.realmDiscoverySnapshot(selectedWorld, catalog.visibleRealms(selectedWorld)); DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); scopeStore.replaceRealmSnapshot( @@ -944,7 +988,7 @@ void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { GameplayWorldCatalog catalog = TestGameplayWorldCatalogs.fromProperties(properties); GameplayWorldCatalog.WorldView selectedWorld = catalog.resolveWorld("preview").orElseThrow(); GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = - catalog.readRealmDiscoverySnapshot(selectedWorld); + catalog.realmDiscoverySnapshot(selectedWorld, catalog.visibleRealms(selectedWorld)); DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index 197f70e66b..daafaea6a9 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -191,8 +191,17 @@ private static GameplayWorldCatalog.RealmView toRealmView( characterCreationPolicy, 1L, stableId("realm", input.getTenantId(), worldSlug, input.getSlug()), - UUID.nameUUIDFromBytes( - ("test-namespace:" + input.getTenantId() + ":" + input.getGameInstanceId()) - .getBytes(StandardCharsets.UTF_8))); + namespaceId(stateScope, input.getTenantId(), worldSlug, input.getSlug())); + } + + private static UUID namespaceId( + String stateScope, long tenantId, String worldSlug, String realmSlug) { + String identity = + switch (stateScope) { + case "SHARED" -> "shared-tenant:" + tenantId; + case "ISOLATED" -> "isolated-realm:" + tenantId + ":" + worldSlug + ":" + realmSlug; + default -> "unresolved-realm:" + tenantId + ":" + worldSlug + ":" + realmSlug; + }; + return UUID.nameUUIDFromBytes(("test-namespace:" + identity).getBytes(StandardCharsets.UTF_8)); } } From 69a9c13767c48fa0ee020339e22a5e455186168c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 13:26:44 +1300 Subject: [PATCH 048/105] Align JOIN evidence and preserve typed pointer failures --- .../account-service/api-contracts.md | 2 + .../game-session-service/protocols.md | 10 +- .../realm-routing-and-playable-state.md | 2 +- .../text/AccountAuthorityEvidence.java | 92 +++++++++++++++ .../command/text/GameplayWorldCatalog.java | 5 +- .../command/text/PlayCommandHandler.java | 86 +++++--------- .../command/text/WorldsCommandHandler.java | 109 ++++++----------- ...essionWebSocketHandlerIntegrationTest.java | 46 +++++--- .../text/GameplayWorldCatalogTest.java | 29 ++++- .../command/text/PlayCommandHandlerTest.java | 92 ++++++++++++++- .../text/WorldsCommandHandlerTest.java | 111 +++++++++++++++++- .../WorldsTextCommandDispatchHandlerTest.java | 3 +- 12 files changed, 420 insertions(+), 167 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f6d986ca17..2bf9d10d0a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -62,6 +62,8 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that PENDING operation only while the retained scope remains valid; current scope validation returns `CONNECT_SCOPE_INVALID` on expiry rather than implementing readback-only recovery of uncertain PENDING outcomes, which remains #2848 work, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. Recovery after an unknown database commit outcome remains open under ADR 0025/#2848; exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof remain unclaimed. Game Session's direct-text `REALMS`/`JOIN` dispatch now uses the retained Account-issued scope and invokes that writer locally. The Gateway guard blocks external exposure of `POST /auth/bootstrap/join` pending accepted proof. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token issuance still does not enforce the emitted lifecycle state or generation and relies on `membershipExists`/`gameplayAdmissionAllowed`; its independent issuance baseline, fresh replay validation, and complete lease contract remain unproved. In contrast, Game Session text `PLAY` locally validates the fresh response's account/tenant identity, membership lifecycle, positive membership version and authority generation for an existing member, and evaluation time. It returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh entitlement and `allowPublicJoin` checks; other non-admitting states remain denials. These local checks do not prove positive live Account runtime reads, which remain fail closed pending typed caller/target authority. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +For `GetTenantMembershipForRuntime`, the current proto represents `membershipAuthorityGeneration` as `uint64`, and Game Session text `PLAY` requires a positive value for an existing member. This numeric representation and positivity check are implementation drift from the target opaque, equality-only generation semantics owned by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the current check does not implement the target generation comparison contract. + ### Current vs Target Export Lifecycle The current `GET /accounts/{accountId}/export` route and current `ExportAccount` implementation are synchronous Account/profile-local exports. They return only the Account-owned local result, have no cross-service required-owner fan-in, and do not satisfy ADR 0050; neither the route nor the current implementation may be described as a complete portable-data export. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 7f3d80ff74..9d0cb44560 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -82,7 +82,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. Current Game Session pointer snapshots carry numeric `tenantId` and `worldSlug` but no `tenantSlug`; local `WORLDS` renders only the bare world slug, and REALMS/JOIN/PLAY resolve that slug only when the current catalog does not contain the same world slug for multiple tenants. Bound menu indices remain available from their exact browse snapshot. This bare-slug shortcut is implementation drift, not proof of the target tenant-scoped stable selector or complete Telnet flow; `REALMS demo/demo` and `JOIN demo/demo` are target examples, not current accepted command forms. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot. `[character]` currently accepts a character name; a response-local character index is target-only and is not implemented. Current world and realm menu indices are bound to their exact connection-local response snapshots and catalog revisions, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. Current Game Session pointer snapshots carry numeric `tenantId` and `worldSlug` but no `tenantSlug`; local `WORLDS` renders only the bare world slug, and REALMS/JOIN/PLAY resolve that slug only when the current catalog does not contain the same world slug for multiple tenants. Bound world and realm menu indices remain available from their exact browse snapshots. This bare-slug shortcut is implementation drift, not proof of the target tenant-scoped stable selector or complete Telnet flow; `REALMS demo/demo` and `JOIN demo/demo` are target examples, not current accepted command forms. ### JOIN Translation and Status @@ -91,7 +91,7 @@ The canonical JOIN and membership-admission contract is defined in [Authenticati The Account membership operation is `JoinPublicProductionMembership`; the direct-text implementation is current and remains the sole membership writer, with Account-owned membership and audit/outbox consequences. Game Session translates `JOIN ` to that operation; it does not create membership locally or use another join writer. The first-party `Join & Play` action remains target-only. - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. -- Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the Account-issued scope in the shared Redis lobby record keyed by the stable numeric transport session ID. Atomic per-key compare-and-set preserves that request identity across retries and Game Session replacement. The record contains no raw JWT; the Account scope is bound to exact account/session identity and expires within its bounded lifetime. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. +- Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the Account-issued scope in the shared Redis lobby record keyed by the stable numeric transport session ID. Atomic per-key compare-and-set preserves that request identity across retries and Game Session replacement. The record contains no raw JWT; the Account scope is bound to exact account/session identity and expires within its bounded lifetime. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. The target contract requires Account to validate that target at the membership commit boundary (see [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative)); the current Account implementation checks the stored scope and target before the membership transaction, and no target-through-commit fence or commit-time target revalidation is proved. A client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. - An ambiguous or stale world/realm selector is a lobby-selection error: Game Session does not guess, does not invoke Account, and directs the client to refresh `WORLDS`/`REALMS`. A discovered scope that is stale or no longer matches the resolved `worldSlug`/`realmSlug` fails closed with the applicable scope or admission error rather than being translated to a newer target. - JOIN idempotency uses the canonical preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session generates and retains the server-side `requestId`, passes the verified local digest inputs and retained scope to Account, and reuses that identity for same-scope retries only while the retained scope remains valid. The Game Session client sends JOIN only while the retained Account scope is strictly unexpired; after an ambiguous transport result it checks again before channel reload and immediately before any same-request retry. If expiry is reached, it returns retryable `AUTH_UNAVAILABLE` without resending JOIN or minting a replacement scope/request; after local scope expiry cleanup, any readback or reconciliation for an uncertain Account operation remains Account-owned. Account replays an exact `{requestId, digest}` outcome and rejects a different digest as `IDEMPOTENCY_CONFLICT`; a new `requestId` is a distinct attempt after a new scope. @@ -120,7 +120,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` now validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; for a public-production missing or non-admitting membership, fresh entitlement and `allowPublicJoin` are evaluated before `JOIN_REQUIRED`. A valid non-public missing or non-admitting membership is classified as `WORLD_ACCESS_DENIED`, with the current player-facing result projected to generic selection guidance when its world is absent from public `WORLDS` discovery (see [Implementation Status](#implementation-status)). Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. Account owns the required independent issuance-time reread of both membership version and authority generation; the baseline proof and connect-token grant validation for private/playtest scopes remain incomplete under the [Account runtime contract](../account-service/runtime-and-data.md#membership-and-entitlement-authority). +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` validates membership lifecycle and authority generation alongside membership existence, admission permission, version, exact account/tenant identity, and a fresh evaluation timestamp. Existing-member admission requires `ACTIVE`; actionable `JOIN_REQUIRED` is limited to a public-production target where the fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports either missing (`MISSING`) membership or existing `INACTIVE` membership whose `gameplayAdmissionAllowed` is false. Fresh entitlement validation must also confirm gameplay availability and `allowPublicJoin=true`. Current Account proto encodes `membershipAuthorityGeneration` as `uint64`, and text `PLAY` requires it to be positive for an existing member; that representation and positivity check are implementation drift from the target opaque, exact-equality-only semantics owned by [Account Runtime and Data](../account-service/runtime-and-data.md#membership-and-entitlement-authority). A valid non-public missing or non-admitting membership is classified as `WORLD_ACCESS_DENIED`, with the current player-facing result projected to generic selection guidance when its world is absent from public `WORLDS` discovery (see [Implementation Status](#implementation-status)). Positive private/playtest grants require exact account, tenant, world, and realm identity, a positive grant version, and a fresh evaluation timestamp. Entitlement snapshots require exact tenant identity, positive entitlement version and billing sequence, and a fresh evaluation timestamp. For all three positive evidence types, freshness means no more than 15 seconds old and not in the future. Account owns the required independent issuance-time reread of both membership version and authority generation; the baseline proof and connect-token grant validation for private/playtest scopes remain incomplete under the [Account runtime contract](../account-service/runtime-and-data.md#membership-and-entitlement-authority). If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -159,7 +159,7 @@ PLAY 1 production 2 OK PLAY Entered world: Demo World / Live Realm as Sora ``` -In the target protocol, `PLAY demo/demo production 2` uses `demo/demo` as the stable `tenantSlug/worldSlug` selector from the exact snapshot, `production` as the tenant-local realm selector, and `2` as a response-local character index. The tenant/world-qualified selector and numeric character selection are target-only and are not implemented. Bound numeric world and realm menu selectors from the exact `WORLDS` and `REALMS` snapshots are implemented locally. `PLAY 1 1 Sora` illustrates target response-local world and realm indices with a character name. The full transcript remains target-state and is not executable end-to-end against the current implementation. Game Session resolves the selectors to `{tenantId, realmId}`, resolves the current admissible runtime target and stable namespace, then binds the internal session to the durable controller identity `{tenantId, playableStateNamespaceId, characterId}` while retaining the authenticated `accountId` as binding-owner evidence, `realmId` and `playableStateScope` as server-derived scope context, and `{gameInstanceId, regionId, regionEpoch}` as the current runtime fence where applicable; the player never selects `realmId`, `gameInstanceId`, `playableStateScope`, or a storage namespace directly. +In the target protocol, `PLAY demo/demo production 2` uses `demo/demo` as the stable `tenantSlug/worldSlug` selector from the exact snapshot, `production` as the tenant-local realm selector, and `2` as a response-local character index. The tenant/world-qualified selector and numeric character selection are target-only and are not implemented; current character selection accepts names only. Bound numeric world and realm menu selectors from the exact `WORLDS` and `REALMS` snapshots are implemented locally. `PLAY 1 1 Sora` illustrates target response-local world and realm indices with a character name. The full transcript remains target-state and is not executable end-to-end against the current implementation. Game Session resolves the selectors to `{tenantId, realmId}`, resolves the current admissible runtime target and stable namespace, then binds the internal session to the durable controller identity `{tenantId, playableStateNamespaceId, characterId}` while retaining the authenticated `accountId` as binding-owner evidence, `realmId` and `playableStateScope` as server-derived scope context, and `{gameInstanceId, regionId, regionEpoch}` as the current runtime fence where applicable; the player never selects `realmId`, `gameInstanceId`, `playableStateScope`, or a storage namespace directly. The Account Service returns canonical `AUTH_*` error codes such as `AUTH_INVALID_CREDENTIALS`, `AUTH_RETRY_LATER`, `AUTH_ACCOUNT_LOCKED`, and `AUTH_UNAVAILABLE`. Game Session translates them into protocol-level responses such as `ERROR INVALID_CREDENTIALS`, `ERROR RETRY_LATER`, and `ERROR AUTH_UNAVAILABLE` so Telnet and WebSocket clients can rely on stable error semantics while the human-readable message remains flexible. `AUTH_ACCOUNT_LOCKED` is the Account-owned safe outcome for an active durable lock; Game Session only translates it and does not decide or create the lock. It is exposed to the client only after sufficient identity proof or through the recovery path. The lock may be entered from verified or high-confidence compromise evidence, explicit Account security policy, or audited operator action; ordinary failed-login throttling uses `AUTH_RETRY_LATER`. @@ -170,7 +170,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – **target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current implementation's persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. -- `JOIN_REQUIRED` – after routing, authority, fresh entitlement, and public-policy checks pass, the selected public-production target has missing membership (`membershipExists=false`/`membershipLifecycleState=MISSING`) or existing non-admitting `INACTIVE` membership (`gameplayAdmissionAllowed=false`) for the account. The target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. Direct-text clients can issue the implemented `JOIN`; first-party `Join & Play` remains unavailable. Current `PLAY` consumes Account's lifecycle, membership-version, and authority-generation fields and does not infer `INACTIVE` from a boolean alone. Canonical eligibility and ordering remain owned by Authentication. +- `JOIN_REQUIRED` – after current routing and authority checks, a fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports either missing membership (`membershipExists=false`/`membershipLifecycleState=MISSING`) or existing `INACTIVE` membership (`gameplayAdmissionAllowed=false`); a fresh entitlement response must also confirm gameplay availability and `allowPublicJoin=true`. The selected target must be public production. This is actionable through the implemented direct-text `JOIN`; first-party `Join & Play` remains unavailable, and complete direct-text/Telnet proof remains open. A grant or cached discovery result is not a substitute. Current `PLAY` consumes Account's lifecycle, membership-version, and authority-generation fields and does not infer `INACTIVE` from a boolean alone. Canonical eligibility and ordering remain owned by Authentication. - `WORLD_ACCESS_DENIED` – current admission classification for a private, playtest, or other non-public target whose membership/admission predicate or existing grant check denies access; no public join action is offered. When the selected world is absent from public `WORLDS` discovery, current `PLAY` projects this definitive denial as generic `PLAY_SELECTION_REQUIRED` without target metadata (see [Implementation Status](#implementation-status)); publicly discoverable worlds retain `WORLD_ACCESS_DENIED`. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. 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 7c400efb58..b0fa510793 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 @@ -55,7 +55,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed; the canonical `JoinPublicProductionMembership` writer is implemented locally, including lifecycle-aware membership fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; `PLAY` admits only an exact safe active snapshot, while an eligible public-production request with missing or non-admitting membership may return non-actionable `JOIN_REQUIRED`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. Game Session's direct-text `JOIN` path now retrieves the retained REALMS scope/request state and invokes that Account writer; this local invocation and writer do not establish the complete first-party `Join & Play` or direct-text/Telnet flow. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed; the canonical `JoinPublicProductionMembership` writer is implemented locally, including lifecycle-aware membership fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; `PLAY` admits only an exact safe active snapshot and returns actionable `JOIN_REQUIRED` only when a fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports either missing (`MISSING`) membership or existing `INACTIVE` membership. Fresh entitlement validation must also confirm gameplay availability and `allowPublicJoin`. Other non-admitting lifecycle states remain denials. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. Game Session's direct-text `JOIN` path now retrieves the retained REALMS scope/request state and invokes that Account writer; this local invocation and writer do not establish complete direct-text/Telnet or first-party `Join & Play` proof. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java new file mode 100644 index 0000000000..f6467d24a6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamesession.command.text; + +import java.time.Clock; +import java.util.Objects; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; + +/** Shared validation for caller- and tenant-bound Account runtime authority snapshots. */ +final class AccountAuthorityEvidence { + private AccountAuthorityEvidence() {} + + static boolean hasMatchingAccountAndTenant( + String accountId, String tenantId, long expectedAccountId, long expectedTenantId) { + try { + return Long.parseLong(accountId) == expectedAccountId + && Long.parseLong(tenantId) == expectedTenantId; + } catch (NumberFormatException ex) { + return false; + } + } + + static boolean hasMatchingTenant(String tenantId, long expectedTenantId) { + try { + return Long.parseLong(tenantId) == expectedTenantId; + } catch (NumberFormatException ex) { + return false; + } + } + + static boolean isSafeMembershipSnapshot( + GetTenantMembershipForRuntimeResponse response, + long expectedAccountId, + long expectedTenantId, + Clock clock) { + Objects.requireNonNull(response, "response must not be null"); + if (!hasMatchingAccountAndTenant( + response.getAccountId(), response.getTenantId(), expectedAccountId, expectedTenantId) + || !AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), clock)) { + return false; + } + if (!response.getMembershipExists()) { + return "MISSING".equalsIgnoreCase(response.getMembershipLifecycleState()) + && !response.getGameplayAdmissionAllowed() + && response.getMembershipVersion() == 0L + && response.getMembershipAuthorityGeneration() == 0L; + } + if (response.getMembershipVersion() <= 0L + || response.getMembershipAuthorityGeneration() <= 0L) { + return false; + } + if (response.getGameplayAdmissionAllowed()) { + return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); + } + return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) + || "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); + } + + static boolean isActiveMembership( + GetTenantMembershipForRuntimeResponse response, + long expectedAccountId, + long expectedTenantId, + Clock clock) { + return response.getMembershipExists() + && response.getGameplayAdmissionAllowed() + && "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) + && isSafeMembershipSnapshot(response, expectedAccountId, expectedTenantId, clock); + } + + static boolean isValidEntitlement( + GetTenantEntitlementsForRuntimeResponse response, long expectedTenantId, Clock clock) { + return hasMatchingTenant(response.getTenantId(), expectedTenantId) + && response.getEntitlementVersion() > 0L + && response.getTenantBillingSequence() > 0L + && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), clock); + } + + static boolean isValidRealmAccessGrant( + GetRealmAccessGrantForRuntimeResponse response, + long expectedAccountId, + long expectedTenantId, + String expectedWorldSlug, + String expectedRealmSlug, + Clock clock) { + return response.getGrantVersion() > 0L + && hasMatchingAccountAndTenant( + response.getAccountId(), response.getTenantId(), expectedAccountId, expectedTenantId) + && expectedWorldSlug.equals(response.getWorldSlug()) + && expectedRealmSlug.equals(response.getRealmSlug()) + && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), clock); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 0e24d2d7ea..c384459fab 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; +import org.jooq.exception.DataAccessException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -854,7 +855,7 @@ private List loadAuthorityPointersForTenant(lo throw ex; } catch (AuthorityPointerUnavailableException ex) { throw ex; - } catch (RuntimeException ex) { + } catch (DataAccessException ex) { throw new AuthorityPointerReadUnavailableException( "Authoritative tenant gameplay pointer list is unavailable", ex); } @@ -1013,7 +1014,7 @@ private static List readAuthorityPointers( throw ex; } catch (AuthorityPointerUnavailableException ex) { throw ex; - } catch (RuntimeException ex) { + } catch (DataAccessException ex) { throw new AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable", ex); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 3d08365390..f58d02307e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -289,6 +289,9 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { null, null); } + if (realmSelection instanceof RealmSelectorResolution.PointerUnavailable) { + return admissionPointerUnavailableFailure(tenantTag, null); + } if (realmSelection instanceof RealmSelectorResolution.Stale) { return failure( "CONNECT_SCOPE_MISMATCH", @@ -327,6 +330,9 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { null, null); } + if (realmSelection instanceof RealmSelectorResolution.PointerUnavailable) { + return admissionPointerUnavailableFailure(tenantTag, null); + } if (realmSelection instanceof RealmSelectorResolution.Stale) { return failure( "CONNECT_SCOPE_MISMATCH", @@ -1149,30 +1155,8 @@ private boolean isSafeMembershipAuthorityResponse( GetTenantMembershipForRuntimeResponse response, SessionContext context, GameplayWorldCatalog.RealmView selectedRealm) { - if (!hasMatchingAuthorityIdentity( - response.getAccountId(), - response.getTenantId(), - context.accountId(), - selectedRealm.tenantId()) - || !AuthorityEvaluationFreshness.isFresh( - response.getEvaluatedAt(), authorityEvaluationClock)) { - return false; - } - if (!response.getMembershipExists()) { - return "MISSING".equalsIgnoreCase(response.getMembershipLifecycleState()) - && !response.getGameplayAdmissionAllowed() - && response.getMembershipVersion() == 0L - && response.getMembershipAuthorityGeneration() == 0L; - } - if (response.getMembershipVersion() <= 0L - || response.getMembershipAuthorityGeneration() <= 0L) { - return false; - } - if (response.getGameplayAdmissionAllowed()) { - return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); - } - return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) - || "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()); + return AccountAuthorityEvidence.isSafeMembershipSnapshot( + response, context.accountId(), selectedRealm.tenantId(), authorityEvaluationClock); } private boolean isValidGrant( @@ -1180,40 +1164,19 @@ private boolean isValidGrant( SessionContext context, GameplayWorldCatalog.WorldView world, GameplayWorldCatalog.RealmView realm) { - return response.getGrantVersion() > 0L - && hasMatchingAuthorityIdentity( - response.getAccountId(), response.getTenantId(), context.accountId(), realm.tenantId()) - && world.slug().equals(response.getWorldSlug()) - && realm.slug().equals(response.getRealmSlug()) - && AuthorityEvaluationFreshness.isFresh( - response.getEvaluatedAt(), authorityEvaluationClock); + return AccountAuthorityEvidence.isValidRealmAccessGrant( + response, + context.accountId(), + realm.tenantId(), + world.slug(), + realm.slug(), + authorityEvaluationClock); } private boolean isValidEntitlement( GetTenantEntitlementsForRuntimeResponse response, GameplayWorldCatalog.RealmView realm) { - return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) - && response.getEntitlementVersion() > 0L - && response.getTenantBillingSequence() > 0L - && AuthorityEvaluationFreshness.isFresh( - response.getEvaluatedAt(), authorityEvaluationClock); - } - - private boolean hasMatchingAuthorityIdentity( - String accountId, String tenantId, long expectedAccountId, long expectedTenantId) { - try { - return Long.parseLong(accountId) == expectedAccountId - && Long.parseLong(tenantId) == expectedTenantId; - } catch (NumberFormatException ex) { - return false; - } - } - - private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { - try { - return Long.parseLong(tenantId) == expectedTenantId; - } catch (NumberFormatException ex) { - return false; - } + return AccountAuthorityEvidence.isValidEntitlement( + response, realm.tenantId(), authorityEvaluationClock); } private boolean maybeRecordFreshEntryFallback( @@ -1318,8 +1281,14 @@ private RealmSelectorResolution resolvePlayRealm( return new RealmSelectorResolution.Stale(); } DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = - gameplayWorldCatalog.readRealmDiscoverySnapshot(world); + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; + try { + currentRealmCatalog = gameplayWorldCatalog.readRealmDiscoverySnapshot(world); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return new RealmSelectorResolution.Unavailable(); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return new RealmSelectorResolution.PointerUnavailable(); + } if (!snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { return new RealmSelectorResolution.Stale(); } @@ -1367,7 +1336,8 @@ private sealed interface RealmSelectorResolution RealmSelectorResolution.NoSelection, RealmSelectorResolution.Invalid, RealmSelectorResolution.Stale, - RealmSelectorResolution.Unavailable { + RealmSelectorResolution.Unavailable, + RealmSelectorResolution.PointerUnavailable { record Selected(GameplayWorldCatalog.RealmView realm) implements RealmSelectorResolution {} record NoSelection() implements RealmSelectorResolution {} @@ -1377,6 +1347,8 @@ record Invalid() implements RealmSelectorResolution {} record Stale() implements RealmSelectorResolution {} record Unavailable() implements RealmSelectorResolution {} + + record PointerUnavailable() implements RealmSelectorResolution {} } private Optional resolveSelection( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index de7d3e6574..5fda191e2e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -43,6 +43,7 @@ public class WorldsCommandHandler { private final EntityManagementClient entityManagementClient; private final AccountClient accountClient; private final DirectTextConnectScopeSessionStore connectScopeSessionStore; + private final Clock clock; @Autowired public WorldsCommandHandler( @@ -50,6 +51,20 @@ public WorldsCommandHandler( EntityManagementClient entityManagementClient, AccountClient accountClient, DirectTextConnectScopeSessionStore connectScopeSessionStore) { + this( + worldCatalog, + entityManagementClient, + accountClient, + connectScopeSessionStore, + Clock.systemUTC()); + } + + WorldsCommandHandler( + GameplayWorldCatalog worldCatalog, + EntityManagementClient entityManagementClient, + AccountClient accountClient, + DirectTextConnectScopeSessionStore connectScopeSessionStore, + Clock clock) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); this.entityManagementClient = Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); @@ -57,6 +72,7 @@ public WorldsCommandHandler( this.connectScopeSessionStore = Objects.requireNonNull( connectScopeSessionStore, "connectScopeSessionStore must not be null"); + this.clock = Objects.requireNonNull(clock, "clock must not be null"); } WorldsCommandHandler( @@ -66,6 +82,7 @@ public WorldsCommandHandler( Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.accountClient = null; this.connectScopeSessionStore = null; + this.clock = Clock.systemUTC(); } public WorldsViewOutput browseView() { @@ -90,7 +107,7 @@ public WorldsViewOutput browseView( maybeCaller.map(SessionContext::accountId).orElse(0L), snapshot.catalogFingerprint(), snapshot.ordinalTargets(), - Instant.now()); + clock.instant()); return snapshot.output(); } @@ -183,7 +200,7 @@ public RealmBrowseResult browseRealms( } catch (DateTimeParseException ex) { return RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - if (!expiresAt.isAfter(Instant.now())) { + if (!expiresAt.isAfter(clock.instant())) { return RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } issuedScopes.add( @@ -219,7 +236,7 @@ public RealmBrowseResult browseRealms( realmSnapshot.catalogFingerprint(), realmSnapshot.ordinalTargets(), issuedScopes, - Instant.now()); + clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); @@ -245,7 +262,7 @@ private WorldSelectorResolution resolveLobbyWorld( } Optional maybeSnapshot; try { - maybeSnapshot = connectScopeSessionStore.worldsSnapshot(caller, Instant.now()); + maybeSnapshot = connectScopeSessionStore.worldsSnapshot(caller, clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new WorldSelectorResolution.Unavailable(); @@ -320,7 +337,7 @@ private RealmSelectorResolution resolveLobbyRealm( try { maybeSnapshot = connectScopeSessionStore.realmsSnapshot( - caller, worldTenantId(world), world.slug(), Instant.now()); + caller, worldTenantId(world), world.slug(), clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new RealmSelectorResolution.Unavailable(); @@ -364,7 +381,7 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( try { maybeSnapshot = connectScopeSessionStore.realmsSnapshot( - caller, worldTenantId(world), world.slug(), Instant.now()); + caller, worldTenantId(world), world.slug(), clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new RealmSelectorResolution.Unavailable(); @@ -417,7 +434,7 @@ private boolean isBoundToCurrentRealmSnapshot( try { maybeSnapshot = connectScopeSessionStore.realmsSnapshot( - caller, worldTenantId(world), world.slug(), Instant.now()); + caller, worldTenantId(world), world.slug(), clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return false; @@ -477,47 +494,6 @@ record Stale() implements WorldSelectorResolution {} record Unavailable() implements WorldSelectorResolution {} } - private boolean isValidEntitlement( - GetTenantEntitlementsForRuntimeResponse response, GameplayWorldCatalog.RealmView realm) { - return hasMatchingTenantId(response.getTenantId(), realm.tenantId()) - && response.getEntitlementVersion() > 0L - && response.getTenantBillingSequence() > 0L - && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); - } - - private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { - try { - return Long.parseLong(tenantId) == expectedTenantId; - } catch (NumberFormatException ex) { - return false; - } - } - - private boolean isValidActiveMembership( - GetTenantMembershipForRuntimeResponse response, - SessionContext sessionContext, - GameplayWorldCatalog.RealmView realm) { - return "ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) - && response.getMembershipVersion() > 0L - && response.getMembershipAuthorityGeneration() > 0L - && hasMatchingAuthorityIdentity( - response.getAccountId(), - response.getTenantId(), - sessionContext.accountId(), - realm.tenantId()) - && AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC()); - } - - private boolean hasMatchingAuthorityIdentity( - String accountId, String tenantId, long expectedAccountId, long expectedTenantId) { - try { - return Long.parseLong(accountId) == expectedAccountId - && Long.parseLong(tenantId) == expectedTenantId; - } catch (NumberFormatException ex) { - return false; - } - } - private boolean isAuthorityUnavailable(String code) { return AuthenticationErrorCodes.UNAVAILABLE.equalsIgnoreCase(code) || "UNAVAILABLE".equalsIgnoreCase(code); @@ -573,7 +549,7 @@ public JoinMembershipResult joinPublicProductionMembership( try { maybeRealmSnapshot = connectScopeSessionStore.realmsSnapshot( - sessionContext, worldTenantId(world), world.slug(), Instant.now()); + sessionContext, worldTenantId(world), world.slug(), clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); @@ -591,7 +567,7 @@ public JoinMembershipResult joinPublicProductionMembership( try { maybeJoinScope = connectScopeSessionStore.publicProductionScopeForJoin( - sessionContext, worldSelector, worldTenantId(world), world.slug(), Instant.now()); + sessionContext, worldSelector, worldTenantId(world), world.slug(), clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); @@ -776,6 +752,8 @@ public CharacterBrowseResult browseCharacters( currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } RealmSelectorResolution realmSelection = resolveLobbyRealm(sessionContext, world, realmSelector, currentRealmCatalog); @@ -912,7 +890,8 @@ private CharacterBrowseAuthorization authorizePublicCharacterBrowse( if (!membershipResponse.getGameplayAdmissionAllowed()) { return CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; } - if (!isValidActiveMembership(membershipResponse, sessionContext, realm)) { + if (!AccountAuthorityEvidence.isActiveMembership( + membershipResponse, sessionContext.accountId(), realm.tenantId(), clock)) { return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; } return CharacterBrowseAuthorization.AUTHORIZED; @@ -946,7 +925,8 @@ private PublicEntitlementAuthorization authorizePublicCharacterEntitlement( : CharacterBrowseAuthorization.DENIED, false); } - if (!isValidEntitlement(entitlementResponse, realm)) { + if (!AccountAuthorityEvidence.isValidEntitlement( + entitlementResponse, realm.tenantId(), clock)) { return new PublicEntitlementAuthorization( CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE, false); } @@ -962,29 +942,8 @@ private boolean isValidMembershipAuthoritySnapshot( GetTenantMembershipForRuntimeResponse response, SessionContext sessionContext, GameplayWorldCatalog.RealmView realm) { - if (!hasMatchingAuthorityIdentity( - response.getAccountId(), - response.getTenantId(), - sessionContext.accountId(), - realm.tenantId()) - || !AuthorityEvaluationFreshness.isFresh(response.getEvaluatedAt(), Clock.systemUTC())) { - return false; - } - if (!response.getMembershipExists()) { - return "MISSING".equalsIgnoreCase(response.getMembershipLifecycleState()) - && !response.getGameplayAdmissionAllowed() - && response.getMembershipVersion() == 0L - && response.getMembershipAuthorityGeneration() == 0L; - } - if (response.getMembershipVersion() <= 0L - || response.getMembershipAuthorityGeneration() <= 0L) { - return false; - } - if ("ACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState())) { - return true; - } - return "INACTIVE".equalsIgnoreCase(response.getMembershipLifecycleState()) - && !response.getGameplayAdmissionAllowed(); + return AccountAuthorityEvidence.isSafeMembershipSnapshot( + response, sessionContext.accountId(), realm.tenantId(), clock); } private boolean hasCompleteSelectedRealmPointerEvidence(GameplayWorldCatalog.RealmView realm) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 99fd69e203..2fe8fc23d2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -258,32 +258,44 @@ void setUp() { .setAuthToken("stub-token") .setAccountId("123") .build()); - org.mockito.Mockito.doReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()) + org.mockito.Mockito.doAnswer( + invocation -> + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(true) + .setMembershipLifecycleState("ACTIVE") + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()) .when(accountClient) .getTenantMembershipForRuntime( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.nullable(String.class)); - org.mockito.Mockito.doReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()) + org.mockito.Mockito.doAnswer( + invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()) .when(accountClient) .getTenantEntitlementsForRuntime( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.nullable(String.class)); + org.mockito.Mockito.doAnswer( + invocation -> + net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-" + java.util.UUID.randomUUID()) + .setConnectScopeExpiresAt(java.time.Instant.now().plusSeconds(300).toString()) + .build()) + .when(accountClient) + .issueDirectTextConnectScope(any(), any()); org.mockito.Mockito.doReturn( ListCharactersByAccountResponse.newBuilder() .addCharacters( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index c98b95181b..262e7867d7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -353,7 +354,7 @@ void visibleWorldsTreatsRealmSlugCaseCollisionsAsAmbiguous() { @Test void pointerReadFailureIsDistinctFromMalformedOrAmbiguousAuthority() { when(authorityService.listPointers()) - .thenThrow(new IllegalStateException("authority down")) + .thenThrow(new DataAccessException("authority down")) .thenReturn(null); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); @@ -363,10 +364,19 @@ void pointerReadFailureIsDistinctFromMalformedOrAmbiguousAuthority() { .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); } + @Test + void unexpectedPointerReadDefectPropagates() { + IllegalStateException defect = new IllegalStateException("unexpected mapping defect"); + when(authorityService.listPointers()).thenThrow(defect); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::readDiscoverySnapshot).isSameAs(defect); + } + @Test void authorityWorldResolutionUsesReadOutageClassificationBeforeSnapshotValidation() { when(authorityService.listPointers()) - .thenThrow(new IllegalStateException("authority down")) + .thenThrow(new DataAccessException("authority down")) .thenReturn(null) .thenReturn( List.of(pointer("demo", "Demo World", "production", "Live Realm", 0L, 11L, 1L))); @@ -384,7 +394,7 @@ void authorityWorldResolutionUsesReadOutageClassificationBeforeSnapshotValidatio @Test void publicProductionCardinalityKeepsReadOutageDistinctFromMalformedSnapshot() { when(authorityService.listPointers()) - .thenThrow(new IllegalStateException("authority down")) + .thenThrow(new DataAccessException("authority down")) .thenReturn( List.of(pointer("demo", "Demo World", "production", "Live Realm", 0L, 11L, 1L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); @@ -439,13 +449,24 @@ void matchesCurrentAdmissionPointerReturnsFalseForSelectorCollision() { void matchesCurrentAdmissionPointerPropagatesTenantReadOutage() { CurrentAdmissionTarget target = currentAdmissionTarget(); when(authorityService.listPointersByTenant(1L)) - .thenThrow(new IllegalStateException("authority down")); + .thenThrow(new DataAccessException("authority down")); assertThatThrownBy( () -> target.catalog().matchesCurrentAdmissionPointer(target.world(), target.realm())) .isInstanceOf(GameplayWorldCatalog.AuthorityPointerReadUnavailableException.class); } + @Test + void matchesCurrentAdmissionPointerPropagatesUnexpectedTenantReadDefect() { + CurrentAdmissionTarget target = currentAdmissionTarget(); + IllegalStateException defect = new IllegalStateException("unexpected mapping defect"); + when(authorityService.listPointersByTenant(1L)).thenThrow(defect); + + assertThatThrownBy( + () -> target.catalog().matchesCurrentAdmissionPointer(target.world(), target.realm())) + .isSameAs(defect); + } + @Test void reverseRuntimeLookupFailsClosedWhenMultipleVisibleRealmsShareRuntimeTarget() { when(authorityService.listPointers()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index c9302dd45b..3f38f61d84 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -44,6 +44,7 @@ import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -507,6 +508,77 @@ void numericRealmSelectorUsesInjectedAuthorityClockForSnapshotLookup() { Mockito.verify(scopeStore).realmsSnapshot(context, 22L, "demo", authorityNow); } + @ParameterizedTest + @ValueSource(strings = {"read-unavailable", "malformed"}) + void numericRealmSelectorMapsPointerExceptionsToTypedFailures(String pointerFailure) { + Instant authorityNow = Instant.parse("2030-05-06T07:08:09Z"); + Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayWorldCatalog baseCatalog = worldCatalog; + GameplayWorldCatalog.DiscoverySnapshot worldSnapshot = baseCatalog.readDiscoverySnapshot(); + GameplayWorldCatalog.WorldView world = baseCatalog.resolveWorld("demo").orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot realmSnapshot = + baseCatalog.readRealmDiscoverySnapshot(world); + DirectTextConnectScopeSessionStore scopeStore = + DirectTextConnectScopeSessionStore.inMemoryForTest(); + scopeStore.replaceRealmSnapshot( + context, + "demo", + 22L, + "demo", + realmSnapshot.catalogFingerprint(), + realmSnapshot.ordinalTargets(), + List.of(), + authorityNow); + GameplayWorldCatalog catalog = Mockito.spy(baseCatalog); + Mockito.doReturn(worldSnapshot).when(catalog).readDiscoverySnapshot(); + if ("read-unavailable".equals(pointerFailure)) { + Mockito.doThrow( + new GameplayWorldCatalog.AuthorityPointerReadUnavailableException("read failed")) + .when(catalog) + .readRealmDiscoverySnapshot(Mockito.any(GameplayWorldCatalog.WorldView.class)); + } else { + Mockito.doThrow(new GameplayWorldCatalog.AuthorityPointerUnavailableException("malformed")) + .when(catalog) + .readRealmDiscoverySnapshot(Mockito.any(GameplayWorldCatalog.WorldView.class)); + } + PlayCommandHandler pointerFailureHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + catalog, + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry, + scopeStore, + authorityClock); + + PlayCommandHandlingResult result = + pointerFailureHandler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "1"), "PLAY demo 1")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo( + "read-unavailable".equals(pointerFailure) + ? GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE + : "ADMISSION_POINTER_UNAVAILABLE"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void numericWorldPlayTreatsUnrecognizedSecondSelectorAsCharacterWhenDefaultRealmIsUnambiguous() { SessionContext context = @@ -886,7 +958,7 @@ void playMapsFinalPointerReadOutageToAuthUnavailableWithoutAdmissionSideEffects( invocation -> { pointerReads.incrementAndGet(); if ("throw".equals(failureMode)) { - throw new IllegalStateException("authority down on final read"); + throw new DataAccessException("authority down on final read"); } return null; }); @@ -937,7 +1009,7 @@ void playMapsFinalPointerReadOutageToAuthUnavailableWithoutAdmissionSideEffects( void playMapsPointerAuthorityReadFailureBeforeAccountOrEntityAdmissionReads() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - when(authorityService.listPointers()).thenThrow(new IllegalStateException("authority down")); + when(authorityService.listPointers()).thenThrow(new DataAccessException("authority down")); PlayCommandHandler authorityBackedHandler = new PlayCommandHandler( sessionAuthenticationService, @@ -1045,7 +1117,7 @@ void playMapsDefaultRealmPointerReadFailureToAuthUnavailableWithoutAdmissionSide return List.of(admissionPointer(1L)); } if ("throw".equals(failureMode)) { - throw new IllegalStateException("authority down during default realm resolution"); + throw new DataAccessException("authority down during default realm resolution"); } return null; }); @@ -2980,7 +3052,16 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { } @ParameterizedTest - @ValueSource(strings = {"stale", "future", "wrong-account", "missing-generation"}) + @ValueSource( + strings = { + "stale", + "future", + "wrong-account", + "wrong-tenant", + "unknown-lifecycle", + "inactive-admitting", + "missing-generation" + }) void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); @@ -2998,6 +3079,9 @@ void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { case "stale" -> response.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); case "future" -> response.setEvaluatedAt(Instant.now().plusSeconds(1).toString()); case "wrong-account" -> response.setAccountId("999"); + case "wrong-tenant" -> response.setTenantId("23"); + case "unknown-lifecycle" -> response.setMembershipLifecycleState("UNKNOWN"); + case "inactive-admitting" -> response.setMembershipLifecycleState("INACTIVE"); case "missing-generation" -> response.setMembershipAuthorityGeneration(0L); default -> throw new IllegalArgumentException(invalidEvidence); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index e48aa6f2e8..d1616ae322 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2,8 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -30,6 +32,7 @@ import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -739,6 +742,102 @@ void browseCharactersReturnsJoinRequiredForPublicInactiveMemberWithoutReadingEnt Mockito.verifyNoInteractions(entityManagementClient); } + @Test + void browseCharactersUsesInjectedClockForFreshCallerBoundAuthorityEvidence() { + Instant authorityNow = Instant.parse("2030-05-06T07:08:09Z"); + Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); + GameplayCatalogProperties properties = publicProductionProperties(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + authenticatedHandler(properties, accountClient, authorityClock); + List evaluatedAtValues = + List.of( + authorityNow, + authorityNow.minusSeconds(15), + authorityNow.minusSeconds(15).minusNanos(1), + authorityNow.plusNanos(1)); + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); + + for (int index = 0; index < evaluatedAtValues.size(); index++) { + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + activeMembership().toBuilder() + .setEvaluatedAt(evaluatedAtValues.get(index).toString()) + .build()); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime( + Mockito.anyString(), Mockito.anyString())) + .thenReturn( + publicEntitlement(true).toBuilder().setEvaluatedAt(authorityNow.toString()).build()); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + if (index < 2) { + assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + } else { + assertThat(result) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + } + } + + for (int index = 0; index < evaluatedAtValues.size(); index++) { + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + activeMembership().toBuilder().setEvaluatedAt(authorityNow.toString()).build()); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime( + Mockito.anyString(), Mockito.anyString())) + .thenReturn( + publicEntitlement(true).toBuilder() + .setEvaluatedAt(evaluatedAtValues.get(index).toString()) + .build()); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + if (index < 2) { + assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + } else { + assertThat(result) + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); + } + } + } + + @Test + void browseCharactersMapsMalformedRealmDiscoveryPointerToAdmissionPointerUnavailable() { + GameplayCatalogProperties properties = publicProductionProperties(); + GameplayWorldCatalog baseCatalog = TestGameplayWorldCatalogs.fromProperties(properties); + GameplayWorldCatalog.DiscoverySnapshot snapshot = baseCatalog.readDiscoverySnapshot(); + GameplayWorldCatalog catalog = Mockito.spy(baseCatalog); + Mockito.doReturn(snapshot).when(catalog).readDiscoverySnapshot(); + Mockito.doThrow(new GameplayWorldCatalog.AuthorityPointerUnavailableException("malformed")) + .when(catalog) + .readRealmDiscoverySnapshot(Mockito.any(GameplayWorldCatalog.WorldView.class)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, + entityManagementClient, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result) + .isEqualTo( + WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + } + @Test void browseCharactersFailsClosedForUnknownPublicMembershipLifecycleWithoutReadingEntityRoster() { assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "UNKNOWN")); @@ -2054,7 +2153,7 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti .thenAnswer( invocation -> { if (unavailable.get()) { - throw new IllegalStateException("pointer authority unavailable"); + throw new DataAccessException("pointer authority unavailable"); } return List.of(authorityPointer("demo", "production", 22L, 1L, true)); }); @@ -2117,6 +2216,16 @@ private WorldsCommandHandler authenticatedHandler( DirectTextConnectScopeSessionStore.inMemoryForTest()); } + private WorldsCommandHandler authenticatedHandler( + GameplayCatalogProperties properties, AccountClient accountClient, Clock clock) { + return new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(properties), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest(), + clock); + } + private GameplayAdmissionPointerSnapshot authorityPointer( String worldSlug, String realmSlug, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 24b1d2344f..c01fd5dbc7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -86,7 +87,7 @@ void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); when(authorityService.listPointers()) - .thenThrow(new IllegalStateException("pointer authority unavailable")) + .thenThrow(new DataAccessException("pointer authority unavailable")) .thenReturn( List.of( new GameplayAdmissionPointerSnapshot( From d519c6babe813108839d40ffb232b3c1f38b7f5e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 13:43:51 +1300 Subject: [PATCH 049/105] Use caller clock for direct-text scope pruning --- .../command/text/WorldsCommandHandler.java | 3 +- .../DirectTextConnectScopeSessionStore.java | 23 ++-- ...irectTextConnectScopeSessionStoreTest.java | 2 +- ...irectTextConnectScopeSessionStoreTest.java | 115 ++++++++++++++++-- 4 files changed, 123 insertions(+), 20 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 5fda191e2e..6fdb56f4d9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -219,7 +219,8 @@ public RealmBrowseResult browseRealms( return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); } try { - connectScopeSessionStore.clearWorldScopes(sessionContext, worldTenantId(world), world.slug()); + connectScopeSessionStore.clearWorldScopes( + sessionContext, worldTenantId(world), world.slug(), clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index b9d3eb75aa..3e2a6234db 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -140,15 +140,16 @@ public void replaceWorldScopes( String requestedWorldSelector, long tenantId, String canonicalWorldSlug, - List scopes) { + List scopes, + Instant now) { Objects.requireNonNull(caller, "caller must not be null"); requireCallerIdentity(caller); + Objects.requireNonNull(now, "now must not be null"); String requestedSelector = normalizeSelector(requestedWorldSelector); String worldSlug = normalizeSelector(canonicalWorldSlug); if (requestedSelector == null || worldSlug == null || tenantId <= 0L) { throw new IllegalArgumentException("world selection identity must be complete"); } - Instant now = Instant.now(); List safeScopes = List.copyOf(Objects.requireNonNull(scopes, "scopes must not be null")); safeScopes.forEach(scope -> validateScopeIdentity(caller, tenantId, scope)); @@ -192,9 +193,11 @@ public void replaceWorldScopes( SessionContext caller, String requestedWorldSelector, String canonicalWorldSlug, - List scopes) { + List scopes, + Instant now) { + Objects.requireNonNull(now, "now must not be null"); long tenantId = uniqueTenantId(scopes); - replaceWorldScopes(caller, requestedWorldSelector, tenantId, canonicalWorldSlug, scopes); + replaceWorldScopes(caller, requestedWorldSelector, tenantId, canonicalWorldSlug, scopes, now); } /** Atomically stores the exact REALMS response and any Account scopes it produced. */ @@ -338,15 +341,17 @@ public Optional realmsSnapshot( snapshot.ordinalTargets())); } - public void clearWorldScopes(SessionContext caller, long tenantId, String canonicalWorldSlug) { + public void clearWorldScopes( + SessionContext caller, long tenantId, String canonicalWorldSlug, Instant now) { Objects.requireNonNull(caller, "caller must not be null"); requireCallerIdentity(caller); + Objects.requireNonNull(now, "now must not be null"); String worldSlug = normalizeSelector(canonicalWorldSlug); if (worldSlug == null || tenantId <= 0L) { return; } String worldKey = worldIdentityKey(tenantId, worldSlug); - long nowMillis = Instant.now().toEpochMilli(); + long nowMillis = now.toEpochMilli(); mutate( caller.sessionId(), nowMillis, @@ -376,7 +381,9 @@ record = LobbyRecord.empty(caller.sessionId()); }); } - public void clearWorldScopes(SessionContext caller, String canonicalWorldSlug) { + public void clearWorldScopes(SessionContext caller, String canonicalWorldSlug, Instant now) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(now, "now must not be null"); String worldSlug = normalizeSelector(canonicalWorldSlug); if (worldSlug == null) { return; @@ -392,7 +399,7 @@ public void clearWorldScopes(SessionContext caller, String canonicalWorldSlug) { .distinct() .toList(); if (matches.size() == 1) { - clearWorldScopes(caller, matches.getFirst().tenantId(), matches.getFirst().worldSlug()); + clearWorldScopes(caller, matches.getFirst().tenantId(), matches.getFirst().worldSlug(), now); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java index 340451eeb0..74f621cadc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java @@ -147,7 +147,7 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws assertThat(requestIds).containsOnly(requestIds.getFirst()); DirectTextConnectScopeSessionStore replacement = replacementInstances.getLast(); - replacement.clearWorldScopes(caller, 22L, "demo-world"); + replacement.clearWorldScopes(caller, 22L, "demo-world", Instant.now()); assertThat( firstInstance.publicProductionScopeForJoin( caller, "1", 22L, "demo-world", Instant.now())) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index e258fa4074..3d840f6efc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -31,7 +31,8 @@ void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { "1", 22L, "demo-world", - List.of(scopedRealm(caller, "demo-world", "scope-secret", expiry))); + List.of(scopedRealm(caller, "demo-world", "scope-secret", expiry)), + now); assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)) .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("scope-secret")); @@ -48,7 +49,8 @@ void refusesExpiredAndAmbiguousPublicScopes() { "demo-world", 22L, "demo-world", - List.of(scopedRealm(caller, "production", "expired-scope", now.minusSeconds(1)))); + List.of(scopedRealm(caller, "production", "expired-scope", now.minusSeconds(1))), + now); assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); @@ -59,7 +61,8 @@ void refusesExpiredAndAmbiguousPublicScopes() { "demo-world", List.of( scopedRealm(caller, "production-a", "scope-a", now.plusSeconds(3600)), - scopedRealm(caller, "production-b", "scope-b", now.plusSeconds(3600)))); + scopedRealm(caller, "production-b", "scope-b", now.plusSeconds(3600))), + now); assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); } @@ -73,9 +76,10 @@ void clearsPriorScopeBeforeReplacingTheWorldBinding() { "1", 22L, "demo-world", - List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(3600)))); + List.of(scopedRealm(caller, "production", "scope-secret", now.plusSeconds(3600))), + now); - store.clearWorldScopes(caller, 22L, "demo-world"); + store.clearWorldScopes(caller, 22L, "demo-world", now); assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)).isEmpty(); } @@ -108,7 +112,7 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { assertThat(firstAttempt.scope().connectScopeId()) .isEqualTo(retryAttempt.scope().connectScopeId()); - store.clearWorldScopes(caller, 22L, "demo-world"); + store.clearWorldScopes(caller, 22L, "demo-world", now); store.replaceRealmSnapshot( caller, "demo-world", @@ -402,7 +406,8 @@ void replacingWorldScopesClearsOnlyThatWorldsRealmsSnapshotAndKeepsJoinScopes() "demo", 22L, "demo", - List.of(scopedRealm(caller, 22L, "production", "join-scope", now.plusSeconds(60)))); + List.of(scopedRealm(caller, 22L, "production", "join-scope", now.plusSeconds(60))), + now); assertThat(store.realmsSnapshot(caller, 22L, "demo", now)).isEmpty(); assertThat(store.realmsSnapshot(caller, 22L, "secondary", now)) @@ -417,6 +422,94 @@ void replacingWorldScopesClearsOnlyThatWorldsRealmsSnapshotAndKeepsJoinScopes() .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("join-scope")); } + @Test + void replacingWorldScopesUsesCallerTimeWhenPruningUnrelatedScopes() { + SessionContext caller = session(41L, 7L); + Instant now = Instant.parse("2000-01-01T00:00:00Z"); + Instant scopeExpiry = now.plusSeconds(600); + store.replaceRealmSnapshot( + caller, + "demo", + 22L, + "demo", + "demo-catalog", + List.of(), + List.of(scopedRealm(caller, 22L, "production", "demo-scope", scopeExpiry)), + now); + store.replaceRealmSnapshot( + caller, + "secondary", + 22L, + "secondary", + "secondary-catalog", + List.of(), + List.of(scopedRealm(caller, 22L, "production", "secondary-scope", scopeExpiry)), + now); + + store.replaceWorldScopes( + caller, + "demo", + "demo", + List.of(scopedRealm(caller, 22L, "production", "replacement-scope", scopeExpiry)), + now); + + assertThat(store.publicProductionScope(caller, 22L, "demo", now)) + .hasValueSatisfying( + scope -> assertThat(scope.connectScopeId()).isEqualTo("replacement-scope")); + assertThat(store.realmsSnapshot(caller, 22L, "secondary", now)) + .hasValueSatisfying( + snapshot -> assertThat(snapshot.catalogFingerprint()).isEqualTo("secondary-catalog")); + assertThat(store.publicProductionScope(caller, 22L, "secondary", now)) + .hasValueSatisfying( + scope -> assertThat(scope.connectScopeId()).isEqualTo("secondary-scope")); + } + + @Test + void clearingWorldScopesUsesCallerTimeWhenPruningUnrelatedScopes() { + SessionContext caller = session(41L, 7L); + Instant now = Instant.parse("2000-01-01T00:00:00Z"); + Instant scopeExpiry = now.plusSeconds(600); + store.replaceRealmSnapshot( + caller, + "demo", + 22L, + "demo", + "demo-catalog", + List.of(), + List.of(scopedRealm(caller, 22L, "production", "demo-scope", scopeExpiry)), + now); + store.replaceRealmSnapshot( + caller, + "secondary", + 22L, + "secondary", + "secondary-catalog", + List.of(), + List.of(scopedRealm(caller, 22L, "production", "secondary-scope", scopeExpiry)), + now); + + store.clearWorldScopes(caller, "demo", now); + + assertThat(store.realmsSnapshot(caller, 22L, "secondary", now)) + .hasValueSatisfying( + snapshot -> assertThat(snapshot.catalogFingerprint()).isEqualTo("secondary-catalog")); + assertThat(store.publicProductionScope(caller, 22L, "secondary", now)) + .hasValueSatisfying( + scope -> assertThat(scope.connectScopeId()).isEqualTo("secondary-scope")); + } + + @Test + void worldScopeMutationsRejectNullCallerTime() { + SessionContext caller = session(41L, 7L); + + assertThatThrownBy(() -> store.replaceWorldScopes(caller, "demo", 22L, "demo", List.of(), null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("now must not be null"); + assertThatThrownBy(() -> store.clearWorldScopes(caller, 22L, "demo", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("now must not be null"); + } + @Test void replacingWorldScopesForAnotherAccountClearsPriorLobbyAuthority() { SessionContext previousCaller = session(41L, 7L); @@ -448,7 +541,8 @@ void replacingWorldScopesForAnotherAccountClearsPriorLobbyAuthority() { "demo", 22L, "demo", - List.of(scopedRealm(currentCaller, 22L, "production", "current-demo-scope", expiresAt))); + List.of(scopedRealm(currentCaller, 22L, "production", "current-demo-scope", expiresAt)), + now); assertThat(store.realmsSnapshot(currentCaller, 22L, "demo", now)).isEmpty(); assertThat(store.realmsSnapshot(currentCaller, 22L, "secondary", now)).isEmpty(); @@ -463,10 +557,11 @@ void rejectsInvalidTransportIdsAndScopesBoundToAnotherIdentity() { assertThatThrownBy(() -> store.clearSession(0L)).isInstanceOf(IllegalArgumentException.class); SessionContext caller = session(7L, 41L); + Instant now = Instant.now(); DirectTextConnectScopeSessionStore.ScopedRealm mismatchedScope = - scopedRealm(session(8L, 41L), "production", "scope-secret", Instant.now().plusSeconds(60)); + scopedRealm(session(8L, 41L), "production", "scope-secret", now.plusSeconds(60)); assertThatThrownBy( - () -> store.replaceWorldScopes(caller, "demo", "demo", List.of(mismatchedScope))) + () -> store.replaceWorldScopes(caller, "demo", "demo", List.of(mismatchedScope), now)) .isInstanceOf(DirectTextConnectScopeSessionStore.ConflictingIdentityException.class); } From d12f9a3ff3551ea75005fb315c9477031e666c53 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:52:23 +1300 Subject: [PATCH 050/105] Resolve direct-text discovery review findings --- .../game-session-service/protocols.md | 6 +- .../game-session-service/runtime-and-data.md | 2 +- .../microservices/tcp-proxy-service/README.md | 2 +- .../tcp-proxy-service/protocols.md | 6 +- .../system-architecture-frontend.md | 4 +- design/project-management/ai-observations.md | 8 +- .../player-access-and-session.md | 2 +- .../realm-routing-and-playable-state.md | 4 +- .../gamesession/client/AccountClient.java | 9 +- .../DirectTextOrdinalSelectionResolver.java | 231 +++++++++++++ .../command/text/PlayCommandHandler.java | 107 ++---- .../command/text/WorldsCommandHandler.java | 140 ++++---- .../WorldsTextCommandDispatchHandler.java | 22 +- .../DirectTextConnectScopeSessionStore.java | 22 -- .../gamesession/client/AccountClientTest.java | 64 ++++ ...irectTextOrdinalSelectionResolverTest.java | 307 ++++++++++++++++++ .../WorldsTextCommandDispatchHandlerTest.java | 91 ++++++ 17 files changed, 822 insertions(+), 205 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 9d0cb44560..4f1b52dee2 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -69,8 +69,8 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `LOGOUT` / `LOGOFF` / `QUIT` | Ends the current session and closes the transport. `LOGOFF` and `QUIT` are exact aliases for canonical `LOGOUT`. | `LOGOUT` | | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | -| `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Direct-text command implemented; target selector form remains unavailable.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. The target `` uses the same tenant-scoped selector rules as `REALMS`; the current command accepts a bound WORLDS index or the bare world slug of a uniquely resolved current catalog world, not `tenantSlug/worldSlug`. | `JOIN demo/demo` (target) | +| `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where target `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; target behavior never resolves a bare `worldSlug` globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | +| `JOIN ` | **Direct-text command implemented; target selector form remains unavailable.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. The target `` uses the same tenant-scoped selector rules as `REALMS`; the current command accepts a bound WORLDS index or the bare world slug of a uniquely resolved current catalog world, not `tenantSlug/worldSlug`. This bare-slug path is implementation drift. | `JOIN demo/demo` (target) | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | @@ -82,7 +82,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot. `[character]` currently accepts a character name; a response-local character index is target-only and is not implemented. Current world and realm menu indices are bound to their exact connection-local response snapshots and catalog revisions, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. Current Game Session pointer snapshots carry numeric `tenantId` and `worldSlug` but no `tenantSlug`; local `WORLDS` renders only the bare world slug, and REALMS/JOIN/PLAY resolve that slug only when the current catalog does not contain the same world slug for multiple tenants. Bound world and realm menu indices remain available from their exact browse snapshots. This bare-slug shortcut is implementation drift, not proof of the target tenant-scoped stable selector or complete Telnet flow; `REALMS demo/demo` and `JOIN demo/demo` are target examples, not current accepted command forms. +Selector rules for `PLAY` match the lobby helpers. Target `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot. `[character]` currently accepts a character name; a response-local character index is target-only and is not implemented. Current world and realm menu indices are bound to their exact connection-local response snapshots and catalog revisions, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. Current Game Session pointer snapshots carry numeric `tenantId` and `worldSlug` but no `tenantSlug`; local `WORLDS` renders only the bare world slug, and REALMS/JOIN/PLAY resolve it only when the current catalog has no duplicate world slug across tenants. This current shortcut is implementation drift: the target never resolves a bare `worldSlug` globally, and `REALMS demo/demo` and `JOIN demo/demo` remain target examples rather than current accepted forms. ### JOIN Translation and Status 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 371d0ef705..ef22405d44 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -143,7 +143,7 @@ Unauthenticated `sessionctx:*` entries may exist before `LOGIN`; they are bootst Game Session owns the live `sessionctx:*` family and applies only its local reset consequence: reset invalidates or rebuilds this bootstrap/lookup context and never preserves it. The canonical reset lifecycle and session-policy choice remain in [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model). Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections; Game Session does not reset or repair them, and gameplay session policy does not change their Account-owned behavior. -The direct-text lobby additionally uses the current `gamesession:lobby:` Redis family for short-lived world/realm snapshots, Account-issued scopes, and stable JOIN request IDs. Game Session owns it as non-preservable pre-auth context: any affected reset must invalidate and read back the exact keys before a new JOIN may rely on that transport session. The key is not tenant- or region-tagged, so a scoped reset cannot infer the affected set from its name; it requires authoritative session inventory or conservative full-family invalidation. The local store implements exact-key `clearSession` and focused tests check its readback; live Redis execution, the canonical reset executor, and scoped readback remain separate gates. This family is not session-preservation authority or a reason to bypass the current fail-closed operator fallback. +The direct-text lobby additionally uses the current `gamesession:lobby:` Redis family for short-lived world/realm snapshots, authenticated Account scope material, and stable JOIN request IDs. Game Session owns it as pre-gameplay lobby state: any affected reset must invalidate and read back the exact keys before a new JOIN may rely on that transport session. The key is not tenant- or region-tagged, so a scoped reset cannot infer the affected set from its name; it requires authoritative session inventory or conservative full-family invalidation. The local store implements exact-key `clearSession` and focused tests check its readback; live Redis execution, the canonical reset executor, and scoped readback remain separate gates. This family is not session-preservation authority or a reason to bypass the current fail-closed operator fallback. Target-state Game Session maintains the bounded active-binding index families owned by [Session Behavior](../../system-architecture-session-behavior.md#session-and-identity-management). The local Redis key shapes are: diff --git a/design/architecture/microservices/tcp-proxy-service/README.md b/design/architecture/microservices/tcp-proxy-service/README.md index f98582d8ce..76e8b857f5 100644 --- a/design/architecture/microservices/tcp-proxy-service/README.md +++ b/design/architecture/microservices/tcp-proxy-service/README.md @@ -47,7 +47,7 @@ Public Telnet TLS is configured as one of two mutually exclusive modes: a dedica - `readiness` is traffic-admission safety for new Telnet sessions. The service is ready only when: - the Telnet listener is bound; - the proxy can reach Spring Cloud Gateway’s readiness surface for the gameplay route; and - - the downstream gameplay admission path supports the currently implemented admission path `connect -> LOGIN [secret] -> PLAY -> first LOOK` for callers with the required existing membership and target-specific visibility/grant authority. + - the downstream gameplay admission path supports completion through the first `LOOK` for callers with the required existing membership and target-specific visibility/grant authority: `connect -> LOGIN [secret] -> PLAY -> first LOOK`. For an otherwise eligible public-production caller whose `PLAY` returns `JOIN_REQUIRED`, it must also support `JOIN -> PLAY` before `LOOK`; returning `JOIN_REQUIRED` alone is not sufficient readiness. Local command support does not prove end-to-end Telnet readiness. - While unready, the proxy must reject new Telnet sessions immediately with an explicit startup/unavailable message and close the connection. It must not silently accept the socket and let the first gameplay command discover startup races later. - Loss of downstream readiness after a session is already established blocks new sessions but does not by itself imply that the proxy process is dead. - Readiness transition observability uses the shared contract from [Deployment Environments](../../infrastructure/deployment-environments.md): `firemud.readiness.current`, `firemud.readiness.transitions`, and structured logs keyed by the curated dependency names `telnetListener` and `gatewayGameplayPath`. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 1354314eaf..b6e2269f1d 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -11,7 +11,7 @@ The replay-cache miss/hit qualifier applies only to connect-token issuance. Text The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance receives fresh Account membership evidence including `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`; a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof. The target requires an independent issuance-time Account reread of `membershipVersion` and `membershipAuthorityGeneration`; the current baseline and replay-revalidation proof remains incomplete under [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check; for eligible public-production targets, only missing or `INACTIVE` membership can reach `JOIN_REQUIRED`, after fresh entitlement/public policy permits joining. Existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` remains denied. Private/playtest targets perform the applicable current realm-grant check. The separate target connect-token grant-validation contract for private/playtest targets also remains unimplemented. The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` always performs fresh membership and applicable private/playtest grant checks, regardless of any connect-token replay-cache state. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). The Telnet credential form is `LOGIN [secret]`. `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. -The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but does not establish the target-required independent issuance-time reread of membership version and authority generation. Its baseline proof remains incomplete, and target private/playtest connect-token grant validation is a separate gap. For an eligible public-production target with missing or `INACTIVE` membership, text `PLAY` evaluates fresh entitlement and `allowPublicJoin` before returning `JOIN_REQUIRED`; entitlement outage or policy denial wins. An existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` is denied. These local gaps do not change the Authentication-owned admission outcomes. +The current text `PLAY` path checks the fresh Account response's membership identity, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`, plus the realm grant where applicable; the current connect-token path receives the same membership fields but does not establish the target-required independent issuance-time reread of membership version and authority generation. Its baseline proof remains incomplete, and target private/playtest connect-token grant validation is a separate gap. Current text `PLAY` returns `JOIN_REQUIRED` for an otherwise eligible public-production target with missing or non-admitting `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks; the target also requires explicit `JOIN` for `INACTIVE` membership before `PLAY`. An existing `ACTIVE` membership with `gameplayAdmissionAllowed=false` is denied. Private/playtest targets never offer public `JOIN`: current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, and target admission requires existing `ACTIVE` membership plus the exact current realm grant. These local gaps do not change the Authentication-owned admission outcomes. The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients have a local `LOGIN` -> `PLAY` -> `LOOK` path for existing admitting members; when `PLAY` returns `JOIN_REQUIRED`, the client can issue `JOIN` and retry `PLAY` before `LOOK`. Focused local JOIN proof exists, while full Telnet discovery/bridge and PostgreSQL/recovery proof remain open. Missing or `INACTIVE` eligible public-production membership reaches `JOIN_REQUIRED` only after fresh entitlement/public policy permits joining; existing `ACTIVE` membership with gameplay admission disabled remains denied. Direct text can invoke the Account-backed writer. Missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. ## Cross-Path Connectivity Contract @@ -36,7 +36,7 @@ These flows describe how Telnet traffic is forwarded into the shared login/sessi - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. - After Telnet-control filtering, the proxy forwards each resulting sanitized gameplay line unchanged to Spring Cloud Gateway; unsupported controls and subnegotiation never leak into the gameplay line. The Game Session Service creates or binds the gameplay session exactly as it does for native WebSocket clients. - **Future smart-client flow** - - No typed `SESSION` gameplay line or proxy-owned semantic extension is part of the current contract. If a later adapter is selected, Game Session owns its semantics and any attach hint remains advisory input that cannot replace the normal human-facing `WORLDS` -> `LOGIN` -> `REALMS` -> Authentication-owned conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow. + - No typed `SESSION` gameplay line or proxy-owned semantic extension is part of the current contract. If a later adapter is selected, Game Session owns its semantics and any attach hint remains advisory input; it cannot replace the current conditional `JOIN` path described above or the target discovery-first sequence owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). ## Advanced Multi-Connection Scenarios @@ -107,7 +107,7 @@ Current rules: - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; -- any future adapter-carried attach hint must remain advisory and must not bypass either the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` fail-closed path or the target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow; only existing `ACTIVE` public-production members skip target `JOIN`. +- any future adapter-carried attach hint must remain advisory and must not bypass the current conditional `JOIN` path described above or the target discovery-first sequence owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. - Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime supports the local Account-backed `JOIN` command and fresh public entitlement/policy gating in Game Session `PLAY`, but still bootstraps hidden default routing and does not enforce `WORLDS`; full target Telnet discovery/bridge and PostgreSQL/recovery proof remain open. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). diff --git a/design/architecture/system-architecture-frontend.md b/design/architecture/system-architecture-frontend.md index 1785ee6c8f..1e6c8c7718 100644 --- a/design/architecture/system-architecture-frontend.md +++ b/design/architecture/system-architecture-frontend.md @@ -20,9 +20,9 @@ The first-party browser consumes the existing Account/Gateway APIs and the versi The current Vite build emits the `web-client` artifact and its reserved `frontend-assets` output, but the independently released static host, public-site routing and delivery (including the target `/auth/**` rewrite), health/security/cache behavior, rollback, and bounded end-to-end browser proof are not implemented or proved. Those gaps remain target implementation obligations rather than evidence that the supported frontend boundary is live. -Direct-text `JOIN` is implemented locally through the Account-owned `JoinPublicProductionMembership` writer; first-party `Join & Play` remains target-only and the complete browser/Telnet flow is not proved. In the target, the writer creates missing membership or restores `INACTIVE`; Game Session admission, connect-token issuance, character creation, and `PLAY` require existing membership and never create or restore it implicitly. The current Account membership response exposes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. Current text `PLAY` validates the fresh lifecycle/version/generation evidence; for an otherwise eligible public-production target, only missing or `INACTIVE` membership can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks pass. An existing `ACTIVE` membership with gameplay admission disabled remains denied. Current connect-token issuance receives the lifecycle/version/generation fields on its fresh path, but replay-cache hits can bypass fresh reads and the target independent issuance baseline/generation reread remains a proof gap. Direct-text JOIN has focused local coverage, while complete Telnet discovery/bridge, PostgreSQL/recovery, and first-party `Join & Play` proof remain open. The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership/grant/entitlement/routing checks pass; current connect-token private/playtest grant validation remains incomplete. Gateway `POST /ws/game/connect-token/revoke` and the dependent immediate edge-revocation step described below are target-only and are not implemented in the current runtime. Account `POST /auth/logout` and `POST /auth/logout-all` guidance below is also target-only and unavailable. The current logout fallback is local reconnect-state clearing plus bounded credential expiry; it is not Account revocation, Account generation advancement, immediate Gateway revocation, an edge deny/replay fence, Game Session gameplay-binding termination, or downstream reconciliation evidence. Edge replay/deny enforcement is claimed only when that Gateway revoke path is implemented and reachable. +The protected-cookie `/ws/game/**` handshake and bootstrap-backed bare `LOGIN` are implemented but non-promotable until Gateway carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence are complete. Returning members and grant-backed private/playtest flows remain eligible only when the live membership/grant/entitlement/routing checks pass; current connect-token private/playtest grant validation remains incomplete. Gateway `POST /ws/game/connect-token/revoke` and Account `POST /auth/logout` and `/auth/logout-all` are target-only and unavailable. The current logout fallback clears local reconnect state and relies on bounded credential expiry; it does not establish Account revocation or generation advancement, Gateway revocation or an edge deny/replay fence, Game Session binding termination, or downstream reconciliation. Edge replay/deny enforcement is claimed only when the Gateway revoke path is implemented and reachable. -The direct-text `JOIN` action is implemented, but first-party `Join & Play` and the independent issuance-time membership baseline/generation reread remain unimplemented or unproved. The frontend must keep the complete first-party browser join flow unavailable until that route, its post-join snapshot, and its token-issuance proof are complete; direct-text clients may use the implemented join writer. Current text `PLAY` and the fresh connect-token path receive lifecycle, version, generation, and evaluation-time fields; existing-member admission requires `ACTIVE`, while only eligible public-production missing or `INACTIVE` membership reaches `JOIN_REQUIRED` after fresh entitlement permits public joining. An existing `ACTIVE` member with gameplay admission disabled remains denied. Returning members and private/playtest callers remain eligible only when the other current membership, grant, entitlement, and routing checks pass. Complete Telnet/browser end-to-end, PostgreSQL/recovery, replay-cache revalidation, and issuance-baseline proof remain open. This status is the frontend summary of the target/current distinction in [Authentication & Authorization](./system-architecture-authentication.md#implementation-status). +Direct-text `JOIN` is implemented locally; first-party `Join & Play` remains unavailable until its route, post-join snapshot, and token-issuance proof are complete. Current text `PLAY` requires a fresh admitting `ACTIVE` membership, while eligible public-production missing or `INACTIVE` membership reaches `JOIN_REQUIRED` after fresh entitlement and public-policy checks. Target `JOIN` creates missing or restores `INACTIVE` membership; `PLAY`, character creation, and connect-token issuance never do so implicitly. Returning members and private/playtest callers still require their applicable current membership, grant, entitlement, and routing checks. Complete browser/Telnet flow, PostgreSQL/recovery, replay-cache revalidation, and issuance-baseline proof remain open. This concise frontend status follows [Authentication & Authorization](./system-architecture-authentication.md#implementation-status), which owns the current and target contract. ### Persisted actor entry UX boundary (PLAYER-01) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a5d392d171..a6adb142da 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -179,7 +179,7 @@ Entry format: - Outcome: an explicit context using `@Configuration` and `@TestComponent` isolates the embedded application; all 284 source-branch Account tests passed with zero skips, failures, or errors. `@TestConfiguration` alone loaded the real application's unrelated gRPC clients and was not sufficient here. The earlier failed combined run remains non-completion evidence. - `2026-10-02`: Preserve the producer exit status when capturing validation logs - - Context: a Game Session validation run failed a new fixture assertion, but a pipeline ending in `tee` returned exit0 because the shell did not enable `pipefail`. + - Context: a Game Session validation run failed a new fixture assertion, but a pipeline ending in `tee` returned exit 0 because the shell did not enable `pipefail`. - Expected pattern: enable `set -o pipefail` before captured validation pipelines and verify the terminal build result and test reports; a log sink's success is not the validation process's success. - Outcome: the failed build was identified from its terminal report, not reported as passing. After the fixture correction, the guarded complete rerun passed; no production check or negative assertion was weakened. @@ -189,3 +189,9 @@ Entry format: - Expected pattern: retain an existing native process wait in its launching agent. For delegated external waits, let the sentinel launch its own canonical read-only waiter for the exact durable trigger or CI run; never retry the evidence-producing operation merely because a handle is unavailable in another agent. - Current status: the launching Gameplay agent retained the live CLI wait. Whether cross-agent process handles are supported in other execution environments is unverified. - Reconsideration trigger: revisit if a future harness requires cross-platform handle portability or a canonical watcher fix is verified. + +- `2026-10-03`: A terminal Hosted notification needs prompt owner consumption + - Context: the exact-head #2898 Hosted review finished with five findings, but Gameplay delayed consuming the sentinel result while handling parent CI; adjudication and the public checkpoint followed about eleven minutes later. + - Observation: an active watcher does not guarantee prompt adjudication. Its reassuring handoff wording cannot replace checking the attributable result and raw findings. + - Expected pattern: consume terminal review evidence, adjudicate it, and publish the canonical checkpoint before returning to integration work. Keep CI repair independent rather than postponing completed review reporting. + - Outcome: review `5398994837` was recorded as 5 found / 4 accepted / 1 routed before implementing its accepted batch; the inherited Account observation has a canonical target route. 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 14298c0699..d8fdcd091c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,7 +32,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure. Game Session text JOIN dispatch is implemented locally under #2898; first-party Join & Play remains unavailable. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target gets retryable `AUTH_UNAVAILABLE`, while unbound private selectors keep the generic hidden projection. Text `PLAY` still requires admitting membership before its applicable Account-owned realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current JOIN commits membership, operation outcome, and audit outbox atomically; global-only registration no longer creates membership. The strict ADR 0025 target/pointer commit gate and durable target fence remain unimplemented. Terminal replay revalidates remote scope/target/entitlement after commit or rollback without rewriting the stored outcome, but retained JOIN/scope deletion or minimization and recovery after an unknown database commit outcome remain open. V27's restrictive FK retains scopes referenced by pending or terminal JOINs; expired unreferenced scopes are swept. The cached successful connect-token path can bypass fresh authority rereads, and current-authority/postcondition revalidation, membership-authority generation propagation, and private/playtest issuance grant validation remain gaps. Subscription locking does not lock the joined billing-owner Account. PostgreSQL runtime and direct-text end-to-end proof are unclaimed; the row-lock regression skips locally without Docker. Gateway public JOIN exposure and first-party Join & Play remain unavailable. Audit-delivery recovery beyond the local outbox boundary, target five-field grant codec producer/consumer and admission propagation, monotonic grant outcomes/tombstones, expiry, tenant-scoped roles, and delegated management remain open. See [Authentication](../../architecture/system-architecture-authentication.md), [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), and [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md). | | `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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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`. | 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 b0fa510793..c59b53b226 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. Account now exposes lifecycle-aware membership evidence (`membershipLifecycleState`, `membershipVersion`, and `membershipAuthorityGeneration`), and the explicit `JoinPublicProductionMembership` writer is implemented locally. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now has a bounded shared Redis lobby record keyed by the stable positive numeric transport session ID: `WORLDS` output and its exact ordinal snapshot come from one catalog read, authenticated Account scopes and sticky JOIN request IDs are caller-bound and survive Game Session replacement, numeric `REALMS` selectors fail closed against stale or changed snapshots, and current bare world slugs re-resolve against current catalog authority. The pointer projection carries no `tenantSlug`, so WORLDS cannot yet emit the canonical `tenantSlug/worldSlug` selector and REALMS/JOIN/PLAY do not accept that stable pair; cross-tenant duplicate world slugs remain visible as distinct tenant-bound ordinal choices, while ambiguous bare slugs fail closed. Snapshot and Account-scope expiry are bounded, and per-key Lua compare-and-set protects JOIN request binding and replacement. Focused unit proof is added; a Docker-gated Redis integration test exercises cross-instance persistence and concurrent JOIN retries but is locally skipped when Docker is unavailable. Game Session now invokes the Account writer from this retained scope, but full direct-text/Telnet and first-party `Join & Play` end-to-end proof remains open. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, separate stored catalog and pointer revisions have not converged through every consumer, the durable routing key has not converged to `{tenantId, realmId}`, the owner-local pointer primitive locks and conditionally compares both expected revisions and commits pointer plus audit together, while prepared-cutover execution remains recorded outside that transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The realm catalog, admission-pointer reads, bootstrap/connect-scope flow, runtime projections, and bounded direct-text [REALMS-to-JOIN handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) have local implementation. Game Session retains caller-bound Account scopes and JOIN request IDs in shared Redis, binds browse ordinals to snapshots, and invokes Account's explicit join writer; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#join-translation-and-status) own the local translation. Focused unit proof exists; the Docker-gated Redis cross-instance/retry proof was skipped locally, and full direct-text/Telnet and first-party `Join & Play` proof remains open. The current pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable; current unique bare-world-slug resolution is implementation drift from the target prohibition on bare `worldSlug` resolution. Routing remains partial: explicit `CLOSED`, consumer-wide revision convergence, canonical `{tenantId, realmId}` addressing, atomic prepared-cutover execution, and bounded active-session drain remain gaps. Public/grant policy lacks expiry, monotonic mutation outcomes/tombstones, and tenant-admin management; playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration remain unimplemented or unproved. See [Authentication](../../architecture/system-architecture-authentication.md) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) for the canonical JOIN and local protocol contracts. ## Packet 4 Status and Proof Gaps @@ -19,7 +19,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | WORLDS and its ordinal snapshot now share one catalog read; direct-text ordinal selection is snapshot-bound, and Account scope/JOIN retry state is shared in bounded Redis lobby state. Full direct-text/Telnet proof remains open. The current pointer carries no `tenantSlug`, so the stable `tenantSlug/worldSlug` selector is not implemented; current bare world slugs are usable only when the catalog resolves them uniquely, while exact browse ordinals are snapshot-bound. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows; canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.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) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority now uses a row-locked expected `{pointerVersion, catalogRevision}` check, a conditional existing-row update, separate route/catalog revisions, and one pointer-plus-audit transaction. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Public pointer mutation/cutover RPCs remain fail-closed, so the full target cutover operation is not live. Explicit `CLOSED`, repository addressing by the canonical `{tenantId, realmId}` key and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 2d8cb85f08..059a2433d1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -215,7 +215,7 @@ public IssueDirectTextConnectScopeResponse issueDirectTextConnectScope( .issueDirectTextConnectScope(request); } catch (StatusRuntimeException ex) { logger.warn("Account direct-text scope issuance failed", ex); - return scopeIssueError(accountAuthorityErrorCode(ex), "Account authority unavailable"); + return scopeIssueError("AUTH_UNAVAILABLE", "Account authority unavailable"); } catch (Exception ex) { logger.warn("Account direct-text scope issuance did not complete", ex); return scopeIssueError("AUTH_UNAVAILABLE", "Account authority unavailable"); @@ -305,13 +305,6 @@ private boolean isPositiveLong(String value) { } } - private String accountAuthorityErrorCode(StatusRuntimeException exception) { - Status.Code statusCode = exception.getStatus().getCode(); - return statusCode == Status.Code.UNAVAILABLE || statusCode == Status.Code.DEADLINE_EXCEEDED - ? "AUTH_UNAVAILABLE" - : statusCode.name(); - } - private IssueDirectTextConnectScopeResponse scopeIssueError(String code, String message) { return IssueDirectTextConnectScopeResponse.newBuilder() .setError(ErrorDetail.newBuilder().setCode(code).setMessage(message)) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java new file mode 100644 index 0000000000..5e6af546a9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamesession.command.text; + +import java.time.Instant; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.DiscoverySnapshot; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmDiscoverySnapshot; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.RealmOrdinalTarget; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.RealmsSnapshot; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.WorldOrdinalTarget; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.WorldsSnapshot; +import net.firedevops.firemud.gamesession.service.SessionContext; + +/** Shared, policy-neutral resolution for direct-text response-local ordinal selectors. */ +final class DirectTextOrdinalSelectionResolver { + private DirectTextOrdinalSelectionResolver() {} + + static WorldTenantResolution resolveWorldTenantId(WorldView world) { + Objects.requireNonNull(world, "world must not be null"); + List tenantIds = world.realms().stream().map(RealmView::tenantId).distinct().toList(); + if (tenantIds.size() != 1) { + return new AmbiguousWorldTenantId(); + } + return new UniqueWorldTenantId(tenantIds.getFirst()); + } + + static long worldTenantIdOrInvalid(WorldView world) { + WorldTenantResolution resolution = resolveWorldTenantId(world); + return resolution instanceof UniqueWorldTenantId unique ? unique.tenantId() : -1L; + } + + static Resolution resolveWorldOrdinal( + String selector, + DirectTextConnectScopeSessionStore store, + SessionContext caller, + Instant now, + DiscoverySnapshot currentCatalog, + GameplayWorldCatalog worldCatalog) { + Objects.requireNonNull(caller, "caller must not be null"); + Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); + if (store == null) { + return new Unavailable<>(); + } + return resolveWorldOrdinal( + selector, + () -> store.worldsSnapshot(caller, now), + now, + currentCatalog, + target -> worldCatalog.resolveSnapshotOrdinal(currentCatalog, target)); + } + + static Resolution resolveWorldOrdinal( + String selector, + Supplier> snapshotReader, + Instant now, + DiscoverySnapshot currentCatalog, + Function> currentTargetResolver) { + Objects.requireNonNull(snapshotReader, "snapshotReader must not be null"); + Objects.requireNonNull(now, "now must not be null"); + Objects.requireNonNull(currentCatalog, "currentCatalog must not be null"); + Objects.requireNonNull(currentTargetResolver, "currentTargetResolver must not be null"); + + Optional maybeSnapshot; + try { + maybeSnapshot = Objects.requireNonNull(snapshotReader.get(), "snapshotReader returned null"); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return new Unavailable<>(); + } + if (maybeSnapshot.isEmpty()) { + return new UnboundSelector<>(); + } + WorldsSnapshot snapshot = maybeSnapshot.orElseThrow(); + if (!snapshot.expiresAt().isAfter(now)) { + return new UnboundSelector<>(); + } + if (!snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + return new SnapshotMismatch<>(); + } + Optional maybeOrdinal = parseOrdinal(selector); + if (maybeOrdinal.isEmpty()) { + return new UnboundSelector<>(); + } + Optional maybeTarget = + snapshot.ordinalTargets().stream() + .filter(target -> target.ordinal() == maybeOrdinal.orElseThrow()) + .findFirst(); + if (maybeTarget.isEmpty()) { + return new UnboundSelector<>(); + } + Optional selected = currentTargetResolver.apply(maybeTarget.orElseThrow()); + return selected.>map(Selected::new).orElseGet(SnapshotMismatch::new); + } + + static Resolution resolveRealmOrdinal( + String selector, + DirectTextConnectScopeSessionStore store, + SessionContext caller, + long tenantId, + WorldView world, + Instant now, + Supplier currentCatalogReader, + GameplayWorldCatalog worldCatalog) { + Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); + Objects.requireNonNull(currentCatalogReader, "currentCatalogReader must not be null"); + Objects.requireNonNull(world, "world must not be null"); + if (store == null) { + return new Unavailable<>(); + } + return resolveRealmOrdinal( + selector, + () -> store.realmsSnapshot(caller, tenantId, world.slug(), now), + tenantId, + world, + now, + currentCatalogReader, + (current, target) -> worldCatalog.resolveRealmSnapshotOrdinal(world, current, target)); + } + + static Resolution resolveRealmOrdinal( + String selector, + Supplier> snapshotReader, + long tenantId, + WorldView world, + Instant now, + Supplier currentCatalogReader, + BiFunction> currentTargetResolver) { + Objects.requireNonNull(snapshotReader, "snapshotReader must not be null"); + Objects.requireNonNull(world, "world must not be null"); + Objects.requireNonNull(now, "now must not be null"); + Objects.requireNonNull(currentCatalogReader, "currentCatalogReader must not be null"); + Objects.requireNonNull(currentTargetResolver, "currentTargetResolver must not be null"); + + Optional maybeSnapshot; + try { + maybeSnapshot = Objects.requireNonNull(snapshotReader.get(), "snapshotReader returned null"); + } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException + | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + return new Unavailable<>(); + } + if (maybeSnapshot.isEmpty()) { + return new UnboundSelector<>(); + } + RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); + if (!snapshot.expiresAt().isAfter(now)) { + return new UnboundSelector<>(); + } + if (tenantId <= 0L + || snapshot.tenantId() != tenantId + || !snapshot.worldSlug().equalsIgnoreCase(world.slug())) { + return new SnapshotMismatch<>(); + } + + RealmDiscoverySnapshot currentCatalog; + try { + currentCatalog = currentCatalogReader.get(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return new Unavailable<>(); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return new PointerUnavailable<>(); + } + if (!currentCatalog.worldSlug().equalsIgnoreCase(world.slug()) + || !snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + return new SnapshotMismatch<>(); + } + Optional maybeOrdinal = parseOrdinal(selector); + if (maybeOrdinal.isEmpty()) { + return new UnboundSelector<>(); + } + Optional maybeTarget = + snapshot.ordinalTargets().stream() + .filter(target -> target.ordinal() == maybeOrdinal.orElseThrow()) + .findFirst(); + if (maybeTarget.isEmpty()) { + return new UnboundSelector<>(); + } + Optional selected = currentTargetResolver.apply(currentCatalog, maybeTarget.orElseThrow()); + return selected.>map(Selected::new).orElseGet(SnapshotMismatch::new); + } + + private static Optional parseOrdinal(String selector) { + if (!GameplayWorldCatalog.isOrdinalSelector(selector)) { + return Optional.empty(); + } + try { + int ordinal = Integer.parseInt(selector.trim()); + return ordinal > 0 ? Optional.of(ordinal) : Optional.empty(); + } catch (NumberFormatException ex) { + return Optional.empty(); + } + } + + sealed interface WorldTenantResolution permits UniqueWorldTenantId, AmbiguousWorldTenantId {} + + record UniqueWorldTenantId(long tenantId) implements WorldTenantResolution {} + + record AmbiguousWorldTenantId() implements WorldTenantResolution {} + + sealed interface Resolution + permits Selected, UnboundSelector, SnapshotMismatch, Unavailable, PointerUnavailable { + default Optional selectedValue() { + return Optional.empty(); + } + } + + record Selected(T value) implements Resolution { + Selected { + Objects.requireNonNull(value, "selected value must not be null"); + } + + @Override + public Optional selectedValue() { + return Optional.of(value); + } + } + + record UnboundSelector() implements Resolution {} + + record SnapshotMismatch() implements Resolution {} + + record Unavailable() implements Resolution {} + + record PointerUnavailable() implements Resolution {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 0458efb788..fb279af147 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1219,38 +1219,21 @@ private WorldSelectorResolution resolvePlayWorld( .map(WorldSelectorResolution.Selected::new) .orElseGet(WorldSelectorResolution.Invalid::new); } - Optional maybeSnapshot; - try { - maybeSnapshot = - connectScopeSessionStore.worldsSnapshot(context, authorityEvaluationClock.instant()); - } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException - | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { - return new WorldSelectorResolution.Unavailable(); - } - if (maybeSnapshot.isEmpty()) { - return new WorldSelectorResolution.Stale(); - } - DirectTextConnectScopeSessionStore.WorldsSnapshot snapshot = maybeSnapshot.orElseThrow(); - if (!snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { - return new WorldSelectorResolution.Stale(); - } - int ordinal; - try { - ordinal = Integer.parseInt(selector.trim()); - } catch (NumberFormatException ex) { - return new WorldSelectorResolution.Stale(); - } - Optional maybeTarget = - snapshot.ordinalTargets().stream() - .filter(target -> target.ordinal() == ordinal) - .findFirst(); - if (maybeTarget.isEmpty()) { - return new WorldSelectorResolution.Stale(); + DirectTextOrdinalSelectionResolver.Resolution resolution = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + selector, + connectScopeSessionStore, + context, + authorityEvaluationClock.instant(), + currentCatalog, + gameplayWorldCatalog); + Optional selected = resolution.selectedValue(); + if (selected.isPresent()) { + return new WorldSelectorResolution.Selected(selected.orElseThrow()); } - return gameplayWorldCatalog - .resolveSnapshotOrdinal(currentCatalog, maybeTarget.orElseThrow()) - .map(WorldSelectorResolution.Selected::new) - .orElseGet(WorldSelectorResolution.Stale::new); + return resolution instanceof DirectTextOrdinalSelectionResolver.Unavailable + ? new WorldSelectorResolution.Unavailable() + : new WorldSelectorResolution.Stale(); } private RealmSelectorResolution resolvePlayRealm( @@ -1264,57 +1247,31 @@ private RealmSelectorResolution resolvePlayRealm( .map(RealmSelectorResolution.Selected::new) .orElseGet(RealmSelectorResolution.Invalid::new); } - long tenantId = worldTenantId(world); + long tenantId = DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world); if (tenantId <= 0L) { return new RealmSelectorResolution.Invalid(); } - Optional maybeSnapshot; - try { - maybeSnapshot = - connectScopeSessionStore.realmsSnapshot( - context, tenantId, world.slug(), authorityEvaluationClock.instant()); - } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException - | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { - return new RealmSelectorResolution.Unavailable(); - } - if (maybeSnapshot.isEmpty()) { - return new RealmSelectorResolution.Stale(); + DirectTextOrdinalSelectionResolver.Resolution resolution = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + selector, + connectScopeSessionStore, + context, + tenantId, + world, + authorityEvaluationClock.instant(), + () -> gameplayWorldCatalog.readRealmDiscoverySnapshot(world), + gameplayWorldCatalog); + Optional selected = resolution.selectedValue(); + if (selected.isPresent()) { + return new RealmSelectorResolution.Selected(selected.orElseThrow()); } - DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; - try { - currentRealmCatalog = gameplayWorldCatalog.readRealmDiscoverySnapshot(world); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + if (resolution instanceof DirectTextOrdinalSelectionResolver.Unavailable) { return new RealmSelectorResolution.Unavailable(); - } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { - return new RealmSelectorResolution.PointerUnavailable(); } - if (!snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { - return new RealmSelectorResolution.Stale(); - } - int ordinal; - try { - ordinal = Integer.parseInt(selector.trim()); - } catch (NumberFormatException ex) { - return new RealmSelectorResolution.Stale(); - } - Optional maybeTarget = - snapshot.ordinalTargets().stream() - .filter(target -> target.ordinal() == ordinal) - .findFirst(); - if (maybeTarget.isEmpty()) { - return new RealmSelectorResolution.Stale(); + if (resolution instanceof DirectTextOrdinalSelectionResolver.PointerUnavailable) { + return new RealmSelectorResolution.PointerUnavailable(); } - return gameplayWorldCatalog - .resolveRealmSnapshotOrdinal(world, currentRealmCatalog, maybeTarget.orElseThrow()) - .map(RealmSelectorResolution.Selected::new) - .orElseGet(RealmSelectorResolution.Stale::new); - } - - private static long worldTenantId(GameplayWorldCatalog.WorldView world) { - List tenantIds = - world.realms().stream().map(GameplayWorldCatalog.RealmView::tenantId).distinct().toList(); - return tenantIds.size() == 1 ? tenantIds.getFirst() : -1L; + return new RealmSelectorResolution.Stale(); } private sealed interface WorldSelectorResolution diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 6fdb56f4d9..6a0034f618 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -220,7 +220,10 @@ public RealmBrowseResult browseRealms( } try { connectScopeSessionStore.clearWorldScopes( - sessionContext, worldTenantId(world), world.slug(), clock.instant()); + sessionContext, + DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world), + world.slug(), + clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); @@ -232,7 +235,7 @@ public RealmBrowseResult browseRealms( connectScopeSessionStore.replaceRealmSnapshot( sessionContext, worldSelector, - worldTenantId(world), + DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world), world.slug(), realmSnapshot.catalogFingerprint(), realmSnapshot.ordinalTargets(), @@ -258,40 +261,21 @@ private WorldSelectorResolution resolveLobbyWorld( .map(WorldSelectorResolution.Selected::new) .orElseGet(WorldSelectorResolution.Invalid::new); } - if (connectScopeSessionStore == null) { - return new WorldSelectorResolution.Unavailable(); - } - Optional maybeSnapshot; - try { - maybeSnapshot = connectScopeSessionStore.worldsSnapshot(caller, clock.instant()); - } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException - | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { - return new WorldSelectorResolution.Unavailable(); + DirectTextOrdinalSelectionResolver.Resolution resolution = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + selector, + connectScopeSessionStore, + caller, + clock.instant(), + currentCatalog, + worldCatalog); + Optional selected = resolution.selectedValue(); + if (selected.isPresent()) { + return new WorldSelectorResolution.Selected(selected.orElseThrow()); } - if (maybeSnapshot.isEmpty()) { - return new WorldSelectorResolution.Stale(); - } - DirectTextConnectScopeSessionStore.WorldsSnapshot worldsSnapshot = maybeSnapshot.orElseThrow(); - if (!worldsSnapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { - return new WorldSelectorResolution.Stale(); - } - int ordinal; - try { - ordinal = Integer.parseInt(selector.trim()); - } catch (NumberFormatException ex) { - return new WorldSelectorResolution.Stale(); - } - Optional maybeTarget = - worldsSnapshot.ordinalTargets().stream() - .filter(target -> target.ordinal() == ordinal) - .findFirst(); - if (maybeTarget.isEmpty()) { - return new WorldSelectorResolution.Stale(); - } - return worldCatalog - .resolveSnapshotOrdinal(currentCatalog, maybeTarget.orElseThrow()) - .map(WorldSelectorResolution.Selected::new) - .orElseGet(WorldSelectorResolution.Stale::new); + return resolution instanceof DirectTextOrdinalSelectionResolver.Unavailable + ? new WorldSelectorResolution.Unavailable() + : new WorldSelectorResolution.Stale(); } private static OptionalLong parseTransportSessionId(String sessionId) { @@ -331,43 +315,26 @@ private RealmSelectorResolution resolveLobbyRealm( .map(RealmSelectorResolution.Selected::new) .orElseGet(RealmSelectorResolution.Invalid::new); } - if (connectScopeSessionStore == null) { - return new RealmSelectorResolution.Unavailable(); - } - Optional maybeSnapshot; - try { - maybeSnapshot = - connectScopeSessionStore.realmsSnapshot( - caller, worldTenantId(world), world.slug(), clock.instant()); - } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException - | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { + DirectTextOrdinalSelectionResolver.Resolution resolution = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + selector, + connectScopeSessionStore, + caller, + DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world), + world, + clock.instant(), + () -> currentCatalog, + worldCatalog); + Optional selected = resolution.selectedValue(); + if (selected.isPresent()) { + return new RealmSelectorResolution.Selected(selected.orElseThrow()); + } + if (resolution instanceof DirectTextOrdinalSelectionResolver.Unavailable) { return new RealmSelectorResolution.Unavailable(); } - if (maybeSnapshot.isEmpty()) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR); - } - DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); - if (!snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); - } - int ordinal; - try { - ordinal = Integer.parseInt(selector.trim()); - } catch (NumberFormatException ex) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR); - } - Optional maybeTarget = - snapshot.ordinalTargets().stream() - .filter(target -> target.ordinal() == ordinal) - .findFirst(); - if (maybeTarget.isEmpty()) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR); - } - return worldCatalog - .resolveRealmSnapshotOrdinal(world, currentCatalog, maybeTarget.orElseThrow()) - .map(RealmSelectorResolution.Selected::new) - .orElseGet( - () -> new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH)); + return resolution instanceof DirectTextOrdinalSelectionResolver.UnboundSelector + ? new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR) + : new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } private RealmSelectorResolution resolveOmittedLobbyRealm( @@ -382,7 +349,10 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( try { maybeSnapshot = connectScopeSessionStore.realmsSnapshot( - caller, worldTenantId(world), world.slug(), clock.instant()); + caller, + DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world), + world.slug(), + clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return new RealmSelectorResolution.Unavailable(); @@ -390,7 +360,7 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( if (maybeSnapshot.isPresent()) { DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) - || snapshot.tenantId() != worldTenantId(world) + || snapshot.tenantId() != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world) || !snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } @@ -435,7 +405,10 @@ private boolean isBoundToCurrentRealmSnapshot( try { maybeSnapshot = connectScopeSessionStore.realmsSnapshot( - caller, worldTenantId(world), world.slug(), clock.instant()); + caller, + DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world), + world.slug(), + clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return false; @@ -445,7 +418,7 @@ private boolean isBoundToCurrentRealmSnapshot( } DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) - || snapshot.tenantId() != worldTenantId(world) + || snapshot.tenantId() != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world) || !snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { return false; } @@ -550,7 +523,10 @@ public JoinMembershipResult joinPublicProductionMembership( try { maybeRealmSnapshot = connectScopeSessionStore.realmsSnapshot( - sessionContext, worldTenantId(world), world.slug(), clock.instant()); + sessionContext, + DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world), + world.slug(), + clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); @@ -568,7 +544,11 @@ public JoinMembershipResult joinPublicProductionMembership( try { maybeJoinScope = connectScopeSessionStore.publicProductionScopeForJoin( - sessionContext, worldSelector, worldTenantId(world), world.slug(), clock.instant()); + sessionContext, + worldSelector, + DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world), + world.slug(), + clock.instant()); } catch (DirectTextConnectScopeSessionStore.StoreUnavailableException | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); @@ -584,7 +564,7 @@ public JoinMembershipResult joinPublicProductionMembership( } catch (NumberFormatException ex) { return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - if (tenantId != worldTenantId(world)) { + if (tenantId != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world)) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } boolean hasPublicProductionRealm; @@ -606,12 +586,6 @@ public JoinMembershipResult joinPublicProductionMembership( playerContext, scope.connectScopeId(), requestId, scope.expiresAt())); } - private static long worldTenantId(GameplayWorldCatalog.WorldView world) { - List tenantIds = - world.realms().stream().map(GameplayWorldCatalog.RealmView::tenantId).distinct().toList(); - return tenantIds.size() == 1 ? tenantIds.getFirst() : -1L; - } - private static String normalizeSelector(String selector) { return selector == null ? "" : selector.trim().toLowerCase(java.util.Locale.ROOT); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index e73d976359..fb8d941f35 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -50,15 +50,16 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request } private TextCommandInterpretationResult handleWorlds(TextCommandDispatchRequest request) { + if (!hasPositiveTransportSessionId(request.sessionId())) { + return errorResult( + "INVALID_ARGUMENT", "Transport session is unavailable. Reconnect and try again."); + } try { return new TextCommandInterpretationResult( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( worldsHandler.browseView(request.sessionId(), request.sessionContext())))); - } catch (IllegalArgumentException ex) { - return errorResult( - "INVALID_ARGUMENT", "Transport session is unavailable. Reconnect and try again."); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return errorResult("AUTH_UNAVAILABLE", "World list is temporarily unavailable."); } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { @@ -70,6 +71,21 @@ private TextCommandInterpretationResult handleWorlds(TextCommandDispatchRequest } } + private boolean hasPositiveTransportSessionId(String sessionId) { + if (sessionId == null || sessionId.isBlank()) { + return false; + } + String trimmed = sessionId.trim(); + if (!trimmed.chars().allMatch(Character::isDigit)) { + return false; + } + try { + return Long.parseLong(trimmed) > 0L; + } catch (NumberFormatException ex) { + return false; + } + } + private TextCommandInterpretationResult handleRealms(TextCommandDispatchRequest request) { if (request.command().realmBrowsePayload().isEmpty() || request.sessionContext().isEmpty()) { return errorResult("INVALID_ARGUMENT", "REALMS requires a world selector after LOGIN."); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index 3e2a6234db..279e983c5f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -1132,28 +1132,6 @@ private LobbyRecord withWorldSnapshot( realmsByWorld); } - private LobbyRecord withWorldSnapshotFrom(LobbyRecord other) { - return new LobbyRecord( - sessionId, - accountId, - other.worldsExpiresAtEpochMs(), - other.catalogFingerprint(), - other.ordinalTargets(), - scopesByWorld, - realmsByWorld); - } - - private LobbyRecord withAccountId(long updatedAccountId) { - return new LobbyRecord( - sessionId, - updatedAccountId, - worldsExpiresAtEpochMs, - catalogFingerprint, - ordinalTargets, - scopesByWorld, - realmsByWorld); - } - private LobbyRecord withScopes(Map> updatedScopes) { return new LobbyRecord( sessionId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 126fe22281..5743af68d6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -48,6 +48,7 @@ import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; @@ -100,6 +101,69 @@ void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() t assertThat(captor.getValue().getPointerVersion()).isEqualTo(4L); } + @ParameterizedTest + @EnumSource(Status.Code.class) + void directTextScopeNormalizesEveryGrpcTransportStatusToAuthUnavailable(Status.Code statusCode) + throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.issueDirectTextConnectScope(any(IssueDirectTextConnectScopeRequest.class))) + .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); + AccountClient client = newClient(stub); + DirectTextConnectScopeTarget target = + new DirectTextConnectScopeTarget( + "22", + "demo-world", + "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "42d234a2-7487-4dda-a7e5-a3831214328e", + "SHARED", + "9", + 7L, + 4L); + + IssueDirectTextConnectScopeResponse response = + client.issueDirectTextConnectScope(directTextContext("request-unused"), target); + + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("AUTH_UNAVAILABLE"); + } + + @Test + void directTextScopePreservesCanonicalApplicationErrorCode() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + IssueDirectTextConnectScopeResponse expected = + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("CONNECT_SCOPE_MISMATCH") + .setMessage("The selected scope no longer matches the target.")) + .build(); + when(stub.issueDirectTextConnectScope(any(IssueDirectTextConnectScopeRequest.class))) + .thenReturn(expected); + AccountClient client = newClient(stub); + DirectTextConnectScopeTarget target = + new DirectTextConnectScopeTarget( + "22", + "demo-world", + "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "42d234a2-7487-4dda-a7e5-a3831214328e", + "SHARED", + "9", + 7L, + 4L); + + IssueDirectTextConnectScopeResponse response = + client.issueDirectTextConnectScope(directTextContext("request-unused"), target); + + assertThat(response).isEqualTo(expected); + assertThat(response.getError().getCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + } + @Test void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { TestClock clock = new TestClock(JOIN_TEST_NOW); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java new file mode 100644 index 0000000000..0816d86df9 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java @@ -0,0 +1,307 @@ +package net.firedevops.firemud.gamesession.command.text; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.DiscoverySnapshot; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmDiscoverySnapshot; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; +import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore.WorldsSnapshot; +import net.firedevops.firemud.gamesession.service.SessionContext; +import org.junit.jupiter.api.Test; + +class DirectTextOrdinalSelectionResolverTest { + private static final Instant NOW = Instant.parse("2030-05-06T07:08:09Z"); + + private final SessionContext caller = + new SessionContext(7L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + private final RealmView realm = + new RealmView( + "production", + "Production", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.fromString("00000000-0000-0000-0000-000000000001"), + UUID.fromString("00000000-0000-0000-0000-000000000002")); + private final WorldView world = new WorldView("demo", "Demo", List.of(realm)); + private final GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(List.of(world)); + private final DiscoverySnapshot worlds = catalog.readDiscoverySnapshot(); + private final RealmDiscoverySnapshot realms = catalog.readRealmDiscoverySnapshot(world); + + @Test + void resolvesWorldAndRealmOrdinalsAgainstCurrentBoundSnapshots() { + DirectTextConnectScopeSessionStore store = DirectTextConnectScopeSessionStore.inMemoryForTest(); + store.replaceWorldSnapshot( + caller.sessionId(), + caller.accountId(), + worlds.catalogFingerprint(), + worlds.ordinalTargets(), + NOW); + store.replaceRealmSnapshot( + caller, + "demo", + 22L, + "demo", + realms.catalogFingerprint(), + realms.ordinalTargets(), + List.of(), + NOW); + + var worldResult = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + "1", store, caller, NOW, worlds, catalog); + var realmResult = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", store, caller, 22L, world, NOW, () -> realms, catalog); + + assertThat(worldResult.selectedValue()).contains(world); + assertThat(realmResult.selectedValue()).contains(realm); + assertThat(DirectTextOrdinalSelectionResolver.resolveWorldTenantId(world)) + .isEqualTo(new DirectTextOrdinalSelectionResolver.UniqueWorldTenantId(22L)); + } + + @Test + void absentAndExpiredWorldSnapshotsRemainUnbound() { + var absent = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + "1", () -> Optional.empty(), NOW, worlds, ignored -> Optional.of(world)); + var expired = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + "1", + () -> + Optional.of( + new WorldsSnapshot(worlds.catalogFingerprint(), NOW, worlds.ordinalTargets())), + NOW, + worlds, + ignored -> Optional.of(world)); + + assertThat(absent).isInstanceOf(DirectTextOrdinalSelectionResolver.UnboundSelector.class); + assertThat(expired).isInstanceOf(DirectTextOrdinalSelectionResolver.UnboundSelector.class); + } + + @Test + void absentAndExpiredRealmSnapshotsRemainUnbound() { + var absent = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + () -> Optional.empty(), + 22L, + world, + NOW, + () -> realms, + (current, target) -> Optional.of(realm)); + var expiredSnapshot = + new DirectTextConnectScopeSessionStore.RealmsSnapshot( + "demo", 22L, "demo", realms.catalogFingerprint(), NOW, realms.ordinalTargets()); + var expired = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + () -> Optional.of(expiredSnapshot), + 22L, + world, + NOW, + () -> realms, + (current, target) -> Optional.of(realm)); + + assertThat(absent).isInstanceOf(DirectTextOrdinalSelectionResolver.UnboundSelector.class); + assertThat(expired).isInstanceOf(DirectTextOrdinalSelectionResolver.UnboundSelector.class); + } + + @Test + void malformedAndOutOfRangeOrdinalsRemainUnbound() { + var snapshot = + new WorldsSnapshot( + worlds.catalogFingerprint(), NOW.plusSeconds(30), worlds.ordinalTargets()); + + for (String selector : List.of("2147483648", "0", "99")) { + var result = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + selector, () -> Optional.of(snapshot), NOW, worlds, ignored -> Optional.of(world)); + assertThat(result) + .as("selector %s", selector) + .isInstanceOf(DirectTextOrdinalSelectionResolver.UnboundSelector.class); + } + + for (String selector : List.of("2147483648", "0", "99")) { + var result = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + selector, + () -> Optional.of(currentRealmsSnapshot()), + 22L, + world, + NOW, + () -> realms, + (current, target) -> Optional.of(realm)); + assertThat(result) + .as("realm selector %s", selector) + .isInstanceOf(DirectTextOrdinalSelectionResolver.UnboundSelector.class); + } + } + + @Test + void changedFingerprintOrCurrentTargetIsSnapshotMismatch() { + var changedFingerprint = + new WorldsSnapshot("changed", NOW.plusSeconds(30), worlds.ordinalTargets()); + var fingerprintResult = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + "1", () -> Optional.of(changedFingerprint), NOW, worlds, ignored -> Optional.of(world)); + var targetResult = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + "1", + () -> Optional.of(currentWorldsSnapshot()), + NOW, + worlds, + ignored -> Optional.empty()); + + assertThat(fingerprintResult) + .isInstanceOf(DirectTextOrdinalSelectionResolver.SnapshotMismatch.class); + assertThat(targetResult) + .isInstanceOf(DirectTextOrdinalSelectionResolver.SnapshotMismatch.class); + + var staleRealmSnapshot = + new DirectTextConnectScopeSessionStore.RealmsSnapshot( + "demo", 22L, "demo", "changed", NOW.plusSeconds(30), realms.ordinalTargets()); + var realmFingerprintResult = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + () -> Optional.of(staleRealmSnapshot), + 22L, + world, + NOW, + () -> realms, + (current, target) -> Optional.of(realm)); + var realmTargetResult = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + () -> Optional.of(currentRealmsSnapshot()), + 22L, + world, + NOW, + () -> realms, + (current, target) -> Optional.empty()); + + assertThat(realmFingerprintResult) + .isInstanceOf(DirectTextOrdinalSelectionResolver.SnapshotMismatch.class); + assertThat(realmTargetResult) + .isInstanceOf(DirectTextOrdinalSelectionResolver.SnapshotMismatch.class); + } + + @Test + void unavailableOrConflictingStoreAndPointerFailuresRemainDistinct() { + var missingWorldStore = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + "1", null, caller, NOW, worlds, catalog); + var missingRealmStore = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", null, caller, 22L, world, NOW, () -> realms, catalog); + var unavailableStore = + DirectTextOrdinalSelectionResolver.resolveWorldOrdinal( + "1", + () -> { + throw new DirectTextConnectScopeSessionStore.StoreUnavailableException("read failed"); + }, + NOW, + worlds, + ignored -> Optional.of(world)); + var conflictingStore = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + () -> { + throw new DirectTextConnectScopeSessionStore.ConflictingIdentityException( + "identity mismatch"); + }, + 22L, + world, + NOW, + () -> realms, + (current, target) -> Optional.of(realm)); + var unavailablePointer = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + () -> Optional.of(currentRealmsSnapshot()), + 22L, + world, + NOW, + () -> { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "read failed"); + }, + (current, target) -> Optional.of(realm)); + var invalidPointer = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + () -> Optional.of(currentRealmsSnapshot()), + 22L, + world, + NOW, + () -> { + throw new GameplayWorldCatalog.AuthorityPointerUnavailableException("invalid"); + }, + (current, target) -> Optional.of(realm)); + + assertThat(unavailableStore).isInstanceOf(DirectTextOrdinalSelectionResolver.Unavailable.class); + assertThat(missingWorldStore) + .isInstanceOf(DirectTextOrdinalSelectionResolver.Unavailable.class); + assertThat(missingRealmStore) + .isInstanceOf(DirectTextOrdinalSelectionResolver.Unavailable.class); + assertThat(conflictingStore).isInstanceOf(DirectTextOrdinalSelectionResolver.Unavailable.class); + assertThat(unavailablePointer) + .isInstanceOf(DirectTextOrdinalSelectionResolver.Unavailable.class); + assertThat(invalidPointer) + .isInstanceOf(DirectTextOrdinalSelectionResolver.PointerUnavailable.class); + } + + @Test + void ambiguousWorldTenantDoesNotProduceAnAuthorityIdentity() { + WorldView ambiguousWorld = + new WorldView( + "demo", + "Demo", + List.of( + realm, + new RealmView( + "preview", + "Preview", + 23L, + 2L, + 1L, + true, + false, + false, + "SHARED", + "ALLOW_NEW", + 1L))); + + assertThat(DirectTextOrdinalSelectionResolver.resolveWorldTenantId(ambiguousWorld)) + .isInstanceOf(DirectTextOrdinalSelectionResolver.AmbiguousWorldTenantId.class); + assertThat(DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(ambiguousWorld)) + .isEqualTo(-1L); + } + + private WorldsSnapshot currentWorldsSnapshot() { + return new WorldsSnapshot( + worlds.catalogFingerprint(), NOW.plusSeconds(30), worlds.ordinalTargets()); + } + + private DirectTextConnectScopeSessionStore.RealmsSnapshot currentRealmsSnapshot() { + return new DirectTextConnectScopeSessionStore.RealmsSnapshot( + "demo", + 22L, + "demo", + realms.catalogFingerprint(), + NOW.plusSeconds(30), + realms.ordinalTargets()); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index c01fd5dbc7..460747f0dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.command.text; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; import java.time.Instant; @@ -34,6 +35,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class WorldsTextCommandDispatchHandlerTest { @@ -131,6 +133,95 @@ void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); } + @ParameterizedTest + @ValueSource(strings = {"malformed", "0", "-7"}) + void worldsRejectsInvalidTransportSessionIdBeforeCatalogStoreOrEventDispatch( + String transportSessionId) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + DirectTextConnectScopeSessionStore store = + Mockito.mock(DirectTextConnectScopeSessionStore.class); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + new GameplayWorldCatalog(authorityService), + entityManagementClient, + Mockito.mock(AccountClient.class), + store), + scriptEventPublisher); + + TextCommandInterpretationResult result = + scopedHandler.handle(worldsRequest(transportSessionId)); + + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + Mockito.verifyNoInteractions( + authorityService, store, entityManagementClient, scriptEventPublisher); + } + + @Test + void worldsDoesNotTranslateCatalogIllegalArgumentExceptionToInvalidArgument() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + throw new IllegalArgumentException("catalog invariant failed"); + }); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + catalog, + entityManagementClient, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); + + assertThatThrownBy(() -> scopedHandler.handle(worldsRequest("7"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("catalog invariant failed"); + Mockito.verifyNoInteractions(scriptEventPublisher); + } + + @Test + void worldsDoesNotTranslateStoreIllegalArgumentExceptionToInvalidArgument() { + DirectTextConnectScopeSessionStore store = + Mockito.mock(DirectTextConnectScopeSessionStore.class); + Mockito.doThrow(new IllegalArgumentException("store invariant failed")) + .when(store) + .replaceWorldSnapshot( + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.anyString(), + Mockito.anyList(), + Mockito.any(Instant.class)); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + GameplayWorldCatalog.forWorldViews(List.of()), + entityManagementClient, + Mockito.mock(AccountClient.class), + store), + scriptEventPublisher); + + assertThatThrownBy(() -> scopedHandler.handle(worldsRequest("7"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("store invariant failed"); + Mockito.verify(store) + .replaceWorldSnapshot( + Mockito.eq(7L), + Mockito.eq(0L), + Mockito.anyString(), + Mockito.anyList(), + Mockito.any(Instant.class)); + Mockito.verifyNoInteractions(scriptEventPublisher); + } + + private static TextCommandDispatchRequest worldsRequest(String transportSessionId) { + return new TextCommandDispatchRequest( + transportSessionId, + new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), + false, + Optional.empty()); + } + @Test void publishesCommandEventForGameplayScopedRealmsBrowse() { gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 22L, 2L, false))); From cb8f25f5c8108434e3e9b0cb8fcc1552759e320d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 19:21:40 +1300 Subject: [PATCH 051/105] test: refresh shared Account authority evaluation evidence --- .../test/AccountRuntimeStubServerTest.java | 92 +++++++++++++++++++ .../test/AccountRuntimeStubServer.java | 14 ++- 2 files changed, 102 insertions(+), 4 deletions(-) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index abc3e59a76..77891d456b 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -4,15 +4,74 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.common.account.AccountProfileJson; import org.junit.jupiter.api.Test; class AccountRuntimeStubServerTest { + @Test + void runtimeAuthorityResponsesUseCurrentInjectedClockTime() throws Exception { + Instant firstEvaluation = Instant.parse("2026-03-30T00:00:00Z"); + Instant nextEvaluation = firstEvaluation.plusSeconds(1); + MutableClock clock = new MutableClock(firstEvaluation, ZoneOffset.UTC); + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0, clock)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + var membershipRequest = + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-1") + .build(); + var grantRequest = + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setWorldSlug("world") + .setRealmSlug("realm") + .setRequestId("request-1") + .build(); + var entitlementsRequest = + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("request-1") + .build(); + + assertThat(stub.getTenantMembershipForRuntime(membershipRequest).getEvaluatedAt()) + .isEqualTo(firstEvaluation.toString()); + assertThat(stub.getRealmAccessGrantForRuntime(grantRequest).getEvaluatedAt()) + .isEqualTo(firstEvaluation.toString()); + assertThat(stub.getTenantEntitlementsForRuntime(entitlementsRequest).getEvaluatedAt()) + .isEqualTo(firstEvaluation.toString()); + + clock.setInstant(nextEvaluation); + + assertThat(stub.getTenantMembershipForRuntime(membershipRequest).getEvaluatedAt()) + .isEqualTo(nextEvaluation.toString()); + assertThat(stub.getRealmAccessGrantForRuntime(grantRequest).getEvaluatedAt()) + .isEqualTo(nextEvaluation.toString()); + assertThat(stub.getTenantEntitlementsForRuntime(entitlementsRequest).getEvaluatedAt()) + .isEqualTo(nextEvaluation.toString()); + } finally { + channel.shutdownNow(); + } + } + } + @Test void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() throws Exception { @@ -129,4 +188,37 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { } } } + + private static final class MutableClock extends Clock { + private final AtomicReference instant; + private final ZoneId zone; + + private MutableClock(Instant instant, ZoneId zone) { + this(new AtomicReference<>(instant), zone); + } + + private MutableClock(AtomicReference instant, ZoneId zone) { + this.instant = instant; + this.zone = zone; + } + + private void setInstant(Instant instant) { + this.instant.set(instant); + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId zone) { + return new MutableClock(instant, zone); + } + + @Override + public Instant instant() { + return instant.get(); + } + } } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 4bb8d1f7a5..e34eeee3d5 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -4,6 +4,7 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.Map; @@ -40,7 +41,6 @@ /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase implements AutoCloseable { - private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; private static final Set IMPLEMENTED_RUNTIME_METHODS = Set.of( "Ping", @@ -52,6 +52,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe "JoinPublicProductionMembership"); private final Server server; + private final Clock clock; private final List authenticateRequests = new CopyOnWriteArrayList<>(); private final AtomicBoolean membershipExists = new AtomicBoolean(true); private final AtomicBoolean gameplayAdmissionAllowed = new AtomicBoolean(true); @@ -65,6 +66,11 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final Map connectScopesById = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { + this(port, Clock.systemUTC()); + } + + public AccountRuntimeStubServer(int port, Clock clock) throws IOException { + this.clock = java.util.Objects.requireNonNull(clock, "clock"); this.server = NettyServerBuilder.forPort(port).addService(this).build().start(); } @@ -175,7 +181,7 @@ public void getTenantMembershipForRuntime( .setMembershipVersion(exists ? 1L : 0L) .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") .setMembershipAuthorityGeneration(exists ? 1L : 0L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } @@ -192,7 +198,7 @@ public void getRealmAccessGrantForRuntime( .setRealmSlug(request.getRealmSlug()) .setGranted(realmAccessGranted.get()) .setGrantVersion(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } @@ -208,7 +214,7 @@ public void getTenantEntitlementsForRuntime( .setAllowPublicJoin(allowPublicJoin.get()) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } From 53db3bf21fda16956d6ecf30049622b60469d86e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 23:26:59 +1300 Subject: [PATCH 052/105] Bound direct-text JOIN terminal transport failures --- .../gamesession/client/AccountClient.java | 2 +- .../gamesession/client/AccountClientTest.java | 72 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 059a2433d1..66cebce70c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -279,7 +279,7 @@ public JoinPublicProductionMembershipResponse joinPublicProductionMembership( return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); } logger.warn("Account direct-text JOIN returned a terminal transport status", ex); - return joinError(ex.getStatus().getCode().name(), "Account JOIN request failed"); + return joinError("JOIN_FAILED", "Account JOIN request failed"); } catch (Exception ex) { logger.warn("Account direct-text JOIN did not complete", ex); return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 5743af68d6..d135a4182a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -204,6 +204,78 @@ void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); } + @ParameterizedTest + @EnumSource( + value = Status.Code.class, + mode = EnumSource.Mode.EXCLUDE, + names = {"OK", "UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void directTextJoinMapsTerminalTransportStatusesToBoundedFailureWithoutRetry( + Status.Code statusCode) throws Exception { + RetryFixture fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + String upstreamDescription = "private account-service detail"; + when(fixture + .initialStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenThrow( + new StatusRuntimeException( + Status.fromCode(statusCode).withDescription(upstreamDescription))); + + JoinPublicProductionMembershipResponse response = + fixture + .client() + .joinPublicProductionMembership( + directTextContext("join-request-1"), + "account-issued-scope", + "join-request-1", + JOIN_TEST_NOW.plusSeconds(60)); + + assertThat(response.getOutcomeCode()).isEqualTo("JOIN_FAILED"); + assertThat(response.getError().getCode()).isEqualTo("JOIN_FAILED"); + assertThat(response.getError().getMessage()).isEqualTo("Account JOIN request failed"); + assertThat(response.getError().getMessage()).doesNotContain(upstreamDescription); + verify(fixture.initialStub()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.retryStub(), never()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void directTextJoinPreservesTypedAccountApplicationResponse() throws Exception { + RetryFixture fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + JoinPublicProductionMembershipResponse expected = + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("JOIN_NOT_ELIGIBLE") + .setAccountId("41") + .setTenantId("22") + .setError( + ErrorDetail.newBuilder() + .setCode("JOIN_NOT_ELIGIBLE") + .setMessage("This account cannot join the selected world.")) + .build(); + when(fixture + .initialStub() + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class))) + .thenReturn(expected); + + JoinPublicProductionMembershipResponse response = + fixture + .client() + .joinPublicProductionMembership( + directTextContext("join-request-1"), + "account-issued-scope", + "join-request-1", + JOIN_TEST_NOW.plusSeconds(60)); + + assertThat(response).isEqualTo(expected); + verify(fixture.retryStub(), never()) + .joinPublicProductionMembership(any(JoinPublicProductionMembershipRequest.class)); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + @Test void directTextJoinDoesNotDispatchForMissingExpiredOrBoundaryScope() throws Exception { TestClock clock = new TestClock(JOIN_TEST_NOW); From d68d34d1a360a3ba8dbca476bfcf5fd4e333cd6e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 23:50:18 +1300 Subject: [PATCH 053/105] fix(gameplay): distinguish stale PLAY selections --- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/protocols.md | 2 +- .../command/text/PlayCommandHandler.java | 12 ++++++------ .../resources/presentation-messages.properties | 1 + .../presentation-messages_fr.properties | 1 + .../command/text/PlayCommandHandlerTest.java | 17 ++++++++++++----- 6 files changed, 22 insertions(+), 13 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 8dca0c9288..f6933d5f25 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -28,7 +28,7 @@ The current public registration path creates only a global Account row and a pla Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live `GetTenantMembershipForRuntime` response and Account producer carry `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. Text `PLAY` validates the exact account/tenant identity, lifecycle, admission, positive membership version and authority generation for an existing member, and evaluation time before binding. It requires `ACTIVE` membership for admission; only `MISSING` or `INACTIVE` membership can yield public `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks pass. Account connect-token issuance and character discovery still rely on the older membership/admission/version/time fields and do not enforce the emitted lifecycle state or authority generation; a cached-success connect-token replay can return before fresh entitlement, membership, or pointer reads. The response still omits `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints`, so these checks do not prove a complete Account authority snapshot or resolve the reader exposure below. +The `GetTenantMembershipForRuntime` proto and Account producer shape carry `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The positive live reader remains fail-closed until positive membership data is available. Text `PLAY` validates the exact account/tenant identity, lifecycle, admission, positive membership version and authority generation for an existing member, and evaluation time before binding. It requires `ACTIVE` membership for admission; only `MISSING` or `INACTIVE` membership can yield public `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks pass. Account connect-token issuance and character discovery still rely on the older membership/admission/version/time fields and do not enforce the emitted lifecycle state or authority generation; a cached-success connect-token replay can return before fresh entitlement, membership, or pointer reads. The response still omits `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints`, so these checks do not prove a complete Account authority snapshot or resolve the reader exposure below. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Account owns the explicit `JoinPublicProductionMembership` writer and its REST controller/operation; Game Session direct-text `REALMS`/`JOIN` now uses the retained Account-issued scope and invokes that writer locally. The Gateway route guard still blocks external exposure of `POST /auth/bootstrap/join`; first-party `Join & Play` remains unavailable. On a fresh connect-token issuance or cache miss, Account rechecks selected target, pointer, entitlement, membership, and runtime target, but does not revalidate the applicable private/playtest grant or establish the target membership-version/authority-generation issuance baseline. Exact target/pointer evidence is reread before the JOIN transaction, but no proof binds target validity through Account commit; the strict ADR 0025 commit fence remains incomplete. Recovery after an unknown database commit outcome remains open under ADR 0025/#2848, with no background PENDING-operation reconciler. Exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, broader reconnect/cutover consumption of admission-pointer truth, operator-facing pointer tooling, and the target issuance membership-generation snapshot remain incomplete. `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`; its current response shape and target routing semantics remain distinct. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 4f1b52dee2..a2b181c68a 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -82,7 +82,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. Target `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot. `[character]` currently accepts a character name; a response-local character index is target-only and is not implemented. Current world and realm menu indices are bound to their exact connection-local response snapshots and catalog revisions, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. Current Game Session pointer snapshots carry numeric `tenantId` and `worldSlug` but no `tenantSlug`; local `WORLDS` renders only the bare world slug, and REALMS/JOIN/PLAY resolve it only when the current catalog has no duplicate world slug across tenants. This current shortcut is implementation drift: the target never resolves a bare `worldSlug` globally, and `REALMS demo/demo` and `JOIN demo/demo` remain target examples rather than current accepted forms. +Selector rules for `PLAY` match the lobby helpers. Target `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot. `[character]` currently accepts a character name; a response-local character index is target-only and is not implemented. Current world and realm menu indices are bound to their exact connection-local response snapshots and catalog revisions, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired or invalidated world/realm snapshot returns `SELECTION_STALE` and directs the player to refresh `WORLDS` or `REALMS`. Ambiguous or invalid selectors require the player to list again rather than being guessed. `CONNECT_SCOPE_MISMATCH` remains reserved for a validated connect context that does not match the server-resolved requested scope. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. Current Game Session pointer snapshots carry numeric `tenantId` and `worldSlug` but no `tenantSlug`; local `WORLDS` renders only the bare world slug, and REALMS/JOIN/PLAY resolve it only when the current catalog has no duplicate world slug across tenants. This current shortcut is implementation drift: the target never resolves a bare `worldSlug` globally, and `REALMS demo/demo` and `JOIN demo/demo` remain target examples rather than current accepted forms. ### JOIN Translation and Status diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index fb279af147..adaa51cde8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -248,9 +248,9 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } if (worldSelection instanceof WorldSelectorResolution.Stale) { return failure( - "CONNECT_SCOPE_MISMATCH", + "SELECTION_STALE", "World selection is stale; run WORLDS again.", - "error.play.connect-scope-mismatch", + "error.play.selection-stale", Map.of(), tenantTag, null, @@ -294,9 +294,9 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } if (realmSelection instanceof RealmSelectorResolution.Stale) { return failure( - "CONNECT_SCOPE_MISMATCH", + "SELECTION_STALE", "Realm selection is stale; run REALMS again.", - "error.play.connect-scope-mismatch", + "error.play.selection-stale", Map.of(), tenantTag, null, @@ -335,9 +335,9 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } if (realmSelection instanceof RealmSelectorResolution.Stale) { return failure( - "CONNECT_SCOPE_MISMATCH", + "SELECTION_STALE", "Realm selection is stale; run REALMS again.", - "error.play.connect-scope-mismatch", + "error.play.selection-stale", Map.of(), tenantTag, null, diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 39c86de9a5..14f0e68bd5 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -20,6 +20,7 @@ error.play.realm-selection-required=Selection required. Use PLAY {worldSlug} first, then JOIN . error.play.public-production-admission-denied=Public joining is not available for this world. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 88f789826a..c76b86897d 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -20,6 +20,7 @@ error.play.realm-selection-required=Sélection requise. Utilisez PLAY {worldSlug error.play.character-selection-required=Selection requise. Utilisez {playUsage} ou consultez {charsUsage} dabord. error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. +error.play.selection-stale=Cette sélection a expiré. Relancez WORLDS ou REALMS, puis réessayez PLAY. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. error.play.join-required=Une adhésion est requise avant PLAY. Consultez d’abord REALMS , puis utilisez JOIN . error.play.public-production-admission-denied=L’adhésion publique n’est pas disponible pour ce monde. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index e3e5ad461e..02c5950e90 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -443,7 +443,14 @@ void numericWorldPlayRejectsReorderedWorldSnapshotBeforeAdmissionSideEffects() { handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("1"), "PLAY 1")); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + assertThat(result.commandResult().errorCode()).isEqualTo("SELECTION_STALE"); + ErrorOutput staleSelection = (ErrorOutput) result.outputs().getFirst().payload(); + assertThat(staleSelection.messageKey()).isEqualTo("error.play.selection-stale"); + assertThat( + new TextPlayerOutputRenderer(new PresentationProperties()) + .render(result.outputs().getFirst(), "fr")) + .isEqualTo( + "ERROR SELECTION_STALE Cette sélection a expiré. Relancez WORLDS ou REALMS, puis réessayez PLAY."); Mockito.verifyNoInteractions( accountClient, entityManagementClient, @@ -634,7 +641,7 @@ void numericWorldCharacterPlayRejectsStaleWorldSnapshotBeforeAdmissionSideEffect "1", new TextCommand(TextCommandType.PLAY, List.of("1", "Sora"), "PLAY 1 Sora")); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + assertThat(result.commandResult().errorCode()).isEqualTo("SELECTION_STALE"); Mockito.verifyNoInteractions( accountClient, entityManagementClient, @@ -656,7 +663,7 @@ void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "1"), "PLAY demo 1")); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + assertThat(result.commandResult().errorCode()).isEqualTo("SELECTION_STALE"); Mockito.verifyNoInteractions( accountClient, entityManagementClient, @@ -819,7 +826,7 @@ void numericPlayRealmFailsClosedForWrongTenantOrStaleRealmSnapshot() { new TextCommand( TextCommandType.PLAY, List.of(worldSelector, "1"), "PLAY " + worldSelector + " 1")); assertThat(wrongTenantResult.commandResult().accepted()).isFalse(); - assertThat(wrongTenantResult.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + assertThat(wrongTenantResult.commandResult().errorCode()).isEqualTo("SELECTION_STALE"); // The right tenant key still fails when its retained REALMS fingerprint is stale. connectScopeSessionStore.replaceRealmSnapshot( @@ -838,7 +845,7 @@ void numericPlayRealmFailsClosedForWrongTenantOrStaleRealmSnapshot() { TextCommandType.PLAY, List.of(worldSelector, "1"), "PLAY " + worldSelector + " 1")); assertThat(staleResult.commandResult().accepted()).isFalse(); - assertThat(staleResult.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + assertThat(staleResult.commandResult().errorCode()).isEqualTo("SELECTION_STALE"); Mockito.verifyNoInteractions(accountClient, entityManagementClient, moderationPolicyClient); } From 8b61cfa38be1d98e1395efe16afbda4166d7ccdb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:56:21 +1300 Subject: [PATCH 054/105] Carry canonical account UUIDs and add bounded owner identity reads --- .../account-service/api-contracts.md | 13 + .../game-design-service/README.md | 4 +- .../game-design-service/api-contracts.md | 17 + ...ame-authoring-publishing-and-activation.md | 3 + .../player-access-and-session.md | 6 +- .../v1/runtime_account_identity_service.proto | 28 ++ .../v1/tenant_identity_service.proto | 27 ++ .../controller/AccountController.java | 36 +- .../controller/AccountRequestReaders.java | 18 + .../controller/ProfileController.java | 15 +- .../dto/AuthenticationResult.java | 21 +- .../dto/PlayerBootstrapResult.java | 2 +- .../service/impl/AccountGrpcService.java | 73 +++- .../service/impl/AccountServiceImpl.java | 77 ++-- .../RuntimeAccountIdentityGrpcService.java | 185 ++++++++++ .../src/main/resources/application-prod.yml | 1 + .../src/main/resources/application.yml | 2 + .../src/main/resources/openapi.yaml | 26 +- .../controller/AccountControllerTest.java | 54 ++- .../controller/AuthControllerTest.java | 21 +- .../controller/ProfileControllerTest.java | 63 ++-- .../PublicBootstrapRoutesProdProfileTest.java | 7 +- .../dto/AuthenticationResultTest.java | 28 ++ ...timeAccountIdentityGrpcAuthWiringTest.java | 327 +++++++++++++++++ .../service/impl/AccountGrpcServiceTest.java | 212 +++++++---- .../service/impl/AccountServiceImplTest.java | 345 ++++++++++++++++-- ...RuntimeAccountIdentityGrpcServiceTest.java | 242 ++++++++++++ .../RuntimeAccountIdentityEvidence.java | 54 +++ ...pcServerPeerIdentityClientInterceptor.java | 89 +++++ .../tenant/RuntimeTenantIdentityEvidence.java | 53 +++ .../RuntimeAccountIdentityEvidenceTest.java | 124 +++++++ ...rverPeerIdentityClientInterceptorTest.java | 206 +++++++++++ .../RuntimeTenantIdentityEvidenceTest.java | 121 ++++++ .../common/security/GrpcClientAuth.java | 6 +- .../firemud/common/security/JwtClaims.java | 31 +- .../common/security/GrpcClientAuthTest.java | 27 +- .../common/security/JwtClaimsTest.java | 57 ++- .../client/AccountRuntimeIdentityClient.java | 164 +++++++++ .../AccountRuntimeIdentityClientTest.java | 313 ++++++++++++++++ .../firemud/gamedesign/entity/Game.java | 2 + .../firemud/gamedesign/mapper/GameMapper.java | 2 + .../gamedesign/repository/GameRepository.java | 148 +++++++- .../repository/GameTenantIdentity.java | 15 + .../impl/TenantIdentityGrpcService.java | 168 +++++++++ .../src/main/resources/application.yml | 4 + .../V29__canonical_game_tenant_identity.sql | 68 ++++ ...nantIdentityRepositoryIntegrationTest.java | 177 +++++++++ .../TenantIdentityGrpcAuthWiringTest.java | 244 +++++++++++++ .../impl/TenantIdentityGrpcServiceTest.java | 206 +++++++++++ .../CommunicationAggregationService.java | 23 +- .../CommunicationAggregationServiceTest.java | 31 +- ...GameDesignRuntimeTenantIdentityClient.java | 164 +++++++++ .../gamesession/client/GameLogicClient.java | 9 +- .../command/text/LoginCommandHandler.java | 76 ++-- .../gamesession/service/AccountIds.java | 22 ++ .../service/FirstPartyConnectContext.java | 2 +- .../FirstPartyConnectContextResolution.java | 11 +- .../FirstPartyConnectContextService.java | 2 +- .../service/SessionAuthenticationService.java | 3 + .../gamesession/service/SessionContext.java | 3 +- .../impl/AccountPresenceQueryServiceImpl.java | 41 ++- .../service/impl/CommandServiceImpl.java | 21 +- .../service/impl/GameSessionGrpcService.java | 32 +- .../RedisAccountRecentPresenceService.java | 32 +- ...RedisFirstPartyConnectContextRegistry.java | 27 +- .../impl/RedisGameplayPresenceService.java | 24 +- .../impl/RedisSessionContextService.java | 13 +- ...DesignRuntimeTenantIdentityClientTest.java | 316 ++++++++++++++++ .../client/GameLogicClientTest.java | 83 +++-- .../command/text/LoginCommandHandlerTest.java | 198 +++++++--- ...irstPartyConnectContextResolutionTest.java | 80 ++++ .../FirstPartyConnectContextServiceTest.java | 65 ++-- .../SessionAuthenticationServiceTest.java | 25 +- .../service/SessionContextTest.java | 45 ++- .../AccountPresenceQueryServiceImplTest.java | 166 ++++++--- .../service/impl/CommandServiceImplTest.java | 97 +++-- .../impl/GameSessionGrpcServiceTest.java | 188 +++++----- ...RedisAccountRecentPresenceServiceTest.java | 186 +++++++--- ...sFirstPartyConnectContextRegistryTest.java | 31 +- .../RedisGameplayPresenceServiceTest.java | 157 ++++++-- .../impl/RedisSessionContextServiceTest.java | 56 +-- .../filter/GameplayHandshakeFilter.java | 2 +- .../filter/GameplayHandshakeFilterTest.java | 100 +++-- 83 files changed, 5686 insertions(+), 777 deletions(-) create mode 100644 protos/account/v1/runtime_account_identity_service.proto create mode 100644 protos/game-design/v1/tenant_identity_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 9f0a4fe06a..e7eca2a03b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -56,6 +56,8 @@ This target contract is not complete in the current service. The existing `secur Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). +`ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. Its focused service test passed 7/7 cases, and its shared auth-interceptor wiring test passed 3/3 cases, including the base and production configuration paths. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. + Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. @@ -112,6 +114,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, UUID provenance, and persisted source numeric row identity. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. @@ -127,6 +130,16 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. +### Runtime account identity owner read + +`RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity` reads Account's already-persisted canonical UUID and provenance for Account's own row. The protobuf in [`runtime_account_identity_service.proto`](../../../../protos/account/v1/runtime_account_identity_service.proto) is the wire authority; Account does not derive an identity from another owner's key or row. + +The only permitted peers are verified Game Session and Entity Management workload identities in the exact configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. The RPC is exempted by its exact full method name from bearer-token validation because it is workload-only; the listener remains mTLS-only, and the handler verifies the exact peer service and namespace. JWT claims and request metadata do not establish workload identity. + +The request contains exactly `canonical_account_id` and `request_id`; both must be canonical, lower-case, nonnil UUID strings, and unknown fields or invalid/missing values are rejected. The schema-version-1 response contains the configured `target_namespace`, exact echoed `request_id` and `canonical_account_id`, `source_account_row_id`, `account_uuid_provenance`, and `source_numeric_row_id`. Both source-row fields and the provenance value must come from the same persisted Account row whose UUID exactly matches the request selector. Numeric row values are provenance only and must not be used as gameplay identity. Account returns no partial evidence when persisted UUID/provenance/source-row evidence is missing, ambiguous, malformed, or inconsistent. + +This read is not an authentication, membership, entitlement, realm-grant, actor-owner, playable-state namespace, or admission decision. It creates no membership or grant and does not select or activate an actor. Game Session and Entity Management retain their respective runtime composition and admission contracts. + ### Operator Authorization References `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 598505a693..2c88de1b49 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -4,7 +4,7 @@ Offers tools for building worlds, items, actions, and events that make up each game. Used by creators to design content without touching the underlying code. It maintains version metadata, configuration manifests, and templates so new game instances can be created with predefined rules. Template creation does not provision administrator accounts; any future bootstrap flow must use Account-owned account, membership, and grant operations. -This service is used only at design time. Runtime clients never request logos, favicons, or themes from it. **Target state:** published assets are served from object storage via manifest files; the current private object-store URLs are not public client delivery, so approved public delivery remains deferred. +Creator authoring and publication are design-time operations. Game Design also exposes an authenticated, internal owner-local tenant-identity metadata read for Game Session; that narrow read does not make Game Design a gameplay or actor-entry authority. Runtime clients never request logos, favicons, or themes from it. **Target state:** published assets are served from object storage via manifest files; the current private object-store URLs are not public client delivery, so approved public delivery remains deferred. Authoritative read surfaces worth wiring into creator/operator tooling: @@ -16,6 +16,8 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved, because `GameAssetServiceImpl` uses `MultipartFile.getBytes()` without matching limits in `AssetStoreProperties`; upload admission and resource-safety readiness remain blocked. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. Publish/export later writes version-prefix objects and a manifest through the private object-store endpoint; target private-candidate/content-addressed publication and approved public `/assets/**` delivery remain unimplemented. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). +The owner-local tenant UUID read is implemented, but published realm-entry policy/descriptor/template production and Game Session/Entity admission composition remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused proof passed for the service (6/6), auth wiring (3/3), and shared evidence (2/2); the PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. See the exact API boundary and current proof record in [API Contracts](./api-contracts.md#runtime-tenant-identity-owner-read) and the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). + ## 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 6f2adfb281..5c8b76dd0a 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -35,6 +35,8 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. Full-version publish has a Temporal `publish` workflow path when Temporal is enabled. Its four owner-to-owner digest reads now use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; the authorization seam no longer depends on an empty-role JWT or an Automation admin-role fallback. End-to-end full-version publication remains blocked: the Game Logic owner digest fails closed because owner-local manifest and provenance for the version's rule inputs are absent, Automation's full-version content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see the explicit status below and [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). When the Temporal beans are disabled or absent, the synchronous `PublishVersion` path returns success only after its local terminal publish gates, release-attestation commit, Version finalization, and artifact publication complete; ordinary validation/export failures are surfaced explicitly. After a downstream exception, exact readback determines the outcome: if it proves that no release bundle or artifact exists and the candidate Version remains `DRAFT`, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row; best-effort object-store cleanup can still be uncertain. Complete release evidence is reconciled to success, while partial evidence remains pending for reconciliation. Restart-independent workflow durability and workflow runtime metadata are target/conditional properties of the Temporal path when its authorization, worker, and readback proofs are live; they are not properties of this synchronous fallback. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. +Game Design now issues a canonical tenant UUID on its owner `game` row and serves the authenticated owner-local `ResolveRuntimeTenantIdentity` read. Migration V29 records exact source-row/key provenance for valid retained keys and leaves blank or out-of-bounds retained keys quarantined without a canonical identity; row identity and provenance are immutable after issuance. This evidence is only a tenant-owner read: it does not publish realm-entry policy or resolve a realm descriptor/template, current realm pointer, playable-state namespace/scope, or actor admission. Reported focused proof: compilation and `generateJooq` succeeded, `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2; the PostgreSQL integration test compiled, but PostgreSQL execution remains unproved because Docker was unavailable. + The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. @@ -69,6 +71,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e ## gRPC APIs - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. +- `ResolveRuntimeTenantIdentity` – returns Game Design's persisted canonical tenant UUID and exact source-row/key provenance to Game Session; this owner-local metadata read does not resolve realm policy, realm routing, playable-state namespace/scope, or actor entry. - `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. @@ -95,6 +98,20 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `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. - `FinalizePurgeVersionAssets` – **Target state:** CAS-guarded purge completion that transitions purge-in-progress artifacts to `PURGED` after byte-deletion confirmation. The current implementation has no database CAS or shared idempotency ledger. +### Runtime tenant identity owner read + +`TenantIdentityService/ResolveRuntimeTenantIdentity` is an internal authenticated read of the canonical tenant identity persisted by Game Design for its own `game` row. The protobuf in [`tenant_identity_service.proto`](../../../../protos/game-design/v1/tenant_identity_service.proto) is the wire authority. The scoped durable-identity boundary remains [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) and [Multi-tenancy](../../system-architecture-multi-tenancy.md); this read does not derive or reassign another owner's identifiers. + +The only permitted peer is the verified Game Session workload identity `spiffe://firemud/ns/{namespace}/sa/game-session-service`, where `{namespace}` must exactly match Game Design's configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. An empty or invalid configured namespace, absent verified peer identity, another service identity, or a peer from another namespace returns `PERMISSION_DENIED`. JWT claims and request metadata are not peer identity; workload authentication follows [Authentication and Authorization](../../system-architecture-authentication.md). + +The shared `AuthTokenInterceptor` configuration exempts exactly this full RPC method name from bearer-token validation because this is a workload-only method under [ADR 0038](../../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). This is not public transport exposure: the gRPC listener still requires mTLS, and the handler requires the exact verified workload identity above. No other Game Design RPC is exempted. + +The request contains exactly two fields: `canonical_tenant_id` and `request_id`, each a canonical lower-case, nonnil UUID string. Unknown protobuf fields, noncanonical/nil IDs, or a missing ID return `INVALID_ARGUMENT`. The tenant UUID is only a selector: Game Design returns it only after an exact canonical-UUID lookup and owner-row provenance validation. + +The response fields are `schema_version` (currently `1`), `target_namespace` (the configured workload namespace, not a playable-state namespace), the exact echoed `request_id`, `canonical_tenant_id`, positive internal `source_game_row_id`, exact retained `source_game_tenant_key`, and `provenance_kind` (`RETAINED_GAME_V29` or `NEW_GAME_ROW`). The tenant UUID and source provenance are issued/read from the same Game Design owner row; callers must not translate the legacy key or row ID into another identity. + +Bounded transport outcomes are: `NOT_FOUND` when no owner row exists for the exact UUID; `FAILED_PRECONDITION` for missing, ambiguous, malformed, or inconsistent persisted provenance; `UNAVAILABLE` for unavailable storage/connection failures; and `INTERNAL` for other read failures. No partial evidence is returned on error. This method does not return a version-bound realm-entry policy, descriptor/template identity, current Game Session pointer, or playable-state namespace/scope; those owner compositions and [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md) actor-entry behavior remain separate, incomplete work. + These gRPC entries are the discoverability index for the control-plane contracts described in [Game Templates and Configuration Tools](game-templates.md) and related architecture docs. When request/response schemas evolve, the proto contract and those architecture sections must be updated in the same change so launch-resolution and template-phase semantics do not drift. ## REST & gRPC Endpoints 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 62c98d61e5..ca4a4faa4d 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. +Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; the issuance and source provenance are immutable. Reported compilation and `generateJooq` succeeded; focused `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2. The PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. This does not prove a Game Design-published version-bound realm-entry policy, descriptor/template identity, Game Session pointer/namespace/scope composition, Entity actor admission, or actor creation/activation. The method contract and status boundary are owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#runtime-tenant-identity-owner-read); actor-entry target behavior remains [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). + 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. @@ -178,6 +180,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the current participant observations and first World mutation handoff do not yet establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. The current implementation lacks the version-scoped asset mapping/authoring path and corresponding publication/export guard; purge and publication recovery also lack complete durable operation, CAS, and exact readback proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. +- Realm-authored controllable actor entry remains incomplete: no explicit published per-version `PLAYER_CREATED` / `PRESEEDED_ONLY` / `AUTO_PROVISIONED` policy with its required descriptor/template identity and version is resolved, and Game Session's current owner pointer/namespace/scope is not yet composed with Entity's fail-closed admission/creation path. The canonical tenant UUID read above supplies owner-row provenance only and is not entry-policy or actor-creation proof. - Normalized-template cutover phase is target-only: no tenant-scoped `GetTemplateReferencePhase` RPC, durable phase authority, or `BACKFILLING`/`VALIDATED`/`ENFORCED` consumer contract exists in the current slice; live launch checks only the per-template `ENFORCED`/`LEGACY` field. The target API and fail-before-launch behavior remain unimplemented and unproved. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. - World design authoring currently has the first typed revision-to-World handoff, including the transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. Broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain outside the current seam. 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 b3eeb9354c..e4b3bc707b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Account's persisted UUID now backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. Authentication results and JWTs, profile and tenant DTO identity fields, Game Session carriers, `PLAY`, and Entity Management remain outside this output slice. Numeric Account-claim consumers remain outside this slice in common-security `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, Social & Groups current-account authorization, and Game Session's numeric control-plane owner authorization. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no UUID-authentication or downstream runtime-proof upgrade. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). +Account's persisted UUID backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. The current candidate extends UUID identity through Account authentication, bootstrap, and profile producers and through the carrier paths described below; tenant identity fields and unrelated numeric-only consumers remain incomplete. Numeric Account-claim consumers still outside this cohort include common-security `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, Social & Groups current-account authorization, and Game Session's numeric control-plane owner authorization. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no deployed/fresh-runtime or global downstream migration proof. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). -Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. +This candidate now carries Account UUID through Account authentication, bootstrap, and profile producers; Common Security subject/account matching; Gateway gameplay-handshake validation; and Game Session and Game Logic carriers. Reported focused unit and formatting tasks passed for Account, Common Security, Gateway, Game Logic, and Game Design; the focused Game Session suite passed 262/262. This is candidate source/test proof, not deployed or fresh-runtime proof, and it does not establish global convergence of numeric Account consumers or backfill historical command UUIDs. Canonical identity and namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Account's `ResolveRuntimeAccountIdentity` owner read has focused service proof (7/7) and auth-wiring proof (3/3); Entity Management's Account identity receiver test passed 7/7. Those reads carry persisted UUID and source-row/provenance evidence but do not create membership, grants, actor ownership, a namespace, or admission authority; Game Session caller wiring remains unclaimed. Focused Game Session proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. Game Session now rejects unreadable or wrong-type registry evidence before persisted-context fallback and preserves numeric/opaque account evidence without mutation. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. `PLAYER`/`PLAY`, actor association/namespace roster, and full-stack fresh-smoke proof remain incomplete. #2898 remains unresolved. + +Game Design now exposes an authenticated owner-local canonical tenant UUID/provenance read intended for Game Session; this slice claims no Game Session caller wiring. The producer is independent of Account UUID authentication and does not establish the current Game Session pointer, playable-state namespace/scope, published actor-entry policy, Entity selection, or actor creation. Its contract and focused proof status are recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#runtime-tenant-identity-owner-read) and the [Game authoring, publishing, and activation tracker](./game-authoring-publishing-and-activation.md). `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. diff --git a/protos/account/v1/runtime_account_identity_service.proto b/protos/account/v1/runtime_account_identity_service.proto new file mode 100644 index 0000000000..4441a9e463 --- /dev/null +++ b/protos/account/v1/runtime_account_identity_service.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Authenticated owner-local read of Account's persisted UUID identity provenance. +service RuntimeAccountIdentityService { + rpc ResolveRuntimeAccountIdentity(ResolveRuntimeAccountIdentityRequest) + returns (ResolveRuntimeAccountIdentityResponse); +} + +message ResolveRuntimeAccountIdentityRequest { + string canonical_account_id = 1; + string request_id = 2; +} + +message ResolveRuntimeAccountIdentityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_account_id = 4; + // Private Account provenance evidence; never use this row key as gameplay identity. + int64 source_account_row_id = 5; + string account_uuid_provenance = 6; + int64 source_numeric_row_id = 7; +} diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto new file mode 100644 index 0000000000..9d88ce123e --- /dev/null +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package gamedesign.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Authenticated owner-local read of Game Design's persisted tenant identity. +service TenantIdentityService { + rpc ResolveRuntimeTenantIdentity(ResolveRuntimeTenantIdentityRequest) + returns (ResolveRuntimeTenantIdentityResponse); +} + +message ResolveRuntimeTenantIdentityRequest { + string canonical_tenant_id = 1; + string request_id = 2; +} + +message ResolveRuntimeTenantIdentityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_tenant_id = 4; + int64 source_game_row_id = 5; + string source_game_tenant_key = 6; + string provenance_kind = 7; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index adc504c777..7ac5c0007c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; @@ -45,8 +46,9 @@ public ResponseEntity> createAccount( @GetMapping("/{accountId}/login-auth-modes") public ResponseEntity> getLoginAuthModes( @PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); return ResponseEntity.ok( ApiResponse.success(accountService.getLoginAuthModes(parsedAccountId))); } @@ -56,8 +58,8 @@ public ResponseEntity> getLoginAuthModes( public ResponseEntity> updateLoginAuthModes( @PathVariable String accountId, @Valid @RequestBody UpdateAccountLoginAuthModesRequest request) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); throw new org.springframework.web.server.ResponseStatusException( HttpStatus.NOT_IMPLEMENTED, "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism"); @@ -66,8 +68,9 @@ public ResponseEntity> updateLoginAuthMode @GetMapping("/{accountId}/export") public ResponseEntity> exportAccount( @PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); AccountDataExportDto data = accountService.exportAccountData(parsedAccountId); return ResponseEntity.ok(ApiResponse.success(data)); } @@ -75,26 +78,35 @@ public ResponseEntity> exportAccount( @GetMapping("/{accountId}/tenant-export") public ResponseEntity> exportTenantData( @PathVariable String accountId, @RequestParam String tenantId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); - SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); + if (!isCurrentAccount(parsedAccountUuid) && !SessionContext.hasTenantAccess(parsedTenantId)) { + throw new org.springframework.web.server.ResponseStatusException( + HttpStatus.FORBIDDEN, "Account access required"); + } + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); TenantDataExportDto data = accountService.exportTenantData(parsedTenantId, parsedAccountId); return ResponseEntity.ok(ApiResponse.success(data)); } @DeleteMapping("/{accountId}") public ResponseEntity> deleteAccount(@PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); accountService.deleteAccount(parsedAccountId); return ResponseEntity.ok(ApiResponse.success(null)); } - private void requireCurrentAccountOrGlobalPrivilegedRole(Long accountId) { - if (SessionContext.isCurrentAccount(accountId) || SessionContext.hasGlobalPrivilegedRole()) { + private void requireCurrentAccountOrGlobalPrivilegedRole(UUID accountUuid) { + if (isCurrentAccount(accountUuid) || SessionContext.hasGlobalPrivilegedRole()) { return; } throw new org.springframework.web.server.ResponseStatusException( org.springframework.http.HttpStatus.FORBIDDEN, "Account access required"); } + + private static boolean isCurrentAccount(UUID accountUuid) { + return accountUuid.toString().equals(SessionContext.getAccountId()); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java index b328921644..3608a1a482 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java @@ -1,10 +1,28 @@ package net.firedevops.firemud.accountservice.controller; +import java.util.UUID; import net.firedevops.firemud.common.security.RequestIdValidation; final class AccountRequestReaders { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private AccountRequestReaders() {} + static UUID requireAccountUuid(String accountId) { + if (accountId == null || accountId.isBlank()) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + try { + UUID parsed = UUID.fromString(accountId); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID", exception); + } + } + static long requireAccountId(String accountId) { return RequestIdValidation.requirePositiveLong(accountId, "accountId"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java index b0bc7c1015..eb2626c23a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.ProfileDto; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.service.AccountService; @@ -33,9 +34,10 @@ public ProfileController(AccountService accountService) { @GetMapping("/{accountId}") public ResponseEntity> getProfile( @PathVariable String accountId, @RequestParam String tenantId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); - requireProfileOwner(parsedAccountId); + requireProfileOwner(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); ProfileDto dto = accountService.getProfile(parsedTenantId, parsedAccountId); return ResponseEntity.ok(ApiResponse.success(dto)); } @@ -43,13 +45,14 @@ public ResponseEntity> getProfile( @PutMapping("/{accountId}") public ResponseEntity> updateProfile( @PathVariable String accountId, @Valid @RequestBody UpdateProfileRequest request) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(request.tenantId()); - requireProfileOwner(parsedAccountId); + requireProfileOwner(parsedAccountUuid); if (request.presenceVisibilityPolicy() == null) { throw new IllegalArgumentException("presenceVisibilityPolicy must be provided"); } request.presenceVisibilityPolicy().requireSelectableByAccountHolder(); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); ProfileDto dto = accountService.updateProfile( new UpdateProfileRequest( @@ -61,8 +64,8 @@ public ResponseEntity> updateProfile( return ResponseEntity.ok(ApiResponse.success(dto)); } - private static void requireProfileOwner(long accountId) { - if (!SessionContext.isCurrentAccount(accountId)) { + private static void requireProfileOwner(UUID accountUuid) { + if (!accountUuid.toString().equals(SessionContext.getAccountId())) { throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Profile access required"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java index 978306a52f..de76f21c51 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java @@ -1,4 +1,23 @@ package net.firedevops.firemud.accountservice.dto; +import java.util.UUID; + /** Result of a successful authentication attempt. */ -public record AuthenticationResult(long accountId, String authToken) {} +public record AuthenticationResult(String accountId, String authToken) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AuthenticationResult { + if (accountId == null) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + UUID parsedAccountId; + try { + parsedAccountId = UUID.fromString(accountId); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID", exception); + } + if (NIL_UUID.equals(parsedAccountId) || !parsedAccountId.toString().equals(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java index a029e6da93..d3eb6d032f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java @@ -2,4 +2,4 @@ /** Result of issuing a short-lived first-party bootstrap token. */ public record PlayerBootstrapResult( - long accountId, String bootstrapToken, String issuedAt, String expiresAt) {} + String accountId, String bootstrapToken, String issuedAt, String expiresAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index dcf7def1f0..65099416a4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -53,6 +53,7 @@ import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.common.security.SessionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -208,6 +209,41 @@ private void requireGameSessionPeer() { } } + private void requireSocialGroupsPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/social-groups-service")) { + throw new AdminAuthorizationException("Verified Social Groups workload identity is required"); + } + } + + private void requireCallerAccountSubject(UUID accountUuid) { + if (SessionContext.isInternalService()) { + throw new AdminAuthorizationException("Authenticated account subject is required"); + } + if (!accountUuid.toString().equals(SessionContext.getAccountId())) { + throw new AdminAuthorizationException("Profile access is restricted to the caller account"); + } + } + + private static UUID requireCanonicalAccountUuid(String value) { + if (value == null || value.isBlank()) { + throw new InvalidRequestException("accountId must be a canonical non-nil UUID", null); + } + try { + UUID accountUuid = UUID.fromString(value); + if (accountUuid.equals(new UUID(0L, 0L)) || !accountUuid.toString().equals(value)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return accountUuid; + } catch (IllegalArgumentException exception) { + throw new InvalidRequestException("accountId must be a canonical non-nil UUID", exception); + } + } + private DirectTextCallerContext directTextCaller( net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { return new DirectTextCallerContext( @@ -312,7 +348,7 @@ public void authenticate( AuthenticateResponse response = AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) - .setAccountId(String.valueOf(result.accountId())) + .setAccountId(result.accountId()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -366,7 +402,7 @@ public void verifyEmailLoginOtp( responseObserver.onNext( AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) - .setAccountId(String.valueOf(result.accountId())) + .setAccountId(result.accountId()) .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( @@ -521,16 +557,24 @@ public void getTenantEntitlementsForRuntime( public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getProfile( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + requireCallerAccountSubject(accountUuid); + long accountId = accountService.resolveAccountStorageId(accountUuid); + var dto = accountService.getProfile(tenantId, accountId); GetProfileResponse response = GetProfileResponse.newBuilder() .setProfileJson(JsonMapper.builder().build().writeValueAsString(dto)) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(appError("GetProfile", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetProfileResponse response = GetProfileResponse.newBuilder() @@ -605,14 +649,19 @@ public void listPresenceVisibilityPolicies( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + requireCallerAccountSubject(accountUuid); + long accountId = accountService.resolveAccountStorageId(accountUuid); JsonNode node = JsonMapper.builder().build().readTree(request.getProfileJson()); String displayName = node.path("displayName").asText(null); String bio = node.path("bio").asText(null); String presenceVisibilityPolicy = node.path("presenceVisibilityPolicy").asText(null); accountService.updateProfile( new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), + tenantId, + accountId, displayName, bio, ProfilePresenceVisibilityPolicy.valueOf( @@ -622,6 +671,14 @@ public void updateProfile( UpdateProfileResponse response = UpdateProfileResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + UpdateProfileResponse response = + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError(appError("UpdateProfile", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { UpdateProfileResponse response = UpdateProfileResponse.newBuilder() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index dc74190fed..c5d538919f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -239,16 +239,17 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica String username, String password) { PrimaryAuthentication authentication = authenticateAccountIdentity(username, password, true); Account account = authentication.account(); + UUID accountUuid = requireAuthenticationPersistedIdentity(account); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String token = mintToken( - account.getId().toString(), + accountUuid.toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims("control-ui", account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + accountUuid.toString(), token); } @Override @@ -263,16 +264,17 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica PrimaryAuthentication authentication = authenticateAccountIdentity(gameplayAccount, password, true); Account account = authentication.account(); + UUID accountUuid = requireAuthenticationPersistedIdentity(account); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String token = mintToken( - account.getId().toString(), + accountUuid.toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + accountUuid.toString(), token); } @Override @@ -337,16 +339,17 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmai throw invalidCredentials(); } requireAuthenticationEligible(account); + UUID accountUuid = requireAuthenticationPersistedIdentity(account); accountEmailLoginChallengeRepository.delete(challenge); String token = mintToken( - account.getId().toString(), + accountUuid.toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + accountUuid.toString(), token); } @Override @@ -356,20 +359,21 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri PrimaryAuthentication authentication = authenticateAccountIdentity(accountIdentifier, secret, true); Account account = authentication.account(); + String accountUuid = requireAuthenticationPersistedIdentity(account).toString(); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String jti = UUID.randomUUID().toString(); long issuedAt = System.currentTimeMillis(); long expiresAt = issuedAt + tokenProperties.getPlayerBootstrapExpirationMs(); String bootstrapToken = mintToken( - String.valueOf(account.getId()), + accountUuid, tokenProperties.getPlayerBootstrapExpirationMs(), - Map.of("aud", "player-bootstrap", "accountId", account.getId(), "jti", jti)); + Map.of("aud", "player-bootstrap", "accountId", accountUuid, "jti", jti)); sessionService.storeAccountSession( account.getId(), bootstrapToken, tokenProperties.getPlayerBootstrapExpirationMs()); logger.info("Issued player bootstrap token for account {}", account.getId()); return new PlayerBootstrapResult( - account.getId(), + accountUuid, bootstrapToken, Instant.ofEpochMilli(issuedAt).toString(), Instant.ofEpochMilli(expiresAt).toString()); @@ -1011,6 +1015,7 @@ private JoinEvaluation evaluateJoin(VerifiedJoinScope scope, boolean lockEntitle return evaluateJoin( new ConnectScopeContext( scope.accountId(), + requireAuthenticationPersistedIdentity(requireAccount(scope.accountId())).toString(), scope.tenantId(), scope.realmId(), scope.worldSlug(), @@ -1216,13 +1221,13 @@ && isPublicProductionRealm(realm)) { long expiresAt = issuedAt + tokenProperties.getConnectTokenExpirationMs(); String connectToken = mintToken( - String.valueOf(bootstrapContext.accountId()), + scopeContext.accountUuid(), tokenProperties.getConnectTokenExpirationMs(), Map.of( "aud", "gameplay-connect", "accountId", - bootstrapContext.accountId(), + scopeContext.accountUuid(), "tenantId", scopeContext.tenantId(), "gameInstanceId", @@ -1404,7 +1409,15 @@ private BootstrapContext requireBootstrapContext(String bootstrapToken) { "Missing bootstrap token", "Invalid bootstrap token"); try { - long accountId = requireSignedActorAccountId(claims); + String accountUuid = + JwtClaims.requireSignedGameplayAccountUuid( + claims, "signed token account subject mismatch"); + long accountId; + try { + accountId = resolveAccountStorageId(UUID.fromString(accountUuid)); + } catch (IllegalArgumentException | IllegalStateException ex) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token", ex); + } if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); } @@ -1663,13 +1676,16 @@ private String mintConnectScopeId( RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { + String accountUuid = + requireAuthenticationPersistedIdentity(requireAccount(bootstrapContext.accountId())) + .toString(); long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); return mintToken( - String.valueOf(bootstrapContext.accountId()), + accountUuid, expirationMs, Map.ofEntries( Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", bootstrapContext.accountId()), + Map.entry("accountId", accountUuid), Map.entry("tenantId", realm.tenantId()), Map.entry("realmId", realm.realmId().toString()), Map.entry("worldSlug", realm.worldSlug()), @@ -1745,6 +1761,8 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { JwtClaims.SignedGameplayRoutingClaims routingClaims = JwtClaims.requireSignedGameplayRoutingClaims( claims, "signed token account subject mismatch"); + String accountUuid = routingClaims.accountId(); + long accountId = resolveAccountStorageId(UUID.fromString(accountUuid)); Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); if (connectScopeExpiresAt == null) { @@ -1754,7 +1772,8 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } return new ConnectScopeContext( - routingClaims.accountId(), + accountId, + accountUuid, routingClaims.tenantId(), requireCanonicalRealmId(claims.get("realmId")), routingClaims.worldSlug(), @@ -1766,15 +1785,11 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { routingClaims.pointerVersion(), evaluatedAt, connectScopeExpiresAt); - } catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException | IllegalStateException ex) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); } } - private static long requireSignedActorAccountId(Claims claims) { - return JwtClaims.requireSignedActorAccountId(claims, "signed token account subject mismatch"); - } - private Claims requireSignedTokenClaims( String token, String expectedAudience, @@ -1987,6 +2002,25 @@ private Account requireAccount(Long accountId) { .orElseThrow(() -> new IllegalArgumentException("Account not found")); } + private UUID requireAuthenticationPersistedIdentity(Account account) { + if (account == null) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + UUID accountUuid = account.getAccountUuid(); + try { + Long resolvedStorageId = resolveAccountStorageId(accountUuid); + if (account.getId() == null || !account.getId().equals(resolvedStorageId)) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + } catch (IllegalArgumentException | IllegalStateException ex) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row", ex); + } + return account.getAccountUuid(); + } + /** Resolves a canonical public identity at the Account persistence boundary only. */ @Override @Transactional(readOnly = true) @@ -2034,7 +2068,7 @@ private Map authenticationTokenClaims(String audience, Account a "aud", audience, "accountId", - account.getId(), + account.getAccountUuid().toString(), "globalRoles", globalRoles, "jti", @@ -2628,6 +2662,7 @@ private String requireCanonicalPlayableStateNamespaceId(String value) { private record ConnectScopeContext( long accountId, + String accountUuid, long tenantId, UUID realmId, String worldSlug, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java new file mode 100644 index 0000000000..a109fe7288 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.account.v1.RuntimeAccountIdentityServiceGrpc; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.DataAccessException; +import org.jooq.exception.TooManyRowsException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; + +/** Authenticated read of Account's exact retained UUID-to-row provenance. */ +@GrpcService +public class RuntimeAccountIdentityGrpcService + extends RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceImplBase { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountRepository accountRepository; + private final String workloadNamespace; + + public RuntimeAccountIdentityGrpcService( + AccountRepository accountRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.accountRepository = accountRepository; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveRuntimeAccountIdentity( + ResolveRuntimeAccountIdentityRequest request, + StreamObserver responseObserver) { + if (!isAllowedRuntimePeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified Game Session or Entity Management workload identity is required") + .asRuntimeException()); + return; + } + + UUID canonicalAccountId = parseCanonicalNonNilUuid(request.getCanonicalAccountId()); + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + if (canonicalAccountId == null + || requestId == null + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription( + "Canonical nonnil IDs and the exact metadata request schema are required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = accountRepository.findByAccountUuid(canonicalAccountId); + } catch (IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Account UUID provenance is ambiguous or invalid") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account identity is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Account identity is temporarily unavailable" + : "Account identity could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Account identity could not be read") + .asRuntimeException()); + return; + } + + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No Account identity for exact canonical account ID") + .asRuntimeException()); + return; + } + + Account account = resolved.orElseThrow(); + if (!hasExactPersistedIdentity(account, canonicalAccountId)) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Account UUID provenance does not match its exact persisted source row") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveRuntimeAccountIdentityResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(workloadNamespace) + .setRequestId(requestId.toString()) + .setCanonicalAccountId(canonicalAccountId.toString()) + .setSourceAccountRowId(account.getId()) + .setAccountUuidProvenance(account.getAccountUuidProvenance().name()) + .setSourceNumericRowId(account.getAccountUuidSourceNumericId()) + .build()); + responseObserver.onCompleted(); + } + + private boolean isAllowedRuntimePeer() { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return false; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !peer.namespace().equals(workloadNamespace)) { + return false; + } + return peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + || peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service"); + } + + private static boolean hasExactPersistedIdentity(Account account, UUID canonicalAccountId) { + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || NIL_UUID.equals(account.getAccountUuid()) + || !canonicalAccountId.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + return false; + } + for (AccountIdentityProvenance provenance : AccountIdentityProvenance.values()) { + if (provenance == account.getAccountUuidProvenance()) { + return true; + } + } + return false; + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException ex) { + return null; + } + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index a0058cdd88..130c82c21d 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -76,6 +76,7 @@ firemud: - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership + - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 526520c5d0..027fc23c34 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -40,6 +40,7 @@ firemud: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} account: credentials: cleanup: @@ -102,6 +103,7 @@ firemud: - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership + - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity management: endpoints: diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 620742cab5..281e85ba42 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -114,14 +114,19 @@ components: type: object properties: accountId: - type: integer + type: string + format: uuid + description: Canonical non-nil Account UUID read back from the authenticated source row; never the numeric database primary key. authToken: type: string + required: [accountId, authToken] PlayerBootstrapResult: type: object properties: accountId: - type: integer + type: string + format: uuid + description: Canonical non-nil Account UUID; never the private numeric database primary key. bootstrapToken: type: string issuedAt: @@ -630,7 +635,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid responses: '200': description: Exported data @@ -646,6 +652,7 @@ paths: required: true schema: type: string + format: uuid responses: '200': description: Allowed login mechanisms @@ -666,6 +673,7 @@ paths: required: true schema: type: string + format: uuid requestBody: required: true content: @@ -688,7 +696,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid - name: tenantId in: query required: true @@ -708,7 +717,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid responses: '200': description: Deletion success @@ -723,7 +733,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid - name: tenantId in: query required: true @@ -746,7 +757,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid requestBody: required: true content: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 616ff0fbc1..9c5f967f1e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -52,6 +52,7 @@ "firemud.auth.http.public-routes[1].path-pattern=/accounts/" }) class AccountControllerTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -117,9 +118,13 @@ void createAccountRetainsMinimumPasswordLength() throws Exception { @Test void deleteAccountAllowsScopedTenantAdmin() throws Exception { String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); mockMvc - .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + delete("/accounts/" + ACCOUNT_UUID) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); } @@ -130,7 +135,9 @@ void deleteAccountRejectsScopedTenantAdminBecauseFullDeletionIsAccountScoped() t jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("tenantAdmin")))); mockMvc - .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + delete("/accounts/" + ACCOUNT_UUID) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.error.code").value("PERMISSION_DENIED")) .andExpect(jsonPath("$.error.message").value("Account access required")); @@ -143,10 +150,14 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.exportAccountData(42L)) .thenReturn(new AccountDataExportDto(account, List.of())); - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc - .perform(get("/accounts/42/export").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + get("/accounts/" + ACCOUNT_UUID + "/export") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); } @@ -158,12 +169,14 @@ void exportTenantDataAllowsScopedTenantRole() throws Exception { "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.exportTenantData(7L, 42L)) .thenReturn(new TenantDataExportDto(7L, account, null)); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); String token = jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("moderator")))); mockMvc .perform( - get("/accounts/42/tenant-export") + get("/accounts/" + ACCOUNT_UUID + "/tenant-export") .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -176,11 +189,10 @@ void exportAccountRejectsMalformedAccountIdBeforeDispatch() throws Exception { mockMvc .perform( - get("/accounts/not-a-number/export") - .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + get("/accounts/not-a-uuid/export").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @@ -191,7 +203,7 @@ void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { mockMvc .perform( - get("/accounts/42/tenant-export") + get("/accounts/" + ACCOUNT_UUID + "/tenant-export") .param("tenantId", "0") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) @@ -203,11 +215,13 @@ void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Exception { - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - delete("/accounts/42") + delete("/accounts/" + ACCOUNT_UUID) .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -215,14 +229,14 @@ void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep } @Test - void deleteAccountRejectsZeroAccountIdBeforeDispatch() throws Exception { + void deleteAccountRejectsNumericAccountIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken("1", Map.of("accountId", "1")); mockMvc .perform(delete("/accounts/0").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @@ -248,18 +262,20 @@ void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { AccountLoginAuthModesDto modes = new AccountLoginAuthModesDto(java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP)); when(accountService.getLoginAuthModes(42L)).thenReturn(modes); - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - get("/accounts/42/login-auth-modes") + get("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.loginAuthModes[0]").value("EMAIL_OTP")); mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[\"EMAIL_OTP\"]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -281,7 +297,7 @@ void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[\"PASSWORD\"]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -293,11 +309,11 @@ void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { @Test void updateLoginAuthModesRejectsEmptySetBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 316a813e0e..ffb292d41e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -60,10 +60,18 @@ void publicOpenApiOmitsUnavailableBootstrapJoin() throws Exception { Map paths = (Map) document.get("paths"); Map components = (Map) document.get("components"); Map schemas = (Map) components.get("schemas"); + Map playerBootstrapResult = + (Map) schemas.get("PlayerBootstrapResult"); + Map playerBootstrapProperties = + (Map) playerBootstrapResult.get("properties"); + Map playerBootstrapAccountId = + (Map) playerBootstrapProperties.get("accountId"); assertFalse(paths.containsKey("/auth/bootstrap/join")); assertTrue(((Map) paths.get("/auth/player-bootstrap")).containsKey("post")); assertTrue(((Map) paths.get("/auth/connect-token")).containsKey("post")); + assertEquals("string", playerBootstrapAccountId.get("type")); + assertEquals("uuid", playerBootstrapAccountId.get("format")); assertFalse(schemas.containsKey("JoinPublicProductionRequest")); assertFalse(schemas.containsKey("JoinPublicProductionResult")); } @@ -89,7 +97,7 @@ void publicOpenApiDocumentsRetryableCharacterDiscoveryOutage() throws Exception void loginReturnsTokenAndAccountId() throws Exception { LoginRequest request = new LoginRequest("demo", "password"); when(accountService.authenticate("demo", "password")) - .thenReturn(new AuthenticationResult(1L, "tok123")); + .thenReturn(new AuthenticationResult("4cae05e8-7a6b-4b14-9d44-665e3eec450b", "tok123")); mockMvc .perform( @@ -98,7 +106,7 @@ void loginReturnsTokenAndAccountId() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.authToken").value("tok123")); } @@ -106,7 +114,7 @@ void loginReturnsTokenAndAccountId() throws Exception { void loginAcceptsExistingOneCharacterPassword() throws Exception { LoginRequest request = new LoginRequest("demo", "x"); when(accountService.authenticate("demo", "x")) - .thenReturn(new AuthenticationResult(1L, "tok123")); + .thenReturn(new AuthenticationResult("4cae05e8-7a6b-4b14-9d44-665e3eec450b", "tok123")); mockMvc .perform( @@ -124,7 +132,10 @@ void playerBootstrapReturnsShortLivedToken() throws Exception { when(accountService.issuePlayerBootstrap("demo", "password")) .thenReturn( new PlayerBootstrapResult( - 1L, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "boot123", + "2026-03-30T00:00:00Z", + "2026-03-30T00:05:00Z")); mockMvc .perform( @@ -133,7 +144,7 @@ void playerBootstrapReturnsShortLivedToken() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.bootstrapToken").value("boot123")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java index 14b86c1fff..043c8d970f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java @@ -33,6 +33,8 @@ @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) @WithFiremudHttpAuthTestProperties class ProfileControllerTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "a2e1342e-a139-49c6-a460-c8e25f6697ae"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -50,11 +52,13 @@ void getProfileReturnsDto() throws Exception { ProfileDto dto = new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); when(accountService.getProfile(1L, 2L)).thenReturn(dto); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -69,11 +73,13 @@ void updateProfileReturnsDto() throws Exception { ProfileDto dto = new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.updateProfile(req)).thenReturn(dto); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -89,7 +95,7 @@ void getProfileRejectsCrossTenantScopedAdmin() throws Exception { jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -98,11 +104,12 @@ void getProfileRejectsCrossTenantScopedAdmin() throws Exception { @Test void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { String token = - jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -112,11 +119,12 @@ void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { @Test void getProfileRejectsGlobalAdminForAnotherAccount() throws Exception { - String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -130,12 +138,12 @@ void getProfileRejectsMalformedAccountIdBeforeDispatch() throws Exception { mockMvc .perform( - get("/profiles/not-a-number") + get("/profiles/not-a-uuid") .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @@ -146,7 +154,7 @@ void getProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "0") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) @@ -163,11 +171,13 @@ void updateProfileAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep ProfileDto dto = new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.updateProfile(req)).thenReturn(dto); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -180,11 +190,11 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforeDispatch() throws Except UpdateProfileRequest request = new UpdateProfileRequest( 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -202,11 +212,12 @@ void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() thro UpdateProfileRequest request = new UpdateProfileRequest( 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); - String token = jwtUtil.generateToken("3", Map.of("accountId", "3")); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -220,11 +231,12 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = - jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -237,11 +249,12 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -264,7 +277,7 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @@ -273,11 +286,11 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { void updateProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { UpdateProfileRequest req = new UpdateProfileRequest(0L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index f6dfd7e760..456a5c2141 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java @@ -40,7 +40,10 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { when(accountService.issuePlayerBootstrap("demo@example.com", "swordfish")) .thenReturn( new PlayerBootstrapResult( - 1L, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "boot123", + "2026-03-30T00:00:00Z", + "2026-03-30T00:05:00Z")); mockMvc .perform( @@ -49,7 +52,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.bootstrapToken").value("boot123")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java new file mode 100644 index 0000000000..aa3f5a8179 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class AuthenticationResultTest { + @Test + void acceptsCanonicalNonNilAccountUuid() { + AuthenticationResult result = + new AuthenticationResult("4cae05e8-7a6b-4b14-9d44-665e3eec450b", "token"); + + assertEquals("4cae05e8-7a6b-4b14-9d44-665e3eec450b", result.accountId()); + } + + @Test + void rejectsNonCanonicalOrNilAccountUuid() { + assertThrows(IllegalArgumentException.class, () -> new AuthenticationResult(null, "token")); + assertThrows(IllegalArgumentException.class, () -> new AuthenticationResult("12", "token")); + assertThrows( + IllegalArgumentException.class, + () -> new AuthenticationResult("00000000-0000-0000-0000-000000000000", "token")); + assertThrows( + IllegalArgumentException.class, + () -> new AuthenticationResult("4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", "token")); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java new file mode 100644 index 0000000000..d6293c0d54 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -0,0 +1,327 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import 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 java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.RuntimeAccountIdentityGrpcService; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionClaims; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class RuntimeAccountIdentityGrpcAuthWiringTest { + private static final String IDENTITY_METHOD = + "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; + private static final String NONPUBLIC_METHOD = + "account.v1.AccountService/GetRealmAccessGrantForRuntime"; + private static final String ACCOUNT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; + private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final MethodDescriptor< + ResolveRuntimeAccountIdentityRequest, ResolveRuntimeAccountIdentityResponse> + IDENTITY_METHOD_DESCRIPTOR = + unaryMethod( + IDENTITY_METHOD, + ResolveRuntimeAccountIdentityRequest.getDefaultInstance(), + ResolveRuntimeAccountIdentityResponse.getDefaultInstance()); + private static final MethodDescriptor< + GetRealmAccessGrantForRuntimeRequest, GetRealmAccessGrantForRuntimeResponse> + NONPUBLIC_METHOD_DESCRIPTOR = + unaryMethod( + NONPUBLIC_METHOD, + GetRealmAccessGrantForRuntimeRequest.getDefaultInstance(), + GetRealmAccessGrantForRuntimeResponse.getDefaultInstance()); + + @Test + void exactSameNamespaceRuntimePeersReachReadOnlyHandlerUnderBaseAndProdYaml() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + for (String peerUri : List.of(GAME_SESSION_URI, ENTITY_MANAGEMENT_URI)) { + AccountRepository repository = mock(AccountRepository.class); + Account account = persistedAccount(); + when(repository.findByAccountUuid(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(Optional.of(account)); + RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, "test"); + + DispatchResult result = dispatchIdentityMethod(interceptor, service, peerUri, null); + + assertThat(result.observer().failure).isFalse(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getCanonicalAccountId()) + .isEqualTo(ACCOUNT_UUID); + assertThat(result.observer().response.getSourceAccountRowId()).isEqualTo(42L); + assertThat(result.handlerDispatched()).isTrue(); + verify(repository).findByAccountUuid(UUID.fromString(ACCOUNT_UUID)); + } + }); + } + } + + @Test + void absentWrongAndWrongNamespacePeersAreDeniedBeforeRepositoryReadUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, jwtUtil) -> { + AccountRepository repository = mock(AccountRepository.class); + RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, "test"); + String privilegedBearer = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of( + "accountId", + ACCOUNT_UUID, + "globalRoles", + List.of("platformAdmin"), + "scopedRoles", + Map.of())); + var validatedBearer = jwtUtil.parseToken(privilegedBearer); + assertThat( + JwtClaims.requireSignedGameplayAccountUuid( + validatedBearer.getPayload(), "Bearer subject/account UUID mismatch")) + .isEqualTo(ACCOUNT_UUID); + assertThat(SessionClaims.fromJwt(validatedBearer).hasPrivilegedRole()).isTrue(); + + DispatchResult absent = dispatchIdentityMethod(interceptor, service, null, null); + DispatchResult wrongService = + dispatchIdentityMethod( + interceptor, service, "spiffe://firemud/ns/test/sa/account-service", null); + DispatchResult wrongNamespace = + dispatchIdentityMethod( + interceptor, + service, + "spiffe://firemud/ns/other/sa/game-session-service", + null); + DispatchResult bearerWithoutPeer = + dispatchIdentityMethod(interceptor, service, null, privilegedBearer); + + for (DispatchResult denied : + List.of(absent, wrongService, wrongNamespace, bearerWithoutPeer)) { + assertThat(denied.observer().failure).isTrue(); + assertThat(denied.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.handlerDispatched()).isTrue(); + } + verifyNoInteractions(repository); + }); + } + } + + @Test + void unrelatedAccountMethodRemainsBearerProtectedUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall + call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(NONPUBLIC_METHOD_DESCRIPTOR); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler< + GetRealmAccessGrantForRuntimeRequest, GetRealmAccessGrantForRuntimeResponse> + next = mock(ServerCallHandler.class); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(next, never()) + .startCall( + org.mockito.ArgumentMatchers.eq(call), + org.mockito.ArgumentMatchers.any(Metadata.class)); + }); + } + } + + private static Account persistedAccount() { + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(UUID.fromString(ACCOUNT_UUID)); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); + account.setAccountUuidSourceNumericId(42L); + return account; + } + + private static DispatchResult dispatchIdentityMethod( + AuthTokenInterceptor interceptor, + RuntimeAccountIdentityGrpcService service, + String peerUri, + String bearerToken) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(IDENTITY_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + TestObserver observer = new TestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ResolveRuntimeAccountIdentityRequest, + ResolveRuntimeAccountIdentityResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ResolveRuntimeAccountIdentityRequest request) { + service.resolveRuntimeAccountIdentity(request, observer); + } + }; + } + }; + ResolveRuntimeAccountIdentityRequest request = + ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(ACCOUNT_UUID) + .setRequestId(REQUEST_UUID) + .build(); + Metadata headers = new Metadata(); + if (bearerToken != null) { + headers.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + bearerToken); + } + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new DispatchResult(observer, handlerDispatched.get()); + } + + private static void withConfiguredInterceptor( + boolean productionLayer, + java.util.function.BiConsumer action) { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withInitializer( + context -> { + try { + YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); + PropertySource accountBase = + yamlLoader + .load( + "account-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(accountBase); + if (productionLayer) { + PropertySource accountProduction = + yamlLoader + .load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addFirst(accountProduction); + } + } catch (IOException exception) { + throw new IllegalStateException( + "Could not load Account application config", exception); + } + }) + .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(IDENTITY_METHOD) + .doesNotContain(NONPUBLIC_METHOD); + action.accept( + context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); + }); + } + + private static < + ReqT extends com.google.protobuf.Message, RespT extends com.google.protobuf.Message> + MethodDescriptor unaryMethod( + String fullMethodName, ReqT requestDefault, RespT responseDefault) { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(requestDefault)) + .setResponseMarshaller(ProtoUtils.marshaller(responseDefault)) + .build(); + } + + private record DispatchResult(TestObserver observer, boolean handlerDispatched) {} + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeAccountIdentityResponse response; + private Status.Code statusCode; + private boolean failure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeAccountIdentityResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = true; + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 1625c033d1..383d9bcf9f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -65,6 +65,8 @@ class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "a2e1342e-a139-49c6-a460-c8e25f6697ae"; private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; @@ -73,6 +75,11 @@ class AccountGrpcServiceTest { "spiffe://firemud/ns/test/sa/game-session-service", WORKLOAD_NAMESPACE, "game-session-service"); + private static final GrpcPeerIdentity SOCIAL_GROUPS_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/social-groups-service", + WORKLOAD_NAMESPACE, + "social-groups-service"); private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() @@ -557,7 +564,9 @@ void verifyEmailLoginOtpReturnsAuthenticatedSession() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) - .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -580,10 +589,33 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("9", ref.get().getAccountId()); + assertEquals(ACCOUNT_UUID, ref.get().getAccountId()); assertEquals("jwt", ref.get().getAuthToken()); } + @Test + void authenticateReturnsCanonicalUuid() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer); + + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("jwt", observer.response().getAuthToken()); + assertTrue(observer.completed()); + } + @Test void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { PingService pingService = Mockito.mock(PingService.class); @@ -710,27 +742,34 @@ public void onCompleted() {} void getProfileReturnsProfile() throws Exception { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.getProfile(1L, 2L)) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( 1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertEquals( "demo", @@ -746,36 +785,64 @@ public void onCompleted() {} .readTree(ref.get().getProfileJson()) .path("presenceVisibilityPolicy") .asText()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); } @Test void getProfileRejectsZeroAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountService); } + @Test + void getProfileRejectsMismatchedCallerSubjectBeforeStorageResolution() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("player"), Map.of()); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verify(accountService, Mockito.never()) + .resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); + } + @Test void listPresenceVisibilityPoliciesMapsPersistedPolicies() { PingService pingService = Mockito.mock(PingService.class); @@ -1110,28 +1177,35 @@ void updateProfileErrorReturnsDetail() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.updateProfile(Mockito.any())) .thenThrow(new IllegalArgumentException("bad")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + new StreamObserver() { + @Override + public void onNext(UpdateProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1141,28 +1215,32 @@ public void onCompleted() {} void updateProfileRejectsZeroTenantIdBeforeUpdate() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("0") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + new StreamObserver() { + @Override + public void onNext(UpdateProfileResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 7f579f6040..e0074444de 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -435,6 +435,7 @@ void createAccountMapsSpringDataIntegrityConflict() { void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -610,6 +611,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -642,6 +644,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -697,6 +700,7 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -784,6 +788,7 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -866,6 +871,7 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -932,6 +938,7 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -998,6 +1005,7 @@ void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1120,6 +1128,7 @@ void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1165,6 +1174,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1276,6 +1286,7 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1387,6 +1398,7 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1485,6 +1497,7 @@ void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String orig void reclaimedScopeRaceReturnsConnectScopeInvalid() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1531,6 +1544,7 @@ void reclaimedScopeRaceReturnsConnectScopeInvalid() { void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1799,6 +1813,7 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setEmailVerified(true); account.setRole("player"); @@ -1831,7 +1846,7 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.authToken()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) .delete(challengeCaptor.getValue()); @@ -1847,6 +1862,7 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1861,7 +1877,7 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); org.mockito.Mockito.verify(sessionService) .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -1872,6 +1888,7 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1886,7 +1903,7 @@ void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) .delete(challenge); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) @@ -1936,6 +1953,57 @@ void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); } + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( + AccountIdentityProvenance provenance) { + Account account = new Account(); + account.setId(31L); + account.setEmail("retained@example.com"); + account.setPasswordHash(hash("password")); + setPersistedAuthenticationIdentity(account, provenance); + when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); + + AuthenticationResult result = + service.authenticateForGameplay("retained@example.com", "password"); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + } + + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(32L); + account.setEmail("unproved@example.com"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(8L); + challenge.setAccountId(32L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(32L)) + .thenReturn(Optional.of(challenge)); + + assertThrows( + IllegalStateException.class, + () -> service.authenticateForGameplay("unproved@example.com", "123456")); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + @Test void emailLoginOtpVerificationFailsClosedForUnknownEmail() { when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); @@ -1953,6 +2021,7 @@ void emailLoginOtpVerificationFailsClosedForUnknownEmail() { void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setRole("player"); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1968,10 +2037,11 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(9L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); @@ -1982,6 +2052,7 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1989,10 +2060,11 @@ void authenticateReturnsControlUiTokenWithoutGameplayMembership() { AuthenticationResult result = service.authenticate("demo", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("control-ui", claims.getAudience().iterator().next()); - assertEquals(1L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); assertFalse(claims.containsKey("tenantId")); @@ -2027,6 +2099,7 @@ void authenticateRejectsIneligibleLifecycleState( void authenticateForGameplayReturnsTokenWhenPasswordMatches() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); @@ -2035,10 +2108,11 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(1L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); org.mockito.Mockito.verify(sessionService) @@ -2050,6 +2124,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { void issuePlayerBootstrapReturnsShortLivedToken() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); account.setLoginAuthModes("PASSWORD"); @@ -2058,7 +2133,7 @@ void issuePlayerBootstrapReturnsShortLivedToken() { PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.bootstrapToken()); assertNotNull(result.issuedAt()); assertNotNull(result.expiresAt()); @@ -2069,15 +2144,51 @@ void issuePlayerBootstrapReturnsShortLivedToken() { org.mockito.ArgumentMatchers.eq(300000L)); var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); assertEquals("player-bootstrap", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertFalse(claims.containsKey("tenantId")); assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); + when(sessionService.isAccountSessionActive(7L, result.bootstrapToken())).thenReturn(true); + var worlds = service.listBootstrapWorlds(result.bootstrapToken()); + assertEquals("demo", worlds.getFirst().worldSlug()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(2)) + .findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(sessionService).isAccountSessionActive(7L, result.bootstrapToken()); verifyNoInteractions(accountEmailLoginChallengeRepository); } + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(50L); + account.setUsername("demo"); + account.setLoginAuthModes("EMAIL_OTP"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(50L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(50L)) + .thenReturn(Optional.of(challenge)); + + assertThrows(IllegalStateException.class, () -> service.issuePlayerBootstrap("demo", "123456")); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + @Test void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { Account emailAccount = new Account(); emailAccount.setId(7L); + setPersistedAuthenticationIdentity(emailAccount); emailAccount.setUsername("email-owner"); emailAccount.setEmail("player@example.com"); emailAccount.setPasswordHash(hash("password")); @@ -2087,7 +2198,7 @@ void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { PlayerBootstrapResult result = service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); - assertEquals(7L, result.accountId()); + assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @@ -2096,6 +2207,7 @@ void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setLoginAuthModes("EMAIL_OTP"); @@ -2110,7 +2222,7 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); @@ -2121,9 +2233,14 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { @Test void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + String accountUuid = account.getAccountUuid().toString(); String bootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2134,11 +2251,20 @@ void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); } - @Test - void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { + @ParameterizedTest + @ValueSource( + strings = { + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901", + " 4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901 " + }) + void listBootstrapWorldsRejectsMalformedOrNoncanonicalBootstrapAccountUuid(String accountUuid) { String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "abc")); + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2146,13 +2272,16 @@ void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { () -> service.listBootstrapWorlds(malformedBootstrapToken)); assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("12", Map.of("aud", "player-bootstrap", "accountId", "11")); + .generateToken( + REALM_ID, + Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); AuthenticationException ex = assertThrows( @@ -2160,13 +2289,14 @@ void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { () -> service.listBootstrapWorlds(malformedBootstrapToken)); assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test - void listBootstrapWorldsRejectsNonPositiveBootstrapTokenClaims() { + void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "0")); + .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); AuthenticationException ex = assertThrows( @@ -2174,6 +2304,7 @@ void listBootstrapWorldsRejectsNonPositiveBootstrapTokenClaims() { () -> service.listBootstrapWorlds(malformedBootstrapToken)); assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test @@ -2231,6 +2362,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2270,6 +2402,7 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2293,6 +2426,7 @@ void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2331,6 +2465,7 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2359,6 +2494,7 @@ void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2397,6 +2533,7 @@ void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransaction void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2432,6 +2569,7 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFi void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2467,6 +2605,7 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2506,6 +2645,7 @@ void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { void issueConnectTokenRejectsMalformedConnectScopeId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2531,10 +2671,69 @@ void issueConnectTokenRejectsMalformedConnectScopeId() { assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); } + @Test + void issueConnectTokenRejectsNumericSignedConnectCarrierWithoutReplayMutation() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String numericConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", "11"), + Map.entry("tenantId", "7"), + Map.entry("realmId", REALM_ID), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", java.time.Instant.now().toString()), + Map.entry( + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(60).toString()), + Map.entry("jti", "numeric-account-id"))); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(numericConnectScopeId, "req-numeric-account-id"))); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong()); + } + @Test void issueConnectTokenRejectsBlankConnectScopeId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2564,6 +2763,7 @@ void issueConnectTokenRejectsBlankConnectScopeId() { void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2617,6 +2817,7 @@ void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { void issueConnectTokenRejectsMalformedConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2671,6 +2872,7 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2723,6 +2925,7 @@ void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2740,12 +2943,12 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "12", + "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3", Map.of( "aud", "bootstrap-connect-scope", "accountId", - "11", + account.getAccountUuid().toString(), "tenantId", "7", "worldSlug", @@ -2776,6 +2979,7 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2829,6 +3033,7 @@ void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2882,6 +3087,7 @@ void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { void authenticateForGameplayUsesNormalizedEmailLookup() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -2891,7 +3097,7 @@ void authenticateForGameplayUsesNormalizedEmailLookup() { service.authenticateForGameplay(" DEMO@example.com ", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(sessionService) .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); verifyNoInteractions(accountTenantMembershipRepository); @@ -2926,12 +3132,13 @@ void authenticateDoesNotUseGlobalAccountFallback() { void authenticateAllowsGlobalIdentityWithoutTenantMembership() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.authToken()); org.mockito.Mockito.verify(sessionService) .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -2942,6 +3149,7 @@ void authenticateAllowsGlobalIdentityWithoutTenantMembership() { void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -2974,6 +3182,7 @@ void getTenantMembershipForRuntimeRejectsMissingAccount() { void getTenantMembershipForRuntimeRejectsCrossTenantAccount() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -3131,6 +3340,7 @@ void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { void issueConnectTokenReturnsShortLivedConnectToken() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3167,6 +3377,9 @@ void issueConnectTokenReturnsShortLivedConnectToken() { .parseToken(result.connectToken()) .getPayload(); assertEquals("gameplay-connect", connectTokenClaims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), connectTokenClaims.getSubject()); + assertEquals( + account.getAccountUuid().toString(), connectTokenClaims.get("accountId", String.class)); assertEquals(17L, ((Number) connectTokenClaims.get("pointerVersion")).longValue()); org.mockito.Mockito.verify(sessionService) .storeSession( @@ -3180,6 +3393,7 @@ void issueConnectTokenReturnsShortLivedConnectToken() { void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFailure() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3234,6 +3448,7 @@ void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFail void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3288,6 +3503,7 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3339,6 +3555,7 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3401,6 +3618,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3459,6 +3677,7 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() void issueConnectTokenRequiresExplicitPublicProductionMembership() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3512,6 +3731,7 @@ void issueConnectTokenRequiresExplicitPublicProductionMembership() { void issueConnectTokenRejectsMissingMembershipWhenPublicJoiningIsDisabled() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3546,6 +3766,7 @@ void issueConnectTokenClassifiesInactivePublicMembershipByJoinPolicy( String subscriptionStatus, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3587,6 +3808,7 @@ void issueConnectTokenClassifiesInactivePublicMembershipByJoinPolicy( void issueConnectTokenClassifiesKnownBillingDenialAndReplaysItDeterministically() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3654,6 +3876,7 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( boolean publicProductionRealm, String realmSlug) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3738,6 +3961,7 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( void issueConnectTokenReplaysSameFailureForSameRequestId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3828,6 +4052,7 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3871,6 +4096,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( boolean membershipExists) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3918,6 +4144,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3954,6 +4181,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( String subscriptionStatus, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3994,6 +4222,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4027,6 +4256,7 @@ void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnav void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4096,6 +4326,7 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4149,6 +4380,7 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4198,6 +4430,7 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { void listBootstrapRealmsIncludesRealmStatePolicy() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4212,6 +4445,12 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { assertEquals(1, realms.size()); assertEquals(REALM_ID, realms.getFirst().realmId()); + var scopeClaims = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(realms.getFirst().connectScopeId()) + .getPayload(); + assertEquals(account.getAccountUuid().toString(), scopeClaims.getSubject()); + assertEquals(account.getAccountUuid().toString(), scopeClaims.get("accountId", String.class)); assertEquals( REALM_ID, new JwtUtil(JWT_SECRET, 300000L) @@ -4236,6 +4475,7 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable String namespaceId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4277,6 +4517,7 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4356,6 +4597,7 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4405,6 +4647,7 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4488,6 +4731,7 @@ void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable( void listBootstrapRealmsPropagatesUnavailableEntitlements() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4508,6 +4752,7 @@ void listBootstrapRealmsPropagatesUnavailableEntitlements() { void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4561,6 +4806,7 @@ void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4602,6 +4848,7 @@ void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4659,6 +4906,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4700,6 +4948,7 @@ void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { void listBootstrapCharactersUsesIsolatedRealmRoster() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4775,6 +5024,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4823,6 +5073,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4871,6 +5122,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4969,6 +5221,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5044,6 +5297,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5071,6 +5325,7 @@ void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { void listBootstrapCharactersRejectsChangedCanonicalRealmId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5109,6 +5364,7 @@ void listBootstrapCharactersRejectsChangedCanonicalRealmId() { void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5157,6 +5413,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5221,6 +5478,7 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5282,6 +5540,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5377,6 +5636,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( void grantRealmAccessUpsertsRuntimeGrant() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountRealmAccessGrantRepository.findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( @@ -5401,6 +5661,7 @@ void grantRealmAccessUpsertsRuntimeGrant() { void getRealmAccessGrantForRuntimeReturnsGrantState() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); AccountRealmAccessGrant grant = new AccountRealmAccessGrant(); grant.setGrantVersion(4L); @@ -5864,13 +6125,49 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } - private static Account directTextAccount() { + private Account directTextAccount() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); return account; } + private void setPersistedAuthenticationIdentity(Account account) { + setPersistedAuthenticationIdentity( + account, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + } + + private void setPersistedAuthenticationIdentity( + Account account, AccountIdentityProvenance provenance) { + account.setAccountUuid(UUID.randomUUID()); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(account.getId()); + when(accountRepository.findById(account.getId())).thenReturn(Optional.of(account)); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + } + + private void assignInvalidAuthenticationIdentity( + Account account, InvalidAuthenticationIdentity failure) { + setPersistedAuthenticationIdentity(account); + switch (failure) { + case MISSING_UUID -> account.setAccountUuid(null); + case NIL_UUID -> account.setAccountUuid(new UUID(0L, 0L)); + case MISSING_PROVENANCE -> account.setAccountUuidProvenance(null); + case MISSING_SOURCE_ROW -> account.setAccountUuidSourceNumericId(null); + case CONTRADICTORY_SOURCE_ROW -> account.setAccountUuidSourceNumericId(33L); + } + } + + private enum InvalidAuthenticationIdentity { + MISSING_UUID, + NIL_UUID, + MISSING_PROVENANCE, + MISSING_SOURCE_ROW, + CONTRADICTORY_SOURCE_ROW + } + private static DirectTextCallerContext directTextCaller() { return new DirectTextCallerContext( 11L, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java new file mode 100644 index 0000000000..19f76ace6c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.accountservice.service.impl; + +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 com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.TooManyRowsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.dao.DataAccessResourceFailureException; + +class RuntimeAccountIdentityGrpcServiceTest { + private static final String WORKLOAD_NAMESPACE = "test"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + private final AccountRepository repository = mock(AccountRepository.class); + private final RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, WORKLOAD_NAMESPACE); + + @ParameterizedTest + @ValueSource(strings = {GAME_SESSION_URI, ENTITY_MANAGEMENT_URI}) + void resolvesExactPersistedIdentityForEachAllowedRuntimePeer(String peerUri) { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenReturn( + Optional.of( + account(ACCOUNT_ID, AccountIdentityProvenance.ACCOUNT_V29_MIGRATION, 42L, 42L))); + + TestObserver observer = call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), peerUri); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getSchemaVersion()).isEqualTo(1); + assertThat(observer.value.getTargetNamespace()).isEqualTo(WORKLOAD_NAMESPACE); + assertThat(observer.value.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(observer.value.getCanonicalAccountId()).isEqualTo(ACCOUNT_ID.toString()); + assertThat(observer.value.getSourceAccountRowId()).isEqualTo(42L); + assertThat(observer.value.getAccountUuidProvenance()).isEqualTo("ACCOUNT_V29_MIGRATION"); + assertThat(observer.value.getSourceNumericRowId()).isEqualTo(42L); + verify(repository).findByAccountUuid(ACCOUNT_ID); + } + + @Test + void deniesMissingWrongNamespaceAndUntrustedPeerIdentitiesBeforeOwnerRead() { + assertThat(status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/other/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/test/sa/social-groups-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { + RuntimeAccountIdentityGrpcService inactiveService = + new RuntimeAccountIdentityGrpcService(repository, ""); + TestObserver observer = new TestObserver(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); + + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + inactiveService.resolveRuntimeAccountIdentity( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), observer)); + + assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsNoncanonicalNilAndOpenMetadataRequestsBeforeOwnerRead() { + assertThat( + status( + call( + request(ACCOUNT_ID.toString().toUpperCase(), REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request("00000000-0000-0000-0000-000000000000", REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), "00000000-0000-0000-0000-000000000000"), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + ResolveRuntimeAccountIdentityRequest openRequest = + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(status(call(openRequest, GAME_SESSION_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void returnsNotFoundAndFailsClosedForMalformedAmbiguousOrMismatchedProvenance() { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenReturn(Optional.empty()) + .thenThrow(new IllegalStateException("private malformed provenance detail")) + .thenThrow(new TooManyRowsException("private duplicate-row detail")) + .thenReturn( + Optional.of( + account(ACCOUNT_ID, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L, 43L))) + .thenReturn( + Optional.of( + account( + UUID.fromString("a2e1342e-a139-49c6-a460-c8e25f6697ae"), + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + 42L, + 42L))); + + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.NOT_FOUND); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void distinguishesTemporaryReadFailureFromInternalReadFailureWithoutLeakingDetails() { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenThrow(new DataAccessResourceFailureException("private database endpoint")) + .thenThrow(new IllegalArgumentException("private persistence detail")); + + TestObserver unavailable = + call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + TestObserver internal = + call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.failure.getDescription()) + .isEqualTo("Account identity is temporarily unavailable"); + assertThat(status(internal)).isEqualTo(Status.Code.INTERNAL); + assertThat(internal.failure.getDescription()).isEqualTo("Account identity could not be read"); + } + + private static Account account( + UUID accountUuid, AccountIdentityProvenance provenance, Long rowId, Long sourceNumericRowId) { + Account account = new Account(); + account.setId(rowId); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(sourceNumericRowId); + return account; + } + + private static ResolveRuntimeAccountIdentityRequest request(String accountId, String requestId) { + return ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(accountId) + .setRequestId(requestId) + .build(); + } + + private TestObserver call(ResolveRuntimeAccountIdentityRequest request, String peerUri) { + TestObserver observer = new TestObserver(); + Runnable invocation = () -> service.resolveRuntimeAccountIdentity(request, observer); + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private static Status.Code status(TestObserver observer) { + assertThat(observer.failure).isNotNull(); + return observer.failure.getCode(); + } + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeAccountIdentityResponse value; + private Status failure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeAccountIdentityResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java new file mode 100644 index 0000000000..575d73484a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.common.account; + +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Read-only Account owner evidence for one persisted canonical account identity. + * + *

The retained numeric row values are private provenance evidence, not gameplay identity. This + * record does not establish membership, actor ownership, namespace ownership, or admission. + */ +public record RuntimeAccountIdentityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + long sourceAccountRowId, + String accountUuidProvenance, + long sourceNumericRowId) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public RuntimeAccountIdentityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported runtime account identity schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalAccountId, "canonicalAccountId"); + if (sourceAccountRowId <= 0L || sourceNumericRowId <= 0L) { + throw new IllegalArgumentException("Account source row identities must be positive"); + } + if (sourceAccountRowId != sourceNumericRowId) { + throw new IllegalArgumentException("Account source row identities must match exactly"); + } + if (!isRecognizedProvenance(accountUuidProvenance)) { + throw new IllegalArgumentException("Account UUID provenance is not recognized"); + } + } + + private static boolean isRecognizedProvenance(String provenance) { + return "ACCOUNT_V29_MIGRATION".equals(provenance) + || "ACCOUNT_REPOSITORY_INSERT".equals(provenance) + || "ACCOUNT_DATABASE_INSERT".equals(provenance); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a nonnil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java new file mode 100644 index 0000000000..cb8925834d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ForwardingClientCall.SimpleForwardingClientCall; +import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; + +/** Rejects response content unless its TLS session proves one exact server workload URI. */ +public final class GrpcServerPeerIdentityClientInterceptor implements ClientInterceptor { + private final String expectedPeerUri; + + public GrpcServerPeerIdentityClientInterceptor(String expectedPeerUri) { + this.expectedPeerUri = + GrpcPeerIdentity.parseUri(expectedPeerUri) + .map(GrpcPeerIdentity::uri) + .filter(uri -> uri.equals(expectedPeerUri)) + .orElseThrow( + () -> new IllegalArgumentException("Exact server workload URI is required")); + } + + @Override + public ClientCall interceptCall( + MethodDescriptor method, CallOptions options, Channel next) { + ClientCall call = next.newCall(method, options); + return new SimpleForwardingClientCall<>(call) { + @Override + public void start(Listener listener, Metadata headers) { + super.start( + new SimpleForwardingClientCallListener<>(listener) { + private boolean verified; + private boolean closed; + + private boolean requireVerifiedPeer() { + if (closed) { + return false; + } + if (verified) { + return true; + } + verified = + GrpcPeerIdentity.fromSslSession( + call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .filter(peer -> expectedPeerUri.equals(peer.uri())) + .isPresent(); + if (!verified) { + closed = true; + listener.onClose( + Status.UNAUTHENTICATED.withDescription( + "Response lacks the exact authenticated server workload identity"), + new Metadata()); + call.cancel("Server workload identity mismatch", null); + } + return verified; + } + + @Override + public void onHeaders(Metadata responseHeaders) { + if (requireVerifiedPeer()) { + super.onHeaders(responseHeaders); + } + } + + @Override + public void onMessage(RespT message) { + if (requireVerifiedPeer()) { + super.onMessage(message); + } + } + + @Override + public void onClose(Status status, Metadata trailers) { + if (closed || (status.isOk() && !requireVerifiedPeer())) { + return; + } + closed = true; + super.onClose(status, trailers); + } + }, + headers); + } + }; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java new file mode 100644 index 0000000000..06366df88b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.common.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable Game Design owner evidence for one persisted runtime tenant identity. */ +public record RuntimeTenantIdentityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int MAX_SOURCE_KEY_CODE_POINTS = 36; + private static final int MAX_SOURCE_KEY_UTF16_LENGTH = 72; + + public RuntimeTenantIdentityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported runtime tenant identity schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); + if (sourceGameTenantKey.isBlank() + || sourceGameTenantKey.length() > MAX_SOURCE_KEY_UTF16_LENGTH + || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) + > MAX_SOURCE_KEY_CODE_POINTS + || !StandardCharsets.UTF_8.newEncoder().canEncode(sourceGameTenantKey)) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { + throw new IllegalArgumentException("Runtime tenant provenance kind is not recognized"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java new file mode 100644 index 0000000000..b2373a0f38 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.common.account; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class RuntimeAccountIdentityEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void acceptsEachCanonicalAccountProvenanceKind() { + assertThat(evidence("ACCOUNT_V29_MIGRATION").sourceAccountRowId()).isEqualTo(73L); + assertThat(evidence("ACCOUNT_REPOSITORY_INSERT").accountUuidProvenance()) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(evidence("ACCOUNT_DATABASE_INSERT").accountUuidProvenance()) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + } + + @Test + void rejectsUnsupportedSchemaNamespaceIdentitySourceRowAndProvenance() { + RuntimeAccountIdentityEvidence valid = evidence("ACCOUNT_V29_MIGRATION"); + assertInvalid( + 2, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance(), + valid.sourceNumericRowId()); + assertInvalid( + 1, + "test.invalid", + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance(), + valid.sourceNumericRowId()); + assertInvalid( + 1, + valid.targetNamespace(), + new UUID(0L, 0L), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance(), + valid.sourceNumericRowId()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + new UUID(0L, 0L), + valid.sourceAccountRowId(), + valid.accountUuidProvenance(), + valid.sourceNumericRowId()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + 0L, + valid.accountUuidProvenance(), + valid.sourceNumericRowId()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance(), + 0L); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance(), + valid.sourceNumericRowId() + 1L); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + null, + valid.sourceNumericRowId()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + "UNKNOWN", + valid.sourceNumericRowId()); + } + + private static RuntimeAccountIdentityEvidence evidence(String provenance) { + return new RuntimeAccountIdentityEvidence( + 1, "test", REQUEST_ID, ACCOUNT_ID, 73L, provenance, 73L); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + long sourceAccountRowId, + String provenance, + long sourceNumericRowId) { + assertThatThrownBy( + () -> + new RuntimeAccountIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalAccountId, + sourceAccountRowId, + provenance, + sourceNumericRowId)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java new file mode 100644 index 0000000000..d9b08d7541 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java @@ -0,0 +1,206 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import javax.net.ssl.SSLSession; +import org.junit.jupiter.api.Test; + +class GrpcServerPeerIdentityClientInterceptorTest { + private static final String EXPECTED = "spiffe://firemud/ns/firemud/sa/game-design-service"; + + @Test + void deliversOnlyTheExactAuthenticatedServerResponse() throws Exception { + Fixture fixture = fixture(session(EXPECTED)); + fixture.call.listener.onHeaders(new Metadata()); + fixture.call.listener.onMessage("owner evidence"); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.headers).hasSize(1); + assertThat(fixture.messages).containsExactly("owner evidence"); + assertThat(fixture.statuses).containsExactly(Status.OK); + assertThat(fixture.call.cancelled).isFalse(); + } + + @Test + void missingAmbiguousDifferentWorkloadOrNamespaceCannotDeliverHeadersOrContent() + throws Exception { + var sessions = new ArrayList(); + sessions.add(null); + sessions.add(session()); + sessions.add(session(EXPECTED, "spiffe://firemud/ns/firemud/sa/account-service")); + sessions.add(session("spiffe://firemud/ns/firemud/sa/account-service")); + sessions.add(session("spiffe://firemud/ns/other/sa/game-design-service")); + sessions.add(session("not-a-workload-identity")); + for (SSLSession session : sessions) { + Fixture fixture = fixture(session); + fixture.call.listener.onHeaders(new Metadata()); + fixture.call.listener.onMessage("untrusted evidence"); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.headers).isEmpty(); + assertThat(fixture.messages).isEmpty(); + assertThat(fixture.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(fixture.call.cancelled).isTrue(); + } + } + + @Test + void contentWithoutHeadersStillRequiresExactPeer() throws Exception { + Fixture unverified = fixture(null); + unverified.call.listener.onMessage("unexpected content"); + assertThat(unverified.messages).isEmpty(); + assertThat(unverified.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + Fixture verified = fixture(session(EXPECTED)); + verified.call.listener.onMessage("owner evidence"); + assertThat(verified.messages).containsExactly("owner evidence"); + } + + @Test + void emptySuccessfulReplyCannotBypassPeerValidation() throws Exception { + Fixture fixture = fixture(null); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(fixture.call.cancelled).isTrue(); + } + + @Test + void transportFailureRemainsUnavailableWithoutInventingAuthenticatedEvidence() throws Exception { + Fixture fixture = fixture(null); + fixture.call.listener.onClose(Status.UNAVAILABLE, new Metadata()); + assertThat(fixture.statuses).containsExactly(Status.UNAVAILABLE); + assertThat(fixture.headers).isEmpty(); + assertThat(fixture.messages).isEmpty(); + assertThat(fixture.call.cancelled).isFalse(); + } + + @Test + void unverifiedCertificateDeniesResponseWithoutThrowingIntoConsumer() throws Exception { + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()) + .thenThrow(new javax.net.ssl.SSLPeerUnverifiedException("no peer")); + Fixture fixture = fixture(session); + fixture.call.listener.onHeaders(new Metadata()); + fixture.call.listener.onClose(Status.OK, new Metadata()); + assertThat(fixture.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(fixture.messages).isEmpty(); + } + + @Test + void configuredIdentityMustBeOneExactCanonicalWorkloadUri() { + assertThatThrownBy(() -> new GrpcServerPeerIdentityClientInterceptor(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new GrpcServerPeerIdentityClientInterceptor("not-a-workload")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://FIREMUD/ns/firemud/sa/game-design-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SSLSession session(String... peerUris) throws Exception { + SSLSession session = mock(SSLSession.class); + X509Certificate certificate = mock(X509Certificate.class); + List> alternatives = new ArrayList<>(); + for (String uri : peerUris) { + alternatives.add(List.of(6, uri)); + } + when(certificate.getSubjectAlternativeNames()).thenReturn(alternatives); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + return session; + } + + private static Fixture fixture(SSLSession session) { + var fixture = new Fixture(); + fixture.call.attributes = + session == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + Channel channel = mock(Channel.class); + when(channel.newCall(null, CallOptions.DEFAULT)).thenReturn(fixture.call); + ClientCall intercepted = + new GrpcServerPeerIdentityClientInterceptor(EXPECTED) + .interceptCall(null, CallOptions.DEFAULT, channel); + intercepted.start( + new ClientCall.Listener<>() { + @Override + public void onHeaders(Metadata headers) { + fixture.headers.add(headers); + } + + @Override + public void onMessage(Object message) { + fixture.messages.add(message); + } + + @Override + public void onClose(Status status, Metadata trailers) { + fixture.statuses.add(status); + } + }, + new Metadata()); + return fixture; + } + + private static final class Fixture { + private final TestCall call = new TestCall(); + private final List headers = new ArrayList<>(); + private final List messages = new ArrayList<>(); + private final List statuses = new ArrayList<>(); + } + + private static final class TestCall extends ClientCall { + private Listener listener; + private Attributes attributes; + private boolean cancelled; + + @Override + public void start(Listener listener, Metadata headers) { + this.listener = listener; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public void request(int count) {} + + @Override + public void cancel(String message, Throwable cause) { + cancelled = true; + } + + @Override + public void halfClose() {} + + @Override + public void sendMessage(Object message) {} + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java new file mode 100644 index 0000000000..0be76125d2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class RuntimeTenantIdentityEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void acceptsNewAndRetainedOwnerEvidence() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + } + + @Test + void rejectsUnsupportedOrIncompleteOwnerEvidence() { + RuntimeTenantIdentityEvidence valid = evidence("NEW_GAME_ROW"); + assertInvalid( + 2, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + "test.invalid", + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + new UUID(0L, 0L), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + new UUID(0L, 0L), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + 0, + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + " ", + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "x".repeat(37), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "invalid-" + (char) 0xd800, + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + "UNKNOWN"); + } + + private static RuntimeTenantIdentityEvidence evidence(String provenanceKind) { + return new RuntimeTenantIdentityEvidence( + 1, "test", REQUEST_ID, TENANT_ID, 42L, "source-game-key-42", provenanceKind); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> + new RuntimeTenantIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java index b39011f625..5e492c7aee 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java @@ -53,14 +53,14 @@ public void start(Listener responseListener, Metadata headers) { } static String createBearerToken(JwtUtil jwtUtil, RuntimeIdentity runtimeIdentity) { - Long accountId = SessionContext.currentAccountIdOrNull(); + String accountId = SessionContext.getAccountId(); List globalRoles = SessionContext.getGlobalRoles(); Map> scopedRoles = SessionContext.getScopedRolesMap(); - if (accountId == null) { + if (accountId == null || accountId.isBlank()) { return createInternalBearerToken(jwtUtil, runtimeIdentity); } - String accountIdText = Long.toString(accountId); + String accountIdText = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); Map claims = new HashMap<>(); claims.put("accountId", accountIdText); claims.put("globalRoles", globalRoles == null ? List.of() : globalRoles); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java index adec1fad6a..d40c0e5959 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.security; import io.jsonwebtoken.Claims; +import java.util.UUID; import org.springframework.util.StringUtils; /** Shared helpers for canonical JWT claim extraction and normalization. */ @@ -42,10 +43,36 @@ public static long requireSignedActorAccountId(Claims claims, String mismatchMes return claimedAccountId; } + public static String requireCanonicalAccountUuid(Object value, String claimName) { + if (!(value instanceof String text) + || !StringUtils.hasText(text) + || !text.equals(text.trim())) { + throw new IllegalArgumentException("Malformed claim: " + claimName); + } + try { + UUID accountUuid = UUID.fromString(text); + if (!accountUuid.toString().equals(text) || accountUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Invalid claim: " + claimName); + } + return text; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Malformed claim: " + claimName, ex); + } + } + + public static String requireSignedGameplayAccountUuid(Claims claims, String mismatchMessage) { + String subjectAccountUuid = requireCanonicalAccountUuid(claims.getSubject(), "sub"); + String claimedAccountUuid = requireCanonicalAccountUuid(claims.get("accountId"), "accountId"); + if (!subjectAccountUuid.equals(claimedAccountUuid)) { + throw new IllegalArgumentException(mismatchMessage); + } + return claimedAccountUuid; + } + public static SignedGameplayRoutingClaims requireSignedGameplayRoutingClaims( Claims claims, String accountMismatchMessage) { return new SignedGameplayRoutingClaims( - requireSignedActorAccountId(claims, accountMismatchMessage), + requireSignedGameplayAccountUuid(claims, accountMismatchMessage), requireLong(claims.get("tenantId"), "tenantId", false), requireText(claims.get("worldSlug"), "worldSlug"), requireText(claims.get("realmSlug"), "realmSlug"), @@ -80,7 +107,7 @@ private static String firstNonBlank(Iterable values) { } public record SignedGameplayRoutingClaims( - long accountId, + String accountId, long tenantId, String worldSlug, String realmSlug, diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java index 31140c22c0..ddcd76ae07 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java @@ -19,6 +19,8 @@ import org.junit.jupiter.api.Test; class GrpcClientAuthTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3"; private static final Metadata.Key AUTH_HEADER = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); @@ -38,15 +40,18 @@ void attachUsesCurrentSessionContextPerCall() { TestStub stub = new TestStub(channel, CallOptions.DEFAULT); TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); - SessionContext.setContext("1", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); customized.invoke(); String firstToken = bearerToken(channel.lastAuthorization()); - assertThat(jwtUtil.parseToken(firstToken).getPayload().getSubject()).isEqualTo("1"); + assertThat(jwtUtil.parseToken(firstToken).getPayload().getSubject()).isEqualTo(ACCOUNT_UUID); + assertThat(jwtUtil.parseToken(firstToken).getPayload().get("accountId")) + .isEqualTo(ACCOUNT_UUID); - SessionContext.setContext("2", List.of("player"), Map.of()); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("player"), Map.of()); customized.invoke(); String secondToken = bearerToken(channel.lastAuthorization()); - assertThat(jwtUtil.parseToken(secondToken).getPayload().getSubject()).isEqualTo("2"); + assertThat(jwtUtil.parseToken(secondToken).getPayload().getSubject()) + .isEqualTo(OTHER_ACCOUNT_UUID); assertThat(secondToken).isNotEqualTo(firstToken); } @@ -77,7 +82,19 @@ void attachRejectsMalformedCurrentAccountClaim() { TestStub stub = new TestStub(channel, CallOptions.DEFAULT); TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); - SessionContext.setContext("not-a-long", List.of("player"), Map.of()); + SessionContext.setContext("not-a-uuid", List.of("player"), Map.of()); + + assertThrows(IllegalArgumentException.class, customized::invoke); + assertThat(channel.lastAuthorization()).isNull(); + } + + @Test + void attachRejectsNumericCurrentAccountClaim() { + CapturingChannel channel = new CapturingChannel(); + TestStub stub = new TestStub(channel, CallOptions.DEFAULT); + TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); + + SessionContext.setContext("42", List.of("player"), Map.of()); assertThrows(IllegalArgumentException.class, customized::invoke); assertThat(channel.lastAuthorization()).isNull(); diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java index 97c999e90d..26c0024caa 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java @@ -11,6 +11,8 @@ import org.junit.jupiter.api.Test; class JwtClaimsTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + @Test void requireLongParsesNumericTextAndRejectsInvalidValues() { assertEquals(7L, JwtClaims.requireLong("7", "accountId", false)); @@ -87,10 +89,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_UUID, Map.of( "accountId", - "11", + ACCOUNT_UUID, "tenantId", "7", "worldSlug", @@ -104,7 +106,7 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle .getPayload(); JwtClaims.SignedGameplayRoutingClaims routingClaims = JwtClaims.requireSignedGameplayRoutingClaims(validClaims, "signed gameplay mismatch"); - assertEquals(11L, routingClaims.accountId()); + assertEquals(ACCOUNT_UUID, routingClaims.accountId()); assertEquals(7L, routingClaims.tenantId()); assertEquals("demo", routingClaims.worldSlug()); assertEquals("production", routingClaims.realmSlug()); @@ -115,10 +117,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_UUID, Map.of( "accountId", - "11", + ACCOUNT_UUID, "tenantId", "7", "worldSlug", @@ -140,10 +142,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_UUID, Map.of( "accountId", - "11", + ACCOUNT_UUID, "tenantId", "7", "worldSlug", @@ -161,4 +163,45 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle JwtClaims.requireSignedGameplayRoutingClaims( zeroPointerClaims, "signed gameplay mismatch")); } + + @Test + void requireSignedGameplayAccountUuidRejectsNoncanonicalOrIncompatibleCarriers() { + JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); + + for (String accountId : + List.of( + "11", + "not-a-uuid", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + "00000000-0000-0000-0000-000000000000", + " " + ACCOUNT_UUID)) { + Claims claims = + jwtUtil + .parseToken(jwtUtil.generateToken(accountId, Map.of("accountId", accountId))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireSignedGameplayAccountUuid(claims, "account subject mismatch")); + } + + Claims mismatchedClaims = + jwtUtil + .parseToken( + jwtUtil.generateToken( + ACCOUNT_UUID, Map.of("accountId", "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3"))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedGameplayAccountUuid( + mismatchedClaims, "account subject mismatch")); + + Claims numericClaim = + jwtUtil + .parseToken(jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", 42L))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireSignedGameplayAccountUuid(numericClaim, "account subject mismatch")); + } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java new file mode 100644 index 0000000000..7fe4b89ca7 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.entitymanagement.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.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.account.v1.RuntimeAccountIdentityServiceGrpc; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +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; + +/** Unwired Entity Management candidate for exact Account-owned runtime identity reads. */ +public final class AccountRuntimeIdentityClient + extends AbstractReloadingBlockingGrpcClient< + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + + public AccountRuntimeIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityManagementMtls(tlsProps), + channelFactory, + AccountRuntimeIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes the client only when an explicit caller owns activation of this handoff. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + return RuntimeAccountIdentityServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service")) + .withCompression("gzip"); + } + + /** Reads Account's exact persisted identity provenance without granting gameplay authority. */ + public RuntimeAccountIdentityEvidence resolveRuntimeAccountIdentity( + String canonicalAccountId, String requestId) { + UUID accountUuid = parseCanonicalNonNilUuid(canonicalAccountId, "canonical account ID"); + UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub currentStub = + stub(); + if (currentStub == null) { + throw new IllegalStateException("Account runtime identity client is not initialized"); + } + + ResolveRuntimeAccountIdentityResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveRuntimeAccountIdentity( + ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(accountUuid.toString()) + .setRequestId(requestUuid.toString()) + .build()); + if (response == null) { + throw new IllegalStateException("Account runtime identity response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Account runtime identity response contains unsupported fields"); + } + + RuntimeAccountIdentityEvidence evidence; + try { + evidence = + new RuntimeAccountIdentityEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"), + parseCanonicalNonNilUuid( + response.getCanonicalAccountId(), "response canonical account ID"), + response.getSourceAccountRowId(), + response.getAccountUuidProvenance(), + response.getSourceNumericRowId()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Account runtime identity response is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !requestUuid.equals(evidence.requestId()) + || !accountUuid.equals(evidence.canonicalAccountId())) { + throw new IllegalStateException( + "Account runtime identity response does not match the exact request"); + } + return evidence; + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static CommonGrpcClientProperties requireEntityManagementMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Entity Management gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Runtime account identity reads require Entity Management workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Runtime account identity reads require Entity Management certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Runtime account identity reads require file-backed Entity Management workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java new file mode 100644 index 0000000000..b98b2fe449 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java @@ -0,0 +1,313 @@ +package unit.net.firedevops.firemud.entitymanagement.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +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.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.account.v1.RuntimeAccountIdentityServiceGrpc; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +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.entitymanagement.client.AccountRuntimeIdentityClient; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +class AccountRuntimeIdentityClientTest { + private static final String NAMESPACE = "test"; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final long SOURCE_ROW_ID = 73L; + + @Test + void forwardsExactCanonicalRequestAndReturnsTypedOwnerEvidence() throws Exception { + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeAccountIdentity(any())) + .thenReturn(validResponse("ACCOUNT_REPOSITORY_INSERT")); + AccountRuntimeIdentityClient client = newClient(stub); + + RuntimeAccountIdentityEvidence evidence = + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString()); + + assertThat(evidence.schemaVersion()).isEqualTo(1); + assertThat(evidence.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(evidence.requestId()).isEqualTo(REQUEST_ID); + assertThat(evidence.canonicalAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(evidence.sourceAccountRowId()).isEqualTo(SOURCE_ROW_ID); + assertThat(evidence.sourceNumericRowId()).isEqualTo(SOURCE_ROW_ID); + assertThat(evidence.accountUuidProvenance()).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ResolveRuntimeAccountIdentityRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).resolveRuntimeAccountIdentity(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getCanonicalAccountId()).isEqualTo(ACCOUNT_ID.toString()); + assertThat(requestCaptor.getValue().getRequestId()).isEqualTo(REQUEST_ID.toString()); + } + + @Test + void rejectsMalformedInputsBeforeStubOrChannelUse() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountRuntimeIdentityClient client = newClientWithoutStub(channelFactory); + List invalidRequests = + List.of( + new String[] {null, REQUEST_ID.toString()}, + new String[] {"", REQUEST_ID.toString()}, + new String[] {"AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", REQUEST_ID.toString()}, + new String[] {"11111111-1111-4111-8111-11111111111", REQUEST_ID.toString()}, + new String[] {"00000000-0000-0000-0000-000000000000", REQUEST_ID.toString()}, + new String[] {ACCOUNT_ID.toString(), null}, + new String[] {ACCOUNT_ID.toString(), ""}, + new String[] {ACCOUNT_ID.toString(), "22222222-2222-4222-8222-22222222222"}, + new String[] {ACCOUNT_ID.toString(), "00000000-0000-0000-0000-000000000000"}); + + for (String[] invalid : invalidRequests) { + assertThatThrownBy(() -> client.resolveRuntimeAccountIdentity(invalid[0], invalid[1])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsUninitializedClientAndAbsentOwnerResponseWithoutActivation() throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountRuntimeIdentityClient uninitialized = newClientWithoutStub(channelFactory); + assertThatThrownBy( + () -> + uninitialized.resolveRuntimeAccountIdentity( + ACCOUNT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeAccountIdentity(any())).thenReturn(null); + AccountRuntimeIdentityClient client = newClient(stub); + assertThatThrownBy( + () -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("absent"); + } + + @Test + void rejectsSchemaMismatchAndEveryResponseFieldOutsideTheExactRequest() throws Exception { + ResolveRuntimeAccountIdentityResponse valid = validResponse("ACCOUNT_V29_MIGRATION"); + assertRejected(valid.toBuilder().setSchemaVersion(2).build()); + assertRejected(valid.toBuilder().setTargetNamespace("other").build()); + assertRejected(valid.toBuilder().setTargetNamespace("").build()); + assertRejected( + valid.toBuilder().setCanonicalAccountId("AB426BB3-A733-43F0-9C8E-2E379CBDF7EC").build()); + assertRejected( + valid.toBuilder().setCanonicalAccountId("33333333-3333-4333-8333-333333333333").build()); + assertRejected( + valid.toBuilder().setCanonicalAccountId("00000000-0000-0000-0000-000000000000").build()); + assertRejected(valid.toBuilder().setRequestId("33333333-3333-4333-8333-333333333333").build()); + assertRejected(valid.toBuilder().setRequestId("22222222-2222-4222-8222-22222222222").build()); + assertRejected(valid.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build()); + assertRejected(valid.toBuilder().setSourceAccountRowId(0L).build()); + assertRejected(valid.toBuilder().setSourceNumericRowId(0L).build()); + assertRejected(valid.toBuilder().setSourceNumericRowId(SOURCE_ROW_ID + 1L).build()); + assertRejected(valid.toBuilder().setAccountUuidProvenance("").build()); + assertRejected(valid.toBuilder().setAccountUuidProvenance("UNKNOWN").build()); + assertRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + } + + @Test + void propagatesTimeoutAndProviderFailuresWithFiniteDeadline() throws Exception { + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub stub = mockStub(); + StatusRuntimeException timeout = + new StatusRuntimeException(Status.DEADLINE_EXCEEDED.withDescription("Account timed out")); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Account unavailable")); + when(stub.resolveRuntimeAccountIdentity(any())).thenThrow(timeout).thenThrow(unavailable); + AccountRuntimeIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + .isSameAs(timeout); + assertThatThrownBy( + () -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + .isSameAs(unavailable); + + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + + assertThatThrownBy( + () -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + for (CommonGrpcClientProperties incomplete : + List.of( + incompleteMtlsProperties(null, "entity.key", "account-ca.crt"), + incompleteMtlsProperties("entity.crt", null, "account-ca.crt"), + incompleteMtlsProperties("entity.crt", "entity.key", null))) { + assertThatThrownBy( + () -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("certificate, key, and CA"); + } + + for (CommonGrpcClientProperties classpath : + List.of( + incompleteMtlsProperties("classpath:entity.crt", "entity.key", "account-ca.crt"), + incompleteMtlsProperties("entity.crt", "classpath:entity.key", "account-ca.crt"), + incompleteMtlsProperties("entity.crt", "entity.key", "classpath:account-ca.crt"))) { + assertThatThrownBy( + () -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + assertThatThrownBy( + () -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(channelFactory); + } + + @Test + void initUsesConfiguredAccountTargetAndFileBackedTls(@TempDir Path directory) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + CommonGrpcClientProperties tls = mtlsProperties(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + AccountRuntimeIdentityClient client = + new AccountRuntimeIdentityClient(endpoints, tls, channelFactory, NAMESPACE); + + verifyNoInteractions(channelFactory); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("account.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static void assertRejected(ResolveRuntimeAccountIdentityResponse response) + throws Exception { + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeAccountIdentity(any())).thenReturn(response); + AccountRuntimeIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class); + } + + private static AccountRuntimeIdentityClient newClient( + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub stub) + throws Exception { + AccountRuntimeIdentityClient client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static AccountRuntimeIdentityClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + } + + private static RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub + mockStub() { + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub stub = + mock(RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static ResolveRuntimeAccountIdentityResponse validResponse(String provenance) { + return ResolveRuntimeAccountIdentityResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(REQUEST_ID.toString()) + .setCanonicalAccountId(ACCOUNT_ID.toString()) + .setSourceAccountRowId(SOURCE_ROW_ID) + .setAccountUuidProvenance(provenance) + .setSourceNumericRowId(SOURCE_ROW_ID) + .build(); + } + + private static CommonGrpcClientProperties mtlsProperties() { + return incompleteMtlsProperties( + "entity-management-client.crt", "entity-management-client.key", "account-ca.crt"); + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + return incompleteMtlsProperties( + Files.createFile(directory.resolve("entity-management-client.crt")).toString(), + Files.createFile(directory.resolve("entity-management-client.key")).toString(), + Files.createFile(directory.resolve("account-ca.crt")).toString()); + } + + private static CommonGrpcClientProperties incompleteMtlsProperties( + String certificate, String privateKey, String caCertificate) { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return tls; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java index 83572c7198..204de77695 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.gamedesign.entity; +import java.util.UUID; import lombok.Data; @Data public class Game { private Long id; private String tenantId; + private UUID canonicalTenantId; private String name; private String description; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java index f9a4d6c07c..2d3c2c6c40 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java @@ -3,10 +3,12 @@ import net.firedevops.firemud.gamedesign.dto.GameDto; import net.firedevops.firemud.gamedesign.entity.Game; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface GameMapper { GameDto toDto(Game entity); + @Mapping(target = "canonicalTenantId", ignore = true) Game toEntity(GameDto dto); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java index 57bce6b96d..638f33c93d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java @@ -2,7 +2,10 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Game; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -18,6 +21,14 @@ public class GameRepository { private static final Table GAME_TABLE = DSL.table(DSL.name("game")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_IDENTITY_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field TENANT_IDENTITY_SOURCE_GAME_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); private static final Field NAME = DSL.field(DSL.name("name"), String.class); private static final Field DESCRIPTION = DSL.field(DSL.name("description"), String.class); @@ -33,22 +44,66 @@ public List findAll() { public Game save(Game game) { if (game.getId() == null) { + if (game.getCanonicalTenantId() != null) { + throw new IllegalArgumentException("Canonical tenant identity is issued by Game Design"); + } Record record = dsl.insertInto(GAME_TABLE) .set(TENANT_ID, game.getTenantId()) .set(NAME, game.getName()) .set(DESCRIPTION, game.getDescription()) - .returning(ID, TENANT_ID, NAME, DESCRIPTION) + .returning( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, + NAME, + DESCRIPTION) .fetchOne(); - return toEntity(record); + if (record == null) { + throw new IllegalStateException("Game insert did not return its persisted row"); + } + Game saved = toEntity(record); + GameTenantIdentity identity = toTenantIdentity(record); + if (saved == null + || saved.getId() == null + || !saved.getId().equals(identity.sourceGameId()) + || !saved.getTenantId().equals(identity.sourceLegacyTenantId()) + || identity.provenanceKind() != GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW) { + throw new IllegalStateException( + "Persisted game tenant identity did not match its owner row"); + } + return saved; } - dsl.update(GAME_TABLE) - .set(TENANT_ID, game.getTenantId()) - .set(NAME, game.getName()) - .set(DESCRIPTION, game.getDescription()) - .where(ID.eq(game.getId())) - .execute(); - return findByTenantId(game.getTenantId()); + Condition identityCondition = ID.eq(game.getId()); + if (game.getTenantId() != null) { + identityCondition = identityCondition.and(TENANT_ID.eq(game.getTenantId())); + } + if (game.getCanonicalTenantId() != null) { + identityCondition = + identityCondition.and(CANONICAL_TENANT_ID.eq(game.getCanonicalTenantId())); + } + Record record = + dsl.update(GAME_TABLE) + .set(NAME, game.getName()) + .set(DESCRIPTION, game.getDescription()) + .where(identityCondition) + .returning( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, + NAME, + DESCRIPTION) + .fetchOne(); + if (record == null) { + throw new IllegalStateException("Game update identity does not match a persisted game row"); + } + return toEntity(record); } public Game findByTenantId(String tenantId) { @@ -65,6 +120,24 @@ public Game findByTenantIdForUpdate(String tenantId) { .fetchOne(this::toEntity); } + /** Reads one persisted tenant UUID and validates its provenance against the actual owner row. */ + public Optional findRuntimeTenantIdentityByCanonicalTenantId( + UUID canonicalTenantId) { + if (canonicalTenantId == null) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + return dsl.select( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) + .from(GAME_TABLE) + .where(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .fetchOptional(this::toRuntimeTenantIdentity); + } + private Game toEntity(Record record) { if (record == null) { return null; @@ -72,8 +145,65 @@ private Game toEntity(Record record) { Game game = new Game(); game.setId(record.get(ID)); game.setTenantId(record.get(TENANT_ID)); + game.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); game.setName(record.get(NAME)); game.setDescription(record.get(DESCRIPTION)); return game; } + + private GameTenantIdentity toTenantIdentity(Record record) { + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); + String provenanceKindValue = record.get(TENANT_IDENTITY_PROVENANCE_KIND); + Long sourceGameId = record.get(TENANT_IDENTITY_SOURCE_GAME_ID); + String sourceLegacyTenantId = record.get(TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID); + if (canonicalTenantId == null + || provenanceKindValue == null + || sourceGameId == null + || sourceGameId <= 0 + || sourceLegacyTenantId == null + || sourceLegacyTenantId.isBlank()) { + throw new IllegalStateException("Persisted game tenant identity provenance is incomplete"); + } + GameTenantIdentity.ProvenanceKind provenanceKind; + try { + provenanceKind = GameTenantIdentity.ProvenanceKind.valueOf(provenanceKindValue); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Persisted game tenant identity provenance kind is unknown", exception); + } + return new GameTenantIdentity( + canonicalTenantId, provenanceKind, sourceGameId, sourceLegacyTenantId); + } + + private GameTenantIdentity toRuntimeTenantIdentity(Record record) { + Long actualGameId = record.get(ID); + String actualTenantKey = record.get(TENANT_ID); + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); + String provenanceKindValue = record.get(TENANT_IDENTITY_PROVENANCE_KIND); + Long sourceGameId = record.get(TENANT_IDENTITY_SOURCE_GAME_ID); + String sourceTenantKey = record.get(TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID); + if (actualGameId == null + || actualGameId <= 0 + || actualTenantKey == null + || actualTenantKey.isBlank() + || canonicalTenantId == null + || provenanceKindValue == null + || sourceGameId == null + || sourceGameId <= 0 + || sourceTenantKey == null + || !actualGameId.equals(sourceGameId) + || !actualTenantKey.equals(sourceTenantKey)) { + throw new IllegalStateException( + "Persisted runtime tenant identity provenance does not match its game row"); + } + + GameTenantIdentity.ProvenanceKind provenanceKind; + try { + provenanceKind = GameTenantIdentity.ProvenanceKind.valueOf(provenanceKindValue); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Persisted runtime tenant identity provenance kind is unknown", exception); + } + return new GameTenantIdentity(canonicalTenantId, provenanceKind, actualGameId, actualTenantKey); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java new file mode 100644 index 0000000000..10e7f0aae2 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.repository; + +import java.util.UUID; + +/** Game Design's canonical tenant identity and exact provenance in its owning game row. */ +public record GameTenantIdentity( + UUID canonicalTenantId, + ProvenanceKind provenanceKind, + Long sourceGameId, + String sourceLegacyTenantId) { + public enum ProvenanceKind { + RETAINED_GAME_V29, + NEW_GAME_ROW + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java new file mode 100644 index 0000000000..15a26369a6 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.jooq.exception.TooManyRowsException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; + +/** Authenticated read of Game Design's own retained tenant identity provenance. */ +@GrpcService +public class TenantIdentityGrpcService + extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { + private final GameRepository gameRepository; + private final String workloadNamespace; + + public TenantIdentityGrpcService( + GameRepository gameRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.gameRepository = gameRepository; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest request, + StreamObserver responseObserver) { + if (!isGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + if (canonicalTenantId == null + || requestId == null + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription( + "Canonical nonnil IDs and the exact metadata request schema are required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = gameRepository.findRuntimeTenantIdentityByCanonicalTenantId(canonicalTenantId); + } catch (IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity provenance is ambiguous or invalid") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design tenant identity is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Game Design tenant identity is temporarily unavailable" + : "Game Design tenant identity could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Game Design tenant identity could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No Game Design tenant identity for exact canonical tenant ID") + .asRuntimeException()); + return; + } + + GameTenantIdentity identity = resolved.orElseThrow(); + RuntimeTenantIdentityEvidence evidence; + try { + if (!canonicalTenantId.equals(identity.canonicalTenantId())) { + throw new IllegalArgumentException("Resolved tenant UUID does not match the request"); + } + evidence = + new RuntimeTenantIdentityEvidence( + 1, + workloadNamespace, + requestId, + identity.canonicalTenantId(), + identity.sourceGameId() == null ? 0L : identity.sourceGameId(), + identity.sourceLegacyTenantId(), + identity.provenanceKind() == null ? null : identity.provenanceKind().name()); + } catch (RuntimeException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design tenant identity readback is incomplete or inconsistent") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveRuntimeTenantIdentityResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(evidence.requestId().toString()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .build()); + responseObserver.onCompleted(); + } + + private boolean isGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"); + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return !new UUID(0L, 0L).equals(parsed) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException ex) { + return null; + } + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 4de4297c8d..d1bce34ed8 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -59,6 +59,9 @@ server: firemud: auth: + grpc: + public-methods: + - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity http: enabled: true role-requirement: PRIVILEGED @@ -72,6 +75,7 @@ firemud: - method: GET path-pattern: /.well-known/** grpc: + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} diff --git a/services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql b/services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql new file mode 100644 index 0000000000..a6758bc557 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql @@ -0,0 +1,68 @@ +ALTER TABLE game + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN tenant_identity_provenance_kind VARCHAR(32), + ADD COLUMN tenant_identity_source_game_id BIGINT, + ADD COLUMN tenant_identity_source_legacy_tenant_id VARCHAR(36); + +-- A UUID is issued only for an exact, nonblank, bounded owner key. Rows outside +-- that shape remain unproven and cannot be resolved by the runtime read. +UPDATE game +SET canonical_tenant_id = gen_random_uuid(), + tenant_identity_provenance_kind = 'RETAINED_GAME_V29', + tenant_identity_source_game_id = id, + tenant_identity_source_legacy_tenant_id = tenant_id +WHERE char_length(tenant_id) BETWEEN 1 AND 36 + AND tenant_id ~ '[^[:space:]]'; + +ALTER TABLE game + ADD CONSTRAINT uq_game_canonical_tenant_id UNIQUE (canonical_tenant_id), + ADD CONSTRAINT chk_game_tenant_identity_provenance CHECK ( + (canonical_tenant_id IS NULL + AND tenant_identity_provenance_kind IS NULL + AND tenant_identity_source_game_id IS NULL + AND tenant_identity_source_legacy_tenant_id IS NULL) + OR + (canonical_tenant_id IS NOT NULL + AND tenant_identity_provenance_kind IS NOT NULL + AND tenant_identity_provenance_kind IN ('RETAINED_GAME_V29', 'NEW_GAME_ROW') + AND tenant_identity_source_game_id IS NOT NULL + AND tenant_identity_source_game_id = id + AND tenant_identity_source_legacy_tenant_id IS NOT NULL + AND tenant_identity_source_legacy_tenant_id = tenant_id + AND char_length(tenant_identity_source_legacy_tenant_id) BETWEEN 1 AND 36 + AND tenant_identity_source_legacy_tenant_id ~ '[^[:space:]]') + ); + +-- [jooq ignore start] +CREATE FUNCTION enforce_game_tenant_identity() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + NEW.canonical_tenant_id := gen_random_uuid(); + NEW.tenant_identity_provenance_kind := 'NEW_GAME_ROW'; + NEW.tenant_identity_source_game_id := NEW.id; + NEW.tenant_identity_source_legacy_tenant_id := NEW.tenant_id; + RETURN NEW; + END IF; + + IF NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + RAISE EXCEPTION 'game legacy tenant_id is immutable after canonical tenant identity issuance' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.tenant_identity_provenance_kind IS DISTINCT FROM OLD.tenant_identity_provenance_kind + OR NEW.tenant_identity_source_game_id IS DISTINCT FROM OLD.tenant_identity_source_game_id + OR NEW.tenant_identity_source_legacy_tenant_id IS DISTINCT FROM OLD.tenant_identity_source_legacy_tenant_id THEN + RAISE EXCEPTION 'game canonical tenant identity and provenance are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_tenant_identity_immutable + BEFORE INSERT OR UPDATE ON game + FOR EACH ROW + EXECUTE FUNCTION enforce_game_tenant_identity(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java new file mode 100644 index 0000000000..ef2dab2ea3 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java @@ -0,0 +1,177 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameTenantIdentityRepositoryIntegrationTest { + private static final String SERVICE_SCHEMA = "game_design_service"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final org.jooq.Field ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final org.jooq.Field SOURCE_GAME_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final org.jooq.Field SOURCE_LEGACY_TENANT_ID = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migratesOnlyExactOwnerKeysAndReadsImmutableGameRowProvenance() throws Exception { + DriverManagerDataSource dataSource = dataSource(); + migrate(dataSource, MigrationVersion.fromVersion("28")); + + long retainedGameId; + long quarantinedGameId; + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection); + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + retainedGameId = insertLegacyGame(dsl, "legacy-owner-alpha", "Alpha"); + quarantinedGameId = insertLegacyGame(dsl, " ", "Unproven"); + } + + migrate(dataSource, null); + + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection); + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + GameRepository repository = new GameRepository(dsl); + UUID retainedTenantId = + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(ID.eq(retainedGameId)) + .fetchOne(CANONICAL_TENANT_ID); + + assertThat(retainedTenantId).isNotNull(); + assertThat(repository.findRuntimeTenantIdentityByCanonicalTenantId(retainedTenantId)) + .contains( + new GameTenantIdentity( + retainedTenantId, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V29, + retainedGameId, + "legacy-owner-alpha")); + assertThat( + dsl.select( + CANONICAL_TENANT_ID, PROVENANCE_KIND, SOURCE_GAME_ID, SOURCE_LEGACY_TENANT_ID) + .from(GAME) + .where(ID.eq(quarantinedGameId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(PROVENANCE_KIND)).isNull(); + assertThat(row.get(SOURCE_GAME_ID)).isNull(); + assertThat(row.get(SOURCE_LEGACY_TENANT_ID)).isNull(); + }); + assertThat(repository.findRuntimeTenantIdentityByCanonicalTenantId(UUID.randomUUID())) + .isEmpty(); + + Game newGame = new Game(); + newGame.setTenantId("new-owner-key"); + newGame.setName("New"); + Game saved = repository.save(newGame); + assertThat(saved.getCanonicalTenantId()).isNotNull(); + assertThat(saved.getId()).isPositive(); + assertThat( + repository.findRuntimeTenantIdentityByCanonicalTenantId(saved.getCanonicalTenantId())) + .contains( + new GameTenantIdentity( + saved.getCanonicalTenantId(), + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + saved.getId(), + "new-owner-key")); + + Game forgedGame = new Game(); + forgedGame.setTenantId("forged-owner-key"); + forgedGame.setName("Forged"); + forgedGame.setCanonicalTenantId(UUID.randomUUID()); + assertThatThrownBy(() -> repository.save(forgedGame)) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(TENANT_ID, "renamed-owner-key") + .where(ID.eq(retainedGameId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.update(GAME) + .set(SOURCE_GAME_ID, SOURCE_GAME_ID.plus(1L)) + .where(ID.eq(retainedGameId)) + .execute()) + .isInstanceOf(DataAccessException.class); + assertThat(dsl.fetchCount(GAME)).isEqualTo(3); + } + } + + private DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, MigrationVersion target) { + FluentConfiguration configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(SERVICE_SCHEMA) + .defaultSchema(SERVICE_SCHEMA) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", SERVICE_SCHEMA)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private void setSearchPath(Connection connection) throws Exception { + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO game_design_service"); + } + } + + private long insertLegacyGame(DSLContext dsl, String tenantId, String name) { + return Objects.requireNonNull( + dsl.insertInto(GAME) + .set(TENANT_ID, tenantId) + .set(NAME, name) + .returning(ID) + .fetchOne(ID)) + .longValue(); + } +} 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 new file mode 100644 index 0000000000..91007bb76b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -0,0 +1,244 @@ +package unit.net.firedevops.firemud.gamedesign.security; + +import static org.assertj.core.api.Assertions.assertThat; +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.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 java.io.IOException; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.v1.PingRequest; +import net.firedevops.firemud.gamedesign.v1.PingResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class TenantIdentityGrpcAuthWiringTest { + private static final String TENANT_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity"; + private static final String PING_METHOD = "gamedesign.v1.GameDesignService/Ping"; + private static final String TENANT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; + private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final MethodDescriptor< + ResolveRuntimeTenantIdentityRequest, ResolveRuntimeTenantIdentityResponse> + TENANT_METHOD_DESCRIPTOR = + unaryMethod( + TENANT_METHOD, + ResolveRuntimeTenantIdentityRequest.getDefaultInstance(), + ResolveRuntimeTenantIdentityResponse.getDefaultInstance()); + private static final MethodDescriptor PING_METHOD_DESCRIPTOR = + unaryMethod(PING_METHOD, PingRequest.getDefaultInstance(), PingResponse.getDefaultInstance()); + + @Test + void noTokenWithValidSameNamespacePeerReachesTenantIdentityService() { + withConfiguredInterceptor( + interceptor -> { + GameRepository repository = mock(GameRepository.class); + UUID tenantId = UUID.fromString(TENANT_UUID); + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(tenantId)) + .thenReturn( + Optional.of( + new GameTenantIdentity( + tenantId, + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + 42L, + "legacy-owner-key-42"))); + TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); + + DispatchResult result = dispatchTenantMethod(interceptor, service, GAME_SESSION_URI); + + assertThat(result.observer().failure).isFalse(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(result.handlerDispatched()).isTrue(); + verify(repository).findRuntimeTenantIdentityByCanonicalTenantId(tenantId); + }); + } + + @Test + void noTokenWithAbsentOrWrongPeerIsDeniedBeforeOwnerRead() { + withConfiguredInterceptor( + interceptor -> { + GameRepository repository = mock(GameRepository.class); + TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); + + DispatchResult absent = dispatchTenantMethod(interceptor, service, null); + DispatchResult wrong = + dispatchTenantMethod( + interceptor, service, "spiffe://firemud/ns/test/sa/account-service"); + + assertThat(absent.observer().failure).isTrue(); + assertThat(absent.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrong.observer().failure).isTrue(); + assertThat(wrong.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(absent.handlerDispatched()).isTrue(); + assertThat(wrong.handlerDispatched()).isTrue(); + org.mockito.Mockito.verifyNoInteractions(repository); + }); + } + + @Test + void unrelatedGameDesignMethodRemainsBearerProtected() { + withConfiguredInterceptor( + interceptor -> { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(PING_METHOD_DESCRIPTOR); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = mock(ServerCallHandler.class); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(next, never()) + .startCall( + org.mockito.ArgumentMatchers.eq(call), + org.mockito.ArgumentMatchers.any(Metadata.class)); + }); + } + + private static DispatchResult dispatchTenantMethod( + AuthTokenInterceptor interceptor, TenantIdentityGrpcService service, String peerUri) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(TENANT_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + TestObserver observer = new TestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ResolveRuntimeTenantIdentityRequest, ResolveRuntimeTenantIdentityResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ResolveRuntimeTenantIdentityRequest request) { + service.resolveRuntimeTenantIdentity(request, observer); + } + }; + } + }; + ResolveRuntimeTenantIdentityRequest request = + ResolveRuntimeTenantIdentityRequest.newBuilder() + .setCanonicalTenantId(TENANT_UUID) + .setRequestId(REQUEST_UUID) + .build(); + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, new Metadata(), next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new DispatchResult(observer, handlerDispatched.get()); + } + + private static void withConfiguredInterceptor( + java.util.function.Consumer action) { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withInitializer( + context -> { + try { + PropertySource gameDesignApplication = + new YamlPropertySourceLoader() + .load( + "game-design-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(gameDesignApplication); + } catch (IOException exception) { + throw new IllegalStateException( + "Could not load Game Design application config", exception); + } + }) + .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .containsExactly(TENANT_METHOD); + action.accept(context.getBean(AuthTokenInterceptor.class)); + }); + } + + private static + MethodDescriptor unaryMethod( + String fullMethodName, ReqT requestDefault, RespT responseDefault) { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(requestDefault)) + .setResponseMarshaller(ProtoUtils.marshaller(responseDefault)) + .build(); + } + + private record DispatchResult(TestObserver observer, boolean handlerDispatched) {} + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeTenantIdentityResponse response; + private Status.Code statusCode; + private boolean failure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeTenantIdentityResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = true; + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java new file mode 100644 index 0000000000..79336c6cce --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -0,0 +1,206 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +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 com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import org.jooq.exception.TooManyRowsException; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; + +class TenantIdentityGrpcServiceTest { + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID TENANT_ID = UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + private final GameRepository repository = mock(GameRepository.class); + private final TenantIdentityGrpcService service = + new TenantIdentityGrpcService(repository, "test"); + + @Test + void resolvesExactOwnerIdentityForAuthenticatedGameSessionPeer() { + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID)) + .thenReturn( + Optional.of( + new GameTenantIdentity( + TENANT_ID, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V29, + 42L, + "legacy-owner-key-42"))); + + TestObserver observer = + call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getSchemaVersion()).isEqualTo(1); + assertThat(observer.value.getTargetNamespace()).isEqualTo("test"); + assertThat(observer.value.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(observer.value.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(observer.value.getSourceGameRowId()).isEqualTo(42L); + assertThat(observer.value.getSourceGameTenantKey()).isEqualTo("legacy-owner-key-42"); + assertThat(observer.value.getProvenanceKind()).isEqualTo("RETAINED_GAME_V29"); + verify(repository).findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID); + } + + @Test + void rejectsUnauthenticatedWrongNamespaceAndWrongServiceBeforeOwnerRead() { + assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(TENANT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/other/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(TENANT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { + TenantIdentityGrpcService inactiveService = new TenantIdentityGrpcService(repository, ""); + TestObserver observer = new TestObserver(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); + + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + inactiveService.resolveRuntimeTenantIdentity( + request(TENANT_ID.toString(), REQUEST_ID.toString()), observer)); + + assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsNoncanonicalNilAndOpenMetadataRequestsBeforeOwnerRead() { + assertThat( + status( + call( + request(TENANT_ID.toString().toUpperCase(), REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request("00000000-0000-0000-0000-000000000000", REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request(TENANT_ID.toString(), "00000000-0000-0000-0000-000000000000"), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + ResolveRuntimeTenantIdentityRequest openRequest = + request(TENANT_ID.toString(), REQUEST_ID.toString()).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(status(call(openRequest, GAME_SESSION_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void returnsNotFoundAndFailsClosedForInvalidOrAmbiguousOwnerEvidence() { + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID)) + .thenReturn(Optional.empty()) + .thenReturn( + Optional.of( + new GameTenantIdentity( + TENANT_ID, GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, 42L, " "))) + .thenThrow(new TooManyRowsException("duplicate owner identity")); + + assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.NOT_FOUND); + assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void mapsUnavailableOwnerReadWithoutReturningPartialEvidence() { + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID)) + .thenThrow(new DataAccessResourceFailureException("unavailable")); + + TestObserver observer = + call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + + assertThat(status(observer)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + + private static ResolveRuntimeTenantIdentityRequest request(String tenantId, String requestId) { + return ResolveRuntimeTenantIdentityRequest.newBuilder() + .setCanonicalTenantId(tenantId) + .setRequestId(requestId) + .build(); + } + + private TestObserver call(ResolveRuntimeTenantIdentityRequest request, String peerUri) { + TestObserver observer = new TestObserver(); + Runnable invocation = () -> service.resolveRuntimeTenantIdentity(request, observer); + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private static Status.Code status(TestObserver observer) { + assertThat(observer.grpcFailure).isTrue(); + assertThat(observer.failure).isNotNull(); + return observer.failure; + } + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeTenantIdentityResponse value; + private Status.Code failure; + private boolean grpcFailure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeTenantIdentityResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + grpcFailure = throwable instanceof StatusRuntimeException; + failure = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java index 926dee9c20..252a22c196 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Optional; import java.util.TreeSet; +import java.util.UUID; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.grpc.GrpcAppErrors; @@ -40,6 +41,7 @@ public class CommunicationAggregationService { private static final Logger LOG = LoggerFactory.getLogger(CommunicationAggregationService.class); private static final String OBSERVER_METADATA_ONLY_FLAG = "observer_metadata_only"; + private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private final SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialStub; private final EntityManagementServiceGrpc.EntityManagementServiceBlockingStub entityStub; @@ -56,10 +58,10 @@ public SendCommunicationResponse send(SendCommunicationRequest request) { SendCommunicationResponse.newBuilder() .setType(request.getType()) .setMessage(normalizedText); - String validatedAccountId = parsePositiveAccountId(request.getAccountId()); - if (validatedAccountId == null) { + String validatedAccountUuid = parseCanonicalAccountUuid(request.getAccountId()); + if (validatedAccountUuid == null) { return errorResponse( - builder, "INVALID_ARGUMENT", "account_id must be a positive numeric account id"); + builder, "INVALID_ARGUMENT", "account_id must be a canonical non-nil Account UUID"); } if (tenantId != null && !isSocialCapabilityEnabled(tenantId, gameInstanceId)) { @@ -102,7 +104,7 @@ public SendCommunicationResponse send(SendCommunicationRequest request) { socialStub.sendMessage( SendMessageRequest.newBuilder() .setTenantId(request.getTenantId()) - .setSenderId(validatedAccountId) + .setSenderId(validatedAccountUuid) .setType(mapType(request.getType())) .setContent(normalizedText) .setRecipientId(audience.recipientId().orElse("")) @@ -396,15 +398,16 @@ private Long parseTenantId(String tenantId) { } } - private String parsePositiveAccountId(String accountId) { - if (!StringUtils.hasText(accountId)) { + private String parseCanonicalAccountUuid(String accountUuid) { + if (accountUuid == null || accountUuid.isEmpty()) { return null; } - String normalized = accountId.trim(); try { - long parsed = Long.parseLong(normalized); - return parsed > 0L ? Long.toString(parsed) : null; - } catch (NumberFormatException ignored) { + UUID parsed = UUID.fromString(accountUuid); + return parsed.equals(NIL_ACCOUNT_UUID) || !parsed.toString().equals(accountUuid) + ? null + : accountUuid; + } catch (IllegalArgumentException ignored) { return null; } } diff --git a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java index 5091a32be2..b13a3656b4 100644 --- a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java +++ b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java @@ -41,7 +41,7 @@ @ExtendWith(MockitoExtension.class) class CommunicationAggregationServiceTest { - private static final String VALID_ACCOUNT_ID = "42"; + private static final String VALID_ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; @Mock private SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialStub; @@ -125,14 +125,16 @@ void unavailableSocialCapabilityAuthorityFailsClosedWithoutCallingDownstreamServ } @Test - void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { + void rejectsMissingMalformedAndNonCanonicalAccountUuidsBeforeDownstreamCalls() { for (String[] accountIdCase : new String[][] { {"empty", ""}, {"whitespace-only", " "}, - {"malformed", "not-a-number"}, - {"zero", "0"}, - {"negative", "-1"}, + {"malformed", "not-a-uuid"}, + {"numeric", "42"}, + {"nil", "00000000-0000-0000-0000-000000000000"}, + {"uppercase", VALID_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT)}, + {"whitespace-padded", " " + VALID_ACCOUNT_ID + " "}, }) { String accountIdCaseDescription = accountIdCase[0]; String accountId = accountIdCase[1]; @@ -154,7 +156,7 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { .isEqualTo("INVALID_ARGUMENT"); assertThat(resp.getError().getMessage()) .as(accountIdCaseDescription) - .isEqualTo("account_id must be a positive numeric account id"); + .isEqualTo("account_id must be a canonical non-nil Account UUID"); } verify(entityStub, never()).listRoomEntities(any()); @@ -162,27 +164,26 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { } @Test - void normalizesPaddedNoncanonicalAccountIdForSocialSender() { - when(socialStub.sendMessage(any())) - .thenReturn(SendMessageResponse.newBuilder().setSuccess(true).build()); - + void rejectsWhitespacePaddedAccountUuidBeforeDownstreamCalls() { SendCommunicationResponse resp = service.send( SendCommunicationRequest.newBuilder() .setTenantId("tenant-1") .setSessionId("sess-1") .setCharacterId("player-0") - .setAccountId(" 0042 ") + .setAccountId(" " + VALID_ACCOUNT_ID + " ") .setType(CommunicationType.TELL) .setTargetCharacterId("player-9") .setTargetCharacterName("Sora") .setText("Meet me outside") .build()); - assertThat(resp.getSuccess()).isTrue(); - ArgumentCaptor captor = ArgumentCaptor.forClass(SendMessageRequest.class); - verify(socialStub).sendMessage(captor.capture()); - assertThat(captor.getValue().getSenderId()).isEqualTo("42"); + assertThat(resp.getSuccess()).isFalse(); + assertThat(resp.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(resp.getError().getMessage()) + .isEqualTo("account_id must be a canonical non-nil Account UUID"); + verify(entityStub, never()).listRoomEntities(any()); + verify(socialStub, never()).sendMessage(any()); } @Test diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java new file mode 100644 index 0000000000..2eb99d9bcf --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java @@ -0,0 +1,164 @@ +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.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; + +/** Unwired Game Session candidate for exact owner-local runtime tenant identity reads. */ +public final class GameDesignRuntimeTenantIdentityClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + + public GameDesignRuntimeTenantIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProps), + channelFactory, + GameDesignRuntimeTenantIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes the client only when an explicit caller owns activation of 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 TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + return TenantIdentityServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) + .withCompression("gzip"); + } + + /** Reads persisted Game Design identity and validates every returned owner field. */ + public RuntimeTenantIdentityEvidence resolveRuntimeTenantIdentity( + String canonicalTenantId, String requestId) { + UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); + UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Design runtime tenant identity client is not initialized"); + } + + ResolveRuntimeTenantIdentityResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest.newBuilder() + .setCanonicalTenantId(tenantUuid.toString()) + .setRequestId(requestUuid.toString()) + .build()); + if (response == null) { + throw new IllegalStateException("Game Design runtime tenant identity response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Game Design runtime tenant identity response contains unsupported fields"); + } + + RuntimeTenantIdentityEvidence evidence; + try { + evidence = + new RuntimeTenantIdentityEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"), + parseCanonicalNonNilUuid( + response.getCanonicalTenantId(), "response canonical tenant ID"), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design runtime tenant identity response is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !requestUuid.equals(evidence.requestId()) + || !tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Game Design runtime tenant identity response does not match the exact request"); + } + return evidence; + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + 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( + "Runtime tenant identity reads require Game Session workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Runtime tenant identity 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( + "Runtime tenant identity 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/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index e192fad1db..80d2d5c745 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -47,6 +47,7 @@ import net.firedevops.firemud.gamelogic.v1.PingResponse; import net.firedevops.firemud.gamelogic.v1.SendCommunicationRequest; import net.firedevops.firemud.gamelogic.v1.SendCommunicationResponse; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.GameplayRuntimeRoomIds; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -156,18 +157,22 @@ public SendCommunicationResponse sendCommunication( String targetCharacterId, String targetCharacterName, String effectId) { + String accountUuid = context.accountId(); + if (!AccountIds.isCanonicalNonNilUuid(accountUuid)) { + throw new IllegalArgumentException( + "Session context must contain a canonical non-nil Account UUID"); + } String canonicalRoomId = GameplayRuntimeRoomIds.requireCanonical(roomId, "roomInstanceId"); String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); String characterId = Long.toString(context.characterId()); - String accountId = context.accountId(); String gameInstanceId = Long.toString(context.gameInstanceId()); SendCommunicationRequest request = SendCommunicationRequest.newBuilder() .setTenantId(tenantId) .setSessionId(sessionId) .setCharacterId(characterId) - .setAccountId(accountId == null ? "" : accountId) + .setAccountId(accountUuid) .setRoomInstance( RoomInstanceRef.newBuilder() .setTenantId(tenantId) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 4f800c6f8d..fd209a04d7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -15,13 +15,13 @@ import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; -import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; @@ -31,6 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Component; /** Handles LOGIN/LOGON commands and generates immediate responses when possible. */ @@ -138,13 +139,15 @@ public LoginCommandHandlingResult handle( return failure(errorCode, publicErrorMessage(error, errorCode)); } - Long authenticatedAccountId = parseAccountId(authResponse.getAccountId()); - if (authenticatedAccountId == null || authenticatedAccountId <= 0) { + String authenticatedAccountId = parseAccountId(authResponse.getAccountId()); + if (authenticatedAccountId == null) { clearFailedLoginSessionState( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); } - invalidateStaleFirstPartyConnectContext(numericSessionId, authenticatedAccountId); + if (!invalidateStaleFirstPartyConnectContext(numericSessionId, authenticatedAccountId)) { + return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); + } persistSessionContext( numericSessionId, instance.getTenantId(), @@ -163,12 +166,16 @@ public LoginCommandHandlingResult handle( Map.of("loginName", canonicalLoginName)))); } - private void invalidateStaleFirstPartyConnectContext(long sessionId, long accountId) { - firstPartyConnectContextRegistry - .find(sessionId) - .filter( - connectContext -> !Objects.equals(connectContext.accountId(), Long.toString(accountId))) - .ifPresent(ignored -> firstPartyConnectContextRegistry.unregister(sessionId)); + private boolean invalidateStaleFirstPartyConnectContext(long sessionId, String accountId) { + try { + firstPartyConnectContextRegistry + .find(sessionId) + .filter(connectContext -> !Objects.equals(connectContext.accountId(), accountId)) + .ifPresent(ignored -> firstPartyConnectContextRegistry.unregister(sessionId)); + return true; + } catch (SerializationException | ClassCastException ex) { + return false; + } } private LoginCommandHandlingResult handleEmailLoginChallenge( @@ -214,8 +221,9 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI Optional maybeContext = connectContextResolution.connectContext(); if (connectContextResolution.invalid()) { - clearFailedLoginSessionState( + clearFailedFirstPartyLoginSessionState( numericSessionId, + existingSession, existingSession != null ? existingSession.tenantId() : 0L, existingSession != null ? existingSession.bootstrapGameInstanceId() : 0L, existingSession != null ? existingSession.worldSlug() : null, @@ -231,18 +239,7 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI } var verifiedContext = maybeContext.get(); - if (existingSession != null - && existingSession.hasAccountIdentity() - && !Objects.equals(existingSession.accountId(), verifiedContext.accountId())) { - firstPartyConnectContextRegistry.unregister(numericSessionId); - return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); - } - long numericAccountId; - try { - numericAccountId = - PositiveLongParsing.requireOptionalText(verifiedContext.accountId(), "accountId") - .orElseThrow(() -> new IllegalArgumentException("accountId must be positive")); - } catch (IllegalArgumentException ex) { + if (!AccountIds.isCanonicalNonNilUuid(verifiedContext.accountId())) { clearFailedFirstPartyLoginSessionState( numericSessionId, existingSession, @@ -253,6 +250,12 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI verifiedContext.pointerVersion()); return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); } + if (existingSession != null + && existingSession.hasAccountIdentity() + && !Objects.equals(existingSession.accountId(), verifiedContext.accountId())) { + firstPartyConnectContextRegistry.unregister(numericSessionId); + return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); + } Optional maybeInstance = gameInstanceRepository.findById(verifiedContext.gameInstanceId()); if (maybeInstance.isEmpty()) { @@ -292,7 +295,7 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI persistSessionContext( numericSessionId, verifiedContext.tenantId(), - numericAccountId, + verifiedContext.accountId(), "first-party:" + verifiedContext.accountId(), null, verifiedContext.gameInstanceId(), @@ -315,7 +318,9 @@ private void clearFailedFirstPartyLoginSessionState( String worldSlug, String realmSlug, long pointerVersion) { - if (existingSession != null && existingSession.hasAccountIdentity()) { + if (existingSession != null + && existingSession.accountId() != null + && !existingSession.accountId().isBlank()) { return; } clearFailedLoginSessionState( @@ -330,7 +335,7 @@ private void clearFailedFirstPartyLoginSessionState( private void persistSessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, String jwt, long bootstrapGameInstanceId, @@ -347,7 +352,7 @@ private void persistSessionContext( projectedExisting != null && projectedExisting.tenantId() == tenantId ? projectedExisting : null; - String accountIdText = Long.toString(accountId); + String accountIdText = accountId; boolean sameAuthenticatedAccount = existing != null && Objects.equals(existing.accountId(), accountIdText); Optional reusableBootstrapShell = @@ -426,7 +431,7 @@ private void persistSessionContext( private Optional reusableBootstrapShell( SessionContext existing, long tenantId, - long accountId, + String accountId, long bootstrapGameInstanceId, net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedConnectContext, String verifiedPlayableStateScope) { @@ -447,7 +452,7 @@ private Optional reusableBootstrapShell( boolean verifiedIdentityAndTargetMatch = verifiedConnectContext.hasCompleteRoutingScope() - && Objects.equals(verifiedConnectContext.accountId(), Long.toString(accountId)) + && Objects.equals(verifiedConnectContext.accountId(), accountId) && verifiedConnectContext.tenantId() == tenantId && verifiedConnectContext.gameInstanceId() == bootstrapGameInstanceId && Objects.equals(existing.playableStateScope(), verifiedPlayableStateScope) @@ -467,7 +472,7 @@ private Optional reusableBootstrapShell( private SessionContext authenticatedBootstrapContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, String jwt, SessionContext bootstrapShell, @@ -475,7 +480,7 @@ private SessionContext authenticatedBootstrapContext( return new SessionContext( sessionId, tenantId, - Long.toString(accountId), + accountId, loginName, 0L, null, @@ -665,13 +670,8 @@ private SessionIdParsing.ParsedSessionId parseSessionId(String sessionIdText) { return SessionIdParsing.parse(sessionIdText); } - private Long parseAccountId(String accountIdText) { - PositiveLongParsing.ParsedPositiveLong parsed = - PositiveLongParsing.parseOptionalText(accountIdText, "accountId"); - if (!parsed.valid()) { - return null; - } - return parsed.value(); + private String parseAccountId(String accountIdText) { + return AccountIds.isCanonicalNonNilUuid(accountIdText) ? accountIdText : null; } private LoginCommandHandlingResult invalidSessionFailure(String message) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java new file mode 100644 index 0000000000..a3a63d6f5a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.UUID; + +/** Validation for canonical Account logical identifiers carried by Game Session. */ +public final class AccountIds { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountIds() {} + + public static boolean isCanonicalNonNilUuid(String value) { + if (value == null || value.isEmpty()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java index f2b6e237fe..d70bcc3463 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java @@ -18,7 +18,7 @@ public record FirstPartyConnectContext( private static final long serialVersionUID = 1L; public boolean hasCompleteRoutingScope() { - return StringUtils.hasText(accountId) + return AccountIds.isCanonicalNonNilUuid(accountId) && tenantId > 0L && gameInstanceId > 0L && pointerVersion > 0L diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java index b3be62a86b..c2d8f2405c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java @@ -2,6 +2,7 @@ import java.util.Objects; import java.util.Optional; +import org.springframework.data.redis.serializer.SerializationException; public record FirstPartyConnectContextResolution( Optional connectContext, boolean invalid) { @@ -16,8 +17,14 @@ public static FirstPartyConnectContextResolution resolve( FirstPartyConnectContextRegistry firstPartyConnectContextRegistry) { Objects.requireNonNull( firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); - Optional registryContext = - firstPartyConnectContextRegistry.find(sessionId); + Optional registryContext; + try { + registryContext = firstPartyConnectContextRegistry.find(sessionId); + } catch (SerializationException | ClassCastException ex) { + // An unreadable legacy carrier is not absence and cannot authorize persisted-context + // fallback. + return new FirstPartyConnectContextResolution(Optional.empty(), true); + } if (registryContext.isPresent()) { FirstPartyConnectContext connectContext = registryContext.orElseThrow(); return new FirstPartyConnectContextResolution( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java index fa8d707640..5882a8ed83 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java @@ -42,7 +42,7 @@ public Optional parse(String token) { claims, "first-party connect context account subject mismatch"); return Optional.of( new FirstPartyConnectContext( - Long.toString(routingClaims.accountId()), + routingClaims.accountId(), routingClaims.tenantId(), routingClaims.worldSlug(), routingClaims.realmSlug(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java index 0ebff77e98..f14a5f3963 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java @@ -92,6 +92,9 @@ public Optional resolveByGameplayName( public SessionContext normalizeResolvedContext(SessionContext context) { Objects.requireNonNull(context, "context must not be null"); + if (context.accountId() != null && !context.hasAccountIdentity()) { + return context; + } SessionContext normalized = sessionRoutingNormalizationService.normalizeProjectedContext(context); if (normalized.equals(context)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index d2ca6ff738..a033cdac80 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -4,7 +4,6 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; -import org.springframework.util.StringUtils; /** Represents persisted login context stored in Redis for a session. */ public record SessionContext( @@ -284,7 +283,7 @@ public boolean hasGameplayIdentity() { } public boolean hasAccountIdentity() { - return StringUtils.hasText(accountId); + return AccountIds.isCanonicalNonNilUuid(accountId); } public boolean hasGameplayBinding() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java index 3c4a0e5084..37b96251d8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java @@ -11,6 +11,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; @@ -59,11 +60,17 @@ public AccountPresenceQueryServiceImpl( public List queryAccountPresence( long tenantId, String viewerAccountId, List accountIds) { Objects.requireNonNull(accountIds, "accountIds"); + if (!AccountIds.isCanonicalNonNilUuid(viewerAccountId)) { + throw new IllegalArgumentException( + "viewerAccountId must be a canonical non-nil Account UUID"); + } LinkedHashSet requestedIds = new LinkedHashSet<>(); for (String accountId : accountIds) { - if (accountId != null && !accountId.isBlank()) { - requestedIds.add(accountId); + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException( + "accountIds must contain canonical non-nil Account UUIDs"); } + requestedIds.add(accountId); } if (requestedIds.isEmpty()) { return List.of(); @@ -74,18 +81,21 @@ public List queryAccountPresence( Map recentStates = accountRecentPresenceService.findByAccountIds(tenantId, requestedIds); for (String accountId : requestedIds) { - results.put( - accountId, - offline(tenantId, accountId, recentStates.get(accountId), currentRuntimePointers)); + AccountRecentPresenceState recentState = + matchingRecentState(tenantId, accountId, recentStates.get(accountId)); + results.put(accountId, offline(tenantId, accountId, recentState, currentRuntimePointers)); } Map> activePresences = gameplayPresenceService.listConnectedByAccountIds(tenantId, requestedIds); for (Map.Entry> entry : activePresences.entrySet()) { String accountId = entry.getKey(); + if (!requestedIds.contains(accountId) || !AccountIds.isCanonicalNonNilUuid(accountId)) { + continue; + } GameplayPresence presence = selectCurrentPresence(tenantId, entry.getValue(), currentRuntimePointers); - if (presence == null) { + if (presence == null || !accountId.equals(presence.accountId())) { continue; } GameplayPresenceActivityState activityState = @@ -93,7 +103,8 @@ public List queryAccountPresence( GameplayAdmissionPointerSnapshot pointer = currentRuntimePointer(tenantId, presence.gameInstanceId(), currentRuntimePointers) .orElse(null); - AccountRecentPresenceState recentState = recentStates.get(accountId); + AccountRecentPresenceState recentState = + matchingRecentState(tenantId, accountId, recentStates.get(accountId)); Long currentGameInstanceId = pointer == null ? presence.gameInstanceId() : pointer.gameInstanceId(); String currentPlayableStateScope = @@ -127,6 +138,17 @@ public List queryAccountPresence( return List.copyOf(new ArrayList<>(results.values())); } + private AccountRecentPresenceState matchingRecentState( + long tenantId, String accountId, AccountRecentPresenceState recentState) { + if (recentState == null + || recentState.tenantId() != tenantId + || !accountId.equals(recentState.accountId()) + || !AccountIds.isCanonicalNonNilUuid(recentState.accountId())) { + return null; + } + return recentState; + } + private GameplayPresence selectCurrentPresence( long tenantId, List presences, @@ -145,7 +167,10 @@ private boolean isCurrentPresence( long tenantId, GameplayPresence presence, Map currentRuntimePointers) { - if (presence == null || presence.tenantId() != tenantId || presence.gameInstanceId() <= 0) { + if (presence == null + || !AccountIds.isCanonicalNonNilUuid(presence.accountId()) + || presence.tenantId() != tenantId + || presence.gameInstanceId() <= 0) { return false; } GameplayAdmissionPointerSnapshots.RoutingBundle routingBundle = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java index 1c89763768..11e1f15473 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java @@ -14,12 +14,12 @@ import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameplayCommandRepository; import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AuthoredCommandAdmission; import net.firedevops.firemud.gamesession.service.CommandService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; -import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -100,12 +100,12 @@ public CommandEnqueueResult enqueue( } var sessionContext = resolveSessionContext(sessionIdText); - Optional numericAccountId; + Optional accountUuid; try { - numericAccountId = + accountUuid = sessionContext .map(SessionContext::accountId) - .flatMap(id -> PositiveLongParsing.requireOptionalText(id, "accountId")); + .map(CommandServiceImpl::requireCanonicalAccountUuid); } catch (IllegalArgumentException ex) { return CommandEnqueueResult.failure("INVALID_ARGUMENT", ex.getMessage()); } @@ -158,7 +158,7 @@ public CommandEnqueueResult enqueue( requiresSoloTick, queueTarget.get(), sessionContext, - numericAccountId, + accountUuid, authoredAdmission, runtimeScope.get()); logger.info( @@ -200,7 +200,7 @@ private GameplayCommand persistAcceptedCommand( boolean requiresSoloTick, QueueTarget queueTarget, Optional sessionContext, - Optional numericAccountId, + Optional accountUuid, AuthoredCommandAdmission authoredAdmission, RuntimeRegionStatus runtimeScope) { Instant now = Instant.now(); @@ -209,7 +209,7 @@ private GameplayCommand persistAcceptedCommand( gameplayCommand.setTenantId(queueTarget.tenantId()); gameplayCommand.setGameInstanceId(queueTarget.queueTargetId()); gameplayCommand.setSessionId(sessionId); - numericAccountId.ifPresent(gameplayCommand::setAccountId); + accountUuid.ifPresent(gameplayCommand::setAccountUuid); sessionContext .map(SessionContext::characterId) .filter(id -> id > 0) @@ -440,4 +440,11 @@ private Optional resolveRuntimeScope(QueueTarget queueTarge private static String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } + + private static UUID requireCanonicalAccountUuid(String value) { + if (!AccountIds.isCanonicalNonNilUuid(value)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return UUID.fromString(value); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 518ac43b8f..5624d14ef9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; @@ -232,11 +233,16 @@ private long parseOwnerAccountId(String ownerAccountIdText) { return ControlPlaneRequestParser.parsePositiveLong(ownerAccountIdText, "ownerAccountId"); } - private List parseAccountIds(List accountIds) { + private String parsePresenceAccountId(String accountId, String fieldName) { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil Account UUID"); + } + return accountId; + } + + private List parsePresenceAccountIds(List accountIds) { return accountIds.stream() - .map( - accountId -> - Long.toString(ControlPlaneRequestParser.parsePositiveLong(accountId, "accountId"))) + .map(accountId -> parsePresenceAccountId(accountId, "accountId")) .toList(); } @@ -439,16 +445,16 @@ public void queryAccountPresence( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); - long viewerAccountId = parseOwnerAccountId(request.getViewerAccountId()); + String viewerAccountId = + parsePresenceAccountId(request.getViewerAccountId(), "viewerAccountId"); requireTenantOrCurrentAccountAccess(tenantId, viewerAccountId); if (request.getAccountIdsCount() > 100) { throw new IllegalArgumentException("accountIds must contain at most 100 entries"); } - List accountIds = parseAccountIds(request.getAccountIdsList()); + List accountIds = parsePresenceAccountIds(request.getAccountIdsList()); QueryAccountPresenceResponse.Builder builder = QueryAccountPresenceResponse.newBuilder(); for (var snapshot : - accountPresenceQueryService.queryAccountPresence( - tenantId, Long.toString(viewerAccountId), accountIds)) { + accountPresenceQueryService.queryAccountPresence(tenantId, viewerAccountId, accountIds)) { AccountPresenceEntry.Builder entry = AccountPresenceEntry.newBuilder() .setAccountId(snapshot.accountId()) @@ -798,6 +804,16 @@ private void requireTenantOrCurrentAccountAccess(long tenantId, long accountId) throw new AuthorizationException("Account access required"); } + private void requireTenantOrCurrentAccountAccess(long tenantId, String accountId) { + String currentAccountId = SessionContext.getAccountId(); + if (SessionContext.hasTenantAccess(tenantId) + || (AccountIds.isCanonicalNonNilUuid(currentAccountId) + && currentAccountId.equals(accountId))) { + return; + } + throw new AuthorizationException("Account access required"); + } + private void requireInstanceAccess(long sessionId) { GameInstance instance = gameInstanceRepository diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java index dd83268e9e..96b049a65d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.function.LongSupplier; import net.firedevops.firemud.gamesession.config.PresenceProperties; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceState; @@ -67,7 +68,9 @@ public RedisAccountRecentPresenceService( @Override public void recordConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { + if (context == null + || context.tenantId() <= 0 + || !AccountIds.isCanonicalNonNilUuid(context.accountId())) { return; } GameplayPresence presence = @@ -113,13 +116,16 @@ public Map findByAccountIds( ValueOperations valueOps = redisTemplate.opsForValue(); LinkedHashMap results = new LinkedHashMap<>(); for (String accountId : accountIds) { - if (accountId == null || accountId.isBlank() || valueOps == null) { + if (!AccountIds.isCanonicalNonNilUuid(accountId) || valueOps == null) { continue; } try { AccountRecentPresenceState state = (AccountRecentPresenceState) valueOps.get(key(tenantId, accountId)); - if (state != null) { + if (state != null + && state.tenantId() == tenantId + && accountId.equals(state.accountId()) + && AccountIds.isCanonicalNonNilUuid(state.accountId())) { results.put(accountId, state); } } catch (SerializationException | ClassCastException ex) { @@ -132,7 +138,10 @@ public Map findByAccountIds( private void write( RoutingSnapshot snapshot, AccountRecentPresenceDisposition disposition, long timestampMs) { ValueOperations valueOps = redisTemplate.opsForValue(); - if (valueOps == null || snapshot == null) { + if (valueOps == null + || snapshot == null + || snapshot.tenantId() <= 0 + || !AccountIds.isCanonicalNonNilUuid(snapshot.accountId())) { return; } String key = key(snapshot.tenantId(), snapshot.accountId()); @@ -165,9 +174,14 @@ public WriteAttemptResult execute(RedisOperations operations) { operations.unwatch(); return WriteAttemptResult.PRESERVED; } - if (retained != null && !(retained instanceof AccountRecentPresenceState)) { - operations.unwatch(); - return WriteAttemptResult.PRESERVED; + if (retained != null) { + if (!(retained instanceof AccountRecentPresenceState retainedState) + || retainedState.tenantId() != snapshot.tenantId() + || !snapshot.accountId().equals(retainedState.accountId()) + || !AccountIds.isCanonicalNonNilUuid(retainedState.accountId())) { + operations.unwatch(); + return WriteAttemptResult.PRESERVED; + } } operations.multi(); operations.opsForValue().set(key, state, ttl); @@ -184,7 +198,9 @@ public WriteAttemptResult execute(RedisOperations operations) { } private RoutingSnapshot routingSnapshot(SessionContext context, GameplayPresence presence) { - if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { + if (context == null + || context.tenantId() <= 0 + || !AccountIds.isCanonicalNonNilUuid(context.accountId())) { return null; } GameplayPresence effectivePresence = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java index b8ded43bcc..661aa27084 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java @@ -30,10 +30,15 @@ public RedisFirstPartyConnectContextRegistry( @Override public void register(long sessionId, FirstPartyConnectContext connectContext) { + if (connectContext == null || !connectContext.hasCompleteRoutingScope()) { + throw new IllegalArgumentException("first-party connect context must be complete"); + } String key = key(sessionId); try { Object retained = valueOperations().get(key); - if (retained != null && !(retained instanceof FirstPartyConnectContext)) { + if (retained != null + && (!(retained instanceof FirstPartyConnectContext retainedContext) + || !retainedContext.hasCompleteRoutingScope())) { throw new IllegalStateException( "Retained first-party connect context is incompatible and cannot be replaced"); } @@ -46,22 +51,28 @@ public void register(long sessionId, FirstPartyConnectContext connectContext) { @Override public Optional find(long sessionId) { - try { - return Optional.ofNullable((FirstPartyConnectContext) valueOperations().get(key(sessionId))); - } catch (SerializationException | ClassCastException ex) { + Object retained = valueOperations().get(key(sessionId)); + if (retained == null) { return Optional.empty(); } + if (!(retained instanceof FirstPartyConnectContext context)) { + throw new ClassCastException( + "Retained first-party connect context has an incompatible value type"); + } + return Optional.of(context); } @Override public void unregister(long sessionId) { String key = key(sessionId); + Object retained; try { - if (valueOperations().get(key) instanceof FirstPartyConnectContext) { - redisTemplate.delete(key); - } + retained = valueOperations().get(key); } catch (SerializationException | ClassCastException ex) { - // Retain unreadable evidence instead of treating it as an absent context. + return; + } + if (retained instanceof FirstPartyConnectContext context && context.hasCompleteRoutingScope()) { + redisTemplate.delete(key); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index 153dfc047d..0038e27efb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -13,6 +13,7 @@ import java.util.function.LongSupplier; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; @@ -71,7 +72,10 @@ public RedisGameplayPresenceService( @Override public void registerConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || context.gameInstanceId() <= 0) { + if (context == null + || !AccountIds.isCanonicalNonNilUuid(context.accountId()) + || context.tenantId() <= 0 + || context.gameInstanceId() <= 0) { return; } ValueOperations valueOps = redisTemplate.opsForValue(); @@ -221,6 +225,9 @@ public List listConnectedByGameInstance(long tenantId, long ga setOps.remove(gameInstanceKey, sessionIdText); continue; } + if (!AccountIds.isCanonicalNonNilUuid(presence.accountId())) { + continue; + } if (presence.tenantId() == tenantId && presence.gameInstanceId() == gameInstanceId) { matches.add(presence); } @@ -246,7 +253,7 @@ public Map> listConnectedByAccountIds( LinkedHashMap> matches = new LinkedHashMap<>(); for (String accountId : accountIds) { - if (accountId == null || accountId.isBlank()) { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { continue; } String accountKey = accountKey(tenantId, accountId); @@ -272,6 +279,9 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } + if (!AccountIds.isCanonicalNonNilUuid(presence.accountId())) { + continue; + } if (presence.tenantId() != tenantId || !java.util.Objects.equals(presence.accountId(), accountId)) { setOps.remove(accountKey, sessionIdText); @@ -291,7 +301,8 @@ public Map> listConnectedByAccountIds( public Optional findConnectedBySessionId(long sessionId) { ValueOperations valueOps = redisTemplate.opsForValue(); try { - return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))); + return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))) + .filter(presence -> AccountIds.isCanonicalNonNilUuid(presence.accountId())); } catch (SerializationException | ClassCastException ex) { return Optional.empty(); } @@ -304,7 +315,12 @@ private String presenceKey(long sessionId) { private GameplayPresence readRetainedPresenceForMutation( ValueOperations valueOps, String presenceKey) { try { - return (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + if (presence != null && !AccountIds.isCanonicalNonNilUuid(presence.accountId())) { + throw new IllegalStateException( + "Retained gameplay presence has an invalid Account UUID; mutation aborted"); + } + return presence; } catch (SerializationException | ClassCastException ex) { throw new IllegalStateException( "Retained gameplay presence is unreadable or incompatible; mutation aborted", ex); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index 742f1aeb5b..f9bb75ea01 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -211,12 +211,21 @@ private List watchKeys(SessionContext context) { private SessionContext readContext( org.springframework.data.redis.core.RedisOperations operations, String key) { - return (SessionContext) operations.opsForValue().get(key); + SessionContext context = (SessionContext) operations.opsForValue().get(key); + if (context != null && context.accountId() != null && !context.hasAccountIdentity()) { + throw new IllegalStateException( + "Retained session context has a non-canonical Account identity and cannot be replaced"); + } + return context; } private Optional findContextForLookup(String key) { try { - return Optional.ofNullable((SessionContext) redisTemplate.opsForValue().get(key)); + SessionContext context = (SessionContext) redisTemplate.opsForValue().get(key); + if (context != null && context.accountId() != null && !context.hasAccountIdentity()) { + return Optional.empty(); + } + return Optional.ofNullable(context); } catch (SerializationException | ClassCastException ex) { return Optional.empty(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java new file mode 100644 index 0000000000..1487459b39 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -0,0 +1,316 @@ +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +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.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +class GameDesignRuntimeTenantIdentityClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String SOURCE_KEY = "game-design-tenant-91"; + private static final long SOURCE_ROW_ID = 91L; + + @Test + void exactOwnerResponseIsTypedAndStableOnRetryForBothProvenanceKinds() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeTenantIdentity(any())) + .thenReturn(validResponse("NEW_GAME_ROW")) + .thenReturn(validResponse("NEW_GAME_ROW")) + .thenReturn(validResponse("RETAINED_GAME_V29")) + .thenReturn(validResponse("RETAINED_GAME_V29")); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + RuntimeTenantIdentityEvidence first = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + RuntimeTenantIdentityEvidence retry = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + + assertThat(first).isEqualTo(retry); + assertThat(first.schemaVersion()).isEqualTo(1); + assertThat(first.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(first.requestId()).isEqualTo(REQUEST_ID); + assertThat(first.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(first.sourceGameRowId()).isEqualTo(SOURCE_ROW_ID); + assertThat(first.sourceGameTenantKey()).isEqualTo(SOURCE_KEY); + assertThat(first.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ResolveRuntimeTenantIdentityRequest.class); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub, times(2)).resolveRuntimeTenantIdentity(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .allSatisfy( + request -> { + assertThat(request.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(request.getRequestId()).isEqualTo(REQUEST_ID.toString()); + }); + + RuntimeTenantIdentityEvidence retained = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + RuntimeTenantIdentityEvidence retainedRetry = + client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); + assertThat(retained).isEqualTo(retainedRetry); + assertThat(retained.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retained.sourceGameRowId()).isEqualTo(SOURCE_ROW_ID); + assertThat(retained.sourceGameTenantKey()).isEqualTo(SOURCE_KEY); + } + + @Test + void rejectsMalformedRequestsBeforeAnyStubOrChannelUse() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignRuntimeTenantIdentityClient client = newClientWithoutStub(channelFactory); + List invalidRequests = + List.of( + new String[] {null, REQUEST_ID.toString()}, + new String[] {"", REQUEST_ID.toString()}, + new String[] {"AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", REQUEST_ID.toString()}, + new String[] {"11111111-1111-4111-8111-11111111111", REQUEST_ID.toString()}, + new String[] {TENANT_ID.toString(), ""}, + new String[] {TENANT_ID.toString(), "22222222-2222-4222-8222-22222222222"}, + new String[] {TENANT_ID.toString(), "00000000-0000-0000-0000-000000000000"}); + + for (String[] invalid : invalidRequests) { + assertThatThrownBy(() -> client.resolveRuntimeTenantIdentity(invalid[0], invalid[1])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsUninitializedClientAndAbsentOwnerResponse() throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignRuntimeTenantIdentityClient uninitialized = newClientWithoutStub(channelFactory); + assertThatThrownBy( + () -> + uninitialized.resolveRuntimeTenantIdentity( + TENANT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeTenantIdentity(any())).thenReturn(null); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + assertThatThrownBy( + () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("absent"); + } + + @Test + void rejectsEveryResponseFieldThatDoesNotMatchTheExactRequestOrClosedSchema() throws Exception { + ResolveRuntimeTenantIdentityResponse valid = validResponse("NEW_GAME_ROW"); + assertRejected(valid.toBuilder().setSchemaVersion(2).build()); + assertRejected(valid.toBuilder().setTargetNamespace("other").build()); + assertRejected(valid.toBuilder().setTargetNamespace("").build()); + assertRejected( + valid.toBuilder().setCanonicalTenantId("AB426BB3-A733-43F0-9C8E-2E379CBDF7EC").build()); + assertRejected(valid.toBuilder().setRequestId("33333333-3333-4333-8333-333333333333").build()); + assertRejected( + valid.toBuilder().setCanonicalTenantId("33333333-3333-4333-8333-333333333333").build()); + assertRejected(valid.toBuilder().setSourceGameRowId(0L).build()); + assertRejected(valid.toBuilder().setSourceGameTenantKey("").build()); + assertRejected(valid.toBuilder().setProvenanceKind("ACCOUNT_ASSOCIATION").build()); + assertRejected(valid.toBuilder().setRequestId("22222222-2222-4222-8222-22222222222").build()); + assertRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + } + + @Test + void propagatesTransportFailureWithBoundedDeadline() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Game Design unavailable")); + when(stub.resolveRuntimeTenantIdentity(any())).thenThrow(unavailable); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) + .isSameAs(unavailable); + + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsPlaintextIncompleteClasspathTlsAndInvalidNamespaceBeforeChannelCreation() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + for (CommonGrpcClientProperties incomplete : + List.of( + incompleteMtlsProperties(null, "client.key", "server-ca.crt"), + incompleteMtlsProperties("client.crt", null, "server-ca.crt"), + incompleteMtlsProperties("client.crt", "client.key", null))) { + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("certificate, key, and CA"); + } + + CommonGrpcClientProperties classpath = mtlsProperties(); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + assertThatThrownBy( + () -> + new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(channelFactory); + } + + @Test + void initUsesConfiguredGameDesignTargetAndFileBackedTls(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = mtlsProperties(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + GameDesignRuntimeTenantIdentityClient client = + new GameDesignRuntimeTenantIdentityClient(endpoints, tls, channelFactory, NAMESPACE); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static void assertRejected(ResolveRuntimeTenantIdentityResponse response) + throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveRuntimeTenantIdentity(any())).thenReturn(response); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class); + } + + private static GameDesignRuntimeTenantIdentityClient newClient( + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) throws Exception { + GameDesignRuntimeTenantIdentityClient client = + newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static GameDesignRuntimeTenantIdentityClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new GameDesignRuntimeTenantIdentityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + } + + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub mockStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = + mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static ResolveRuntimeTenantIdentityResponse validResponse(String provenanceKind) { + return ResolveRuntimeTenantIdentityResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setSourceGameRowId(SOURCE_ROW_ID) + .setSourceGameTenantKey(SOURCE_KEY) + .setProvenanceKind(provenanceKind) + .build(); + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties 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; + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.createFile(directory.resolve("game-session-client.crt")).toString()); + tls.setPrivateKey(Files.createFile(directory.resolve("game-session-client.key")).toString()); + tls.setCaCert(Files.createFile(directory.resolve("game-design-ca.crt")).toString()); + return tls; + } + + private static CommonGrpcClientProperties incompleteMtlsProperties( + String certificate, String privateKey, String caCertificate) { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return tls; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index c91a9c9043..51f2e212c2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -4,6 +4,7 @@ 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; @@ -43,9 +44,24 @@ import org.mockito.ArgumentCaptor; class GameLogicClientTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, "0", "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, + 22L, + ACCOUNT_UUID, + "", + 123L, + "", + 1L, + "R-1021", + "", + null, + 1L, + "world", + "realm", + 17L, + "SHARED"); @Test void resolveLookForwardsGameInstanceIdIntoRoomInstance() throws Exception { @@ -321,7 +337,7 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( PickupVisibleRoomItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -345,7 +361,7 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( } @Test - void sendCommunicationMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws Exception { + void sendCommunicationForwardsCanonicalAccountUuidUnchanged() throws Exception { GameLogicClient client = newClient(); GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); @@ -355,7 +371,7 @@ void sendCommunicationMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws E setStub(client, stub); client.sendCommunication( - sessionContextWithAccountId(null), + sessionContextWithAccountId(ACCOUNT_UUID), "Sora", "R-1021", CommunicationType.SAY, @@ -363,22 +379,47 @@ void sendCommunicationMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws E null, null, null); - client.sendCommunication( - sessionContextWithAccountId("acct:opaque/legacy"), - "Sora", - "R-1021", - CommunicationType.SAY, - "hello", - null, - null, - null); - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(SendCommunicationRequest.class); - verify(stub, times(2)).sendCommunication(requestCaptor.capture()); - assertThat(requestCaptor.getAllValues()) - .extracting(SendCommunicationRequest::getAccountId) - .containsExactly("", "acct:opaque/legacy"); + verify(stub).sendCommunication(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getAccountId()).isEqualTo(ACCOUNT_UUID); + } + + @Test + void sendCommunicationRejectsInvalidAccountUuidBeforeRpc() throws Exception { + GameLogicClient client = newClient(); + GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = + mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + + for (String accountId : + new String[] { + null, + "", + "42", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), + " " + ACCOUNT_UUID + " ", + " ", + "not-a-uuid" + }) { + assertThatThrownBy( + () -> + client.sendCommunication( + sessionContextWithAccountId(accountId), + "Sora", + "R-1021", + CommunicationType.SAY, + "hello", + null, + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil Account UUID"); + } + + verify(stub, never()).sendCommunication(any(SendCommunicationRequest.class)); } @Test @@ -463,7 +504,7 @@ void dropCarriedItemForwardsRawReferenceAndSessionContextThroughGameLogic() thro DropCarriedItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -610,7 +651,7 @@ private static GameLogicClient newClient() { GameplaySessionAttestationService attestationService = mock(GameplaySessionAttestationService.class); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-1021", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "world", "realm", "17", "SHARED")) .thenReturn("attestation"); when(attestationService.issueGameplaySessionAttestation( "22", "41", null, "123", "1", "R-1021", "world", "realm", "17", "SHARED")) @@ -628,7 +669,7 @@ private static GameLogicClient newClient() { "SHARED")) .thenReturn("attestation"); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-2045", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-2045", "world", "realm", "17", "SHARED")) .thenReturn("destination-attestation"); when(attestationService.issueInternalProbeAttestation("22", "1", "R-1021")) .thenReturn("probe-attestation"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index 4b3ae791f2..517fcf43a8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -41,10 +41,13 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class LoginCommandHandlerTest { private static final String AUTH_TOKEN = "mock-jwt"; + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + private static final String OTHER_ACCOUNT_UUID = "2b23537d-c5cc-4fa8-8c0d-dc4c38c77a92"; private final GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); @@ -68,7 +71,10 @@ void setUp() { stubSessionContext(bootstrapShell(1L, 1L)); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_UUID) + .build()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); sessionRoutingNormalizationService = @@ -401,7 +407,7 @@ void credentialLoginCanReauthenticateAfterUnavailableFirstPartyContext() { ArgumentCaptor saved = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService, times(2)).save(saved.capture()); assertNull(saved.getAllValues().get(0).accountId()); - assertEquals("77", saved.getAllValues().get(1).accountId()); + assertEquals(ACCOUNT_UUID, saved.getAllValues().get(1).accountId()); assertEquals("demo@example.com", saved.getAllValues().get(1).loginName()); } @@ -432,7 +438,7 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( .thenReturn( Optional.of( new FirstPartyConnectContext( - "99", + OTHER_ACCOUNT_UUID, 22L, "demo", "production", @@ -447,12 +453,14 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( LoginCommandHandlingResult result = handler.handle("1", command, false); assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 99", joinedOutputText(result.outputs())); + assertEquals( + "Logged in as first-party account " + OTHER_ACCOUNT_UUID, + joinedOutputText(result.outputs())); verify(accountClient, never()).authenticate(anyString(), anyString()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); - assertEquals("99", context.accountId()); + assertEquals(OTHER_ACCOUNT_UUID, context.accountId()); assertEquals(1L, context.bootstrapGameInstanceId()); assertEquals(0L, context.gameInstanceId()); assertEquals(0L, context.characterId()); @@ -540,8 +548,16 @@ void bareLoginRejectsAbsentFirstPartyAccountBeforeInstanceLookup() { @Test void bareLoginRejectsOpaqueFirstPartyAccountWithoutClearingExistingOwnerAlias() { + assertBareLoginRetainsMalformedFirstPartyAccount("acct:opaque/legacy"); + } + + @Test + void bareLoginRejectsNumericFirstPartyAccountWithoutClearingExistingOwnerAlias() { + assertBareLoginRetainsMalformedFirstPartyAccount("42"); + } + + private void assertBareLoginRetainsMalformedFirstPartyAccount(String accountId) { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); - String accountId = "acct:opaque/legacy"; stubSessionContext( new SessionContext( 1L, @@ -596,7 +612,16 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi GameInstance instance = buildInstance(1L, 22L, 77L); FirstPartyConnectContext accountAContext = new FirstPartyConnectContext( - "99", 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); + OTHER_ACCOUNT_UUID, + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); AtomicBoolean accountAContextRegistered = new AtomicBoolean(true); List registryEvents = new java.util.ArrayList<>(); Mockito.doAnswer( @@ -632,23 +657,61 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi List.of("find-account-a", "find-account-a", "unregister", "find-empty"), registryEvents); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService, times(3)).save(captor.capture()); - assertEquals("99", captor.getAllValues().get(0).accountId()); - assertEquals("77", captor.getAllValues().get(1).accountId()); + assertEquals(OTHER_ACCOUNT_UUID, captor.getAllValues().get(0).accountId()); + assertEquals(ACCOUNT_UUID, captor.getAllValues().get(1).accountId()); assertEquals("demo@example.com", captor.getAllValues().get(1).loginName()); assertEquals(AUTH_TOKEN, captor.getAllValues().get(1).jwt()); assertEquals(null, captor.getAllValues().get(2).accountId()); } + @Test + void credentialLoginFailsClosedWhenFirstPartyContextIsUnreadable() { + TextCommand credentialLogin = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + when(firstPartyConnectContextRegistry.find(1L)) + .thenThrow(new SerializationException("retained connect context is unreadable")); + + LoginCommandHandlingResult result = handler.handle("1", credentialLogin, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(firstPartyConnectContextRegistry, never()).unregister(1L); + } + + @Test + void credentialLoginFailsClosedWhenFirstPartyContextHasWrongType() { + TextCommand credentialLogin = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + when(firstPartyConnectContextRegistry.find(1L)) + .thenThrow(new ClassCastException("retained connect context has the wrong type")); + + LoginCommandHandlingResult result = handler.handle("1", credentialLogin, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(firstPartyConnectContextRegistry, never()).unregister(1L); + } + @Test void staleFirstPartyRegistryCannotReplacePersistedCredentialIdentity() { SessionContext credentialIdentity = - new SessionContext(1L, 22L, "77", "demo@example.com", 0L, null, 0L, "mock-jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, "mock-jwt"); stubSessionContext(credentialIdentity); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "99", + OTHER_ACCOUNT_UUID, 22L, "demo", "production", @@ -677,7 +740,7 @@ void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, null, 0L, null, @@ -700,7 +763,8 @@ void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() LoginCommandHandlingResult result = handler.handle("1", command, false); assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 77", joinedOutputText(result.outputs())); + assertEquals( + "Logged in as first-party account " + ACCOUNT_UUID, joinedOutputText(result.outputs())); } @Test @@ -710,7 +774,7 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, null, 0L, null, @@ -746,7 +810,7 @@ void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSess new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, null, 0L, null, @@ -779,7 +843,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerTenantIsInvalid() { .thenReturn( Optional.of( new FirstPartyConnectContext( - "77", + ACCOUNT_UUID, 0L, "demo", "production", @@ -804,7 +868,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerGameInstanceIdIsInvalid() .thenReturn( Optional.of( new FirstPartyConnectContext( - "77", + ACCOUNT_UUID, 22L, "demo", "production", @@ -831,7 +895,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerWorldOrRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - "77", + ACCOUNT_UUID, 22L, " ", "production", @@ -856,7 +920,16 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - "77", 22L, "demo", " ", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"))); + ACCOUNT_UUID, + 22L, + "demo", + " ", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"))); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -866,20 +939,22 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { } @Test - void bareLoginRejectsStalePointerVersion() { + void bareLoginRejectsPointerVersionMismatch() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); stubSessionContext(staleGameplayContext(1L)); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "77", + ACCOUNT_UUID, 22L, "demo", "production", 1L, - 0L, + 2L, "scope-1", "jti-1", "req-1", @@ -889,10 +964,10 @@ void bareLoginRejectsStalePointerVersion() { LoginCommandHandlingResult result = handler.handle("1", command, false); assertFalse(result.commandResult().accepted()); - assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + assertEquals("CONNECT_SCOPE_MISMATCH", result.commandResult().errorCode()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertClearedSessionContext(captor.getValue(), 1L); + assertClearedSessionContext(captor.getValue(), 2L); } @Test @@ -914,7 +989,7 @@ void successfulLoginStoresSessionContext() { net.firedevops.firemud.gamesession.service.SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals("77", context.accountId()); + assertEquals(ACCOUNT_UUID, context.accountId()); assertEquals(0L, context.characterId()); assertEquals(0L, context.gameInstanceId()); assertNull(context.roomInstanceId()); @@ -979,7 +1054,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", @@ -1000,7 +1075,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", @@ -1023,7 +1098,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals("77", context.accountId()); + assertEquals(ACCOUNT_UUID, context.accountId()); assertEquals(88L, context.characterId()); assertEquals(1L, context.gameInstanceId()); assertEquals("R-2045", context.roomInstanceId()); @@ -1042,12 +1117,15 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_UUID) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", @@ -1074,7 +1152,7 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("99", savedContext.getValue().accountId()); + assertEquals(OTHER_ACCOUNT_UUID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1090,7 +1168,10 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_UUID) + .build()); stubSessionContext(staleGameplayContext(0L)); handler.handle("1", command, false); @@ -1103,10 +1184,10 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_ACCOUNT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals("77", clearedContext.getValue().accountId()); + assertEquals(ACCOUNT_UUID, clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("99", savedContext.getValue().accountId()); + assertEquals(OTHER_ACCOUNT_UUID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1122,12 +1203,15 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_UUID) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", @@ -1153,9 +1237,9 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { .clearGameplayBinding(existing, "LOGIN_TENANT_CHANGED"); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); - assertEquals("77", existing.accountId()); + assertEquals(ACCOUNT_UUID, existing.accountId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("77", savedContext.getValue().accountId()); + assertEquals(ACCOUNT_UUID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1171,7 +1255,10 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_UUID) + .build()); stubSessionContext(staleGameplayContext(0L)); handler.handle("1", command, false); @@ -1184,10 +1271,10 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_TENANT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals("77", clearedContext.getValue().accountId()); + assertEquals(ACCOUNT_UUID, clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("77", savedContext.getValue().accountId()); + assertEquals(ACCOUNT_UUID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1204,12 +1291,15 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_UUID) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", @@ -1235,7 +1325,7 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); inOrder.verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); - assertEquals("99", context.accountId()); + assertEquals(OTHER_ACCOUNT_UUID, context.accountId()); assertEquals("other@example.com", context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); @@ -1262,7 +1352,10 @@ void reloginAsDifferentAccountDoesNotReplaceContextWhenPresenceClearFails() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_UUID) + .build()); SessionContext existing = staleGameplayContext(1L); stubSessionContext(existing); Mockito.doThrow(new IllegalStateException("presence clear unavailable")) @@ -1299,7 +1392,7 @@ void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals("77", context.accountId()); + assertEquals(ACCOUNT_UUID, context.accountId()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); assertEquals(0L, context.gameInstanceId()); @@ -1368,7 +1461,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", @@ -1407,7 +1500,10 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_UUID) + .build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1415,7 +1511,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { assertEquals("Logged in as demo@example.com", joinedOutputText(result.outputs())); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertEquals("99", captor.getValue().accountId()); + assertEquals(OTHER_ACCOUNT_UUID, captor.getValue().accountId()); assertEquals("demo@example.com", captor.getValue().loginName()); assertEquals(77L, instance.getOwnerAccountId()); } @@ -1816,7 +1912,7 @@ private static SessionContext staleGameplayContext(long pointerVersion) { return new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", @@ -1837,7 +1933,7 @@ private static SessionContext staleGameplayContextWithoutSelector(long pointerVe return new SessionContext( 1L, 22L, - "77", + ACCOUNT_UUID, "demo@example.com", 88L, "Sora", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java new file mode 100644 index 0000000000..7612b7d612 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java @@ -0,0 +1,80 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; +import net.firedevops.firemud.gamesession.service.SessionContext; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.serializer.SerializationException; + +class FirstPartyConnectContextResolutionTest { + private static final String ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + + @Test + void unreadableRetainedContextIsInvalidAndDoesNotUsePersistedFallback() { + FirstPartyConnectContextRegistry registry = mock(FirstPartyConnectContextRegistry.class); + when(registry.find(91L)).thenThrow(new SerializationException("old record shape")); + + FirstPartyConnectContextResolution resolution = + FirstPartyConnectContextResolution.resolve(91L, persistedContext(), registry); + + assertTrue(resolution.invalid()); + assertEquals(Optional.empty(), resolution.connectContext()); + } + + @Test + void wrongTypeRetainedContextIsInvalidAndDoesNotUsePersistedFallback() { + FirstPartyConnectContextRegistry registry = mock(FirstPartyConnectContextRegistry.class); + when(registry.find(91L)).thenThrow(new ClassCastException("incompatible retained value")); + + FirstPartyConnectContextResolution resolution = + FirstPartyConnectContextResolution.resolve(91L, persistedContext(), registry); + + assertTrue(resolution.invalid()); + assertEquals(Optional.empty(), resolution.connectContext()); + } + + @Test + void absentRetainedContextUsesCompletePersistedFallback() { + FirstPartyConnectContextRegistry registry = mock(FirstPartyConnectContextRegistry.class); + when(registry.find(91L)).thenReturn(Optional.empty()); + + FirstPartyConnectContextResolution resolution = + FirstPartyConnectContextResolution.resolve(91L, persistedContext(), registry); + + assertFalse(resolution.invalid()); + assertEquals( + Optional.of( + new FirstPartyConnectContext( + ACCOUNT_ID, 22L, "demo", "production", 41L, 17L, "scope-1", null, "req-1", null)), + resolution.connectContext()); + } + + private static SessionContext persistedContext() { + return new SessionContext( + 91L, + 22L, + ACCOUNT_ID, + "first-party:91", + 0L, + null, + 0L, + null, + null, + null, + 41L, + "demo", + "production", + 17L, + null, + "scope-1", + "req-1"); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java index 100177c024..85555e8747 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java @@ -12,6 +12,8 @@ import org.junit.jupiter.api.Test; class FirstPartyConnectContextServiceTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3"; @Test void parseReadsJwtClaimsThroughInjectedUtil() { @@ -23,8 +25,8 @@ void parseReadsJwtClaimsThroughInjectedUtil() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); @@ -40,7 +42,7 @@ void parseReadsJwtClaimsThroughInjectedUtil() { assertTrue(service.parse("token").isPresent()); FirstPartyConnectContext context = service.parse("token").orElseThrow(); - assertEquals("42", context.accountId()); + assertEquals(ACCOUNT_UUID, context.accountId()); assertEquals(7L, context.tenantId()); assertEquals("demo", context.worldSlug()); assertEquals("production", context.realmSlug()); @@ -80,7 +82,7 @@ void parseRejectsMalformedAccountSubjectClaim() { } @Test - void parseRejectsZeroAccountClaim() { + void parseRejectsNumericAccountSubjectAndClaim() { FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); properties.setJwtSecret("secret"); JwtUtil jwtUtil = mock(JwtUtil.class); @@ -90,6 +92,25 @@ void parseRejectsZeroAccountClaim() { when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); when(claims.getSubject()).thenReturn("42"); + when(claims.get("accountId")).thenReturn("42"); + + FirstPartyConnectContextService service = + new FirstPartyConnectContextService(properties, jwtUtil); + + assertTrue(service.parse("token").isEmpty()); + } + + @Test + void parseRejectsZeroAccountClaim() { + FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); + properties.setJwtSecret("secret"); + JwtUtil jwtUtil = mock(JwtUtil.class); + @SuppressWarnings("unchecked") + Jws jws = mock(Jws.class); + Claims claims = mock(Claims.class); + when(jwtUtil.parseToken("token")).thenReturn(jws); + when(jws.getPayload()).thenReturn(claims); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); when(claims.get("accountId")).thenReturn("0"); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); @@ -117,8 +138,8 @@ void parseRejectsAccountSubjectMismatch() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("41"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(OTHER_ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); @@ -145,8 +166,8 @@ void parseRejectsMalformedTenantClaim() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn("not-a-number"); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); @@ -173,8 +194,8 @@ void parseRejectsMissingTenantClaim() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(null); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); @@ -201,8 +222,8 @@ void parseRejectsMissingWorldSlugClaim() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn(""); when(claims.get("realmSlug")).thenReturn("production"); @@ -229,8 +250,8 @@ void parseRejectsMissingRealmSlugClaim() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn(""); @@ -257,8 +278,8 @@ void parseRejectsMissingConnectScopeIdClaim() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); @@ -285,8 +306,8 @@ void parseRejectsMissingConnectRequestIdClaim() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); @@ -313,8 +334,8 @@ void parseRejectsMissingPointerVersionClaim() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); @@ -341,8 +362,8 @@ void parseRejectsMissingPointerVersionClaimWhenNotPresent() { Claims claims = mock(Claims.class); when(jwtUtil.parseToken("token")).thenReturn(jws); when(jws.getPayload()).thenReturn(claims); - when(claims.getSubject()).thenReturn("42"); - when(claims.get("accountId")).thenReturn("42"); + when(claims.getSubject()).thenReturn(ACCOUNT_UUID); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID); when(claims.get("tenantId")).thenReturn(7L); when(claims.get("worldSlug")).thenReturn("demo"); when(claims.get("realmSlug")).thenReturn("production"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java index 638e0b2623..f96e5f5108 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java @@ -17,6 +17,7 @@ import org.mockito.Mockito; class SessionAuthenticationServiceTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -45,7 +46,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -66,13 +67,13 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals("123", resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_UUID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); assertEquals(0L, resolved.orElseThrow().characterId()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); - assertEquals("123", captor.getValue().accountId()); + assertEquals(ACCOUNT_UUID, captor.getValue().accountId()); assertEquals(0L, captor.getValue().gameInstanceId()); assertEquals(0L, captor.getValue().pointerVersion()); } @@ -81,7 +82,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { SessionContext incomplete = new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); + 41L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(incomplete)); when(sessionContextService.findByTenantAndSessionId(22L, 41L)) .thenReturn(Optional.of(incomplete)); @@ -89,7 +90,7 @@ void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals("123", resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_UUID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService) @@ -102,7 +103,7 @@ void resolveSessionContextClearsGameplayBindingWhenRuntimeTargetAuthorityIsAmbig new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -139,7 +140,7 @@ void resolveSessionContextKeepsCurrentGameplayBindingWhenPointerMatches() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -172,7 +173,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -192,7 +193,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { Optional resolved = service.resolveUnverifiedSessionContext(22L, 41L); assertTrue(resolved.isPresent()); - assertEquals("123", resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_UUID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); @@ -204,7 +205,7 @@ void resolveUnverifiedSessionContextFailsClosedWhenTenantScopedSessionIsMissing( new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -260,7 +261,7 @@ void resolveByGameplayIdentityNormalizesResolvedContext() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -292,7 +293,7 @@ void resolveByGameplayNameKeepsCurrentContextWhenPointerMatches() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java index b9bc2b7024..224353aa64 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java @@ -7,20 +7,30 @@ import org.junit.jupiter.api.Test; class SessionContextTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; @Test void preservesLegacyAndSyntheticRuntimeRoomIdsVerbatim() { SessionContext legacyNumeric = - new SessionContext(1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); SessionContext legacyPrefixed = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); SessionContext legacyUppercasePrefixed = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); SessionContext syntheticProbe = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "readiness-room-1", "jwt"); + 1L, + 22L, + ACCOUNT_UUID, + "demo@example.com", + 7001L, + "Emberline", + 41L, + "readiness-room-1", + "jwt"); assertEquals("1", legacyNumeric.roomInstanceId()); assertEquals("room-1", legacyPrefixed.roomInstanceId()); @@ -34,7 +44,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectRequest() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_UUID, "first-party:123", 0L, null, @@ -60,7 +70,7 @@ void hasPartialPersistedFirstPartyConnectContextIgnoresStandardGameplaySession() new SessionContext( 1L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -85,7 +95,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_UUID, "first-party:123", 0L, null, @@ -135,12 +145,12 @@ void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity( void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { SessionContext complete = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingRoom = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayRegionBinding()); assertFalse(missingRoom.hasGameplayRegionBinding()); @@ -150,13 +160,14 @@ void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { @Test void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { SessionContext gameOnly = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 41L, null, "jwt"); SessionContext characterOnly = - new SessionContext(1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); SessionContext roomOnly = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, "R-1", "jwt"); SessionContext blank = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, null, "jwt"); assertTrue(gameOnly.hasGameplayBinding()); assertTrue(characterOnly.hasGameplayBinding()); @@ -168,12 +179,12 @@ void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { void hasGameplayIdentityRequiresPositiveGameInstanceAndCharacter() { SessionContext complete = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingGameInstance = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayIdentity()); assertFalse(missingGameInstance.hasGameplayIdentity()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java index f71d635e40..8d66a7e4d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.Instant; @@ -20,6 +22,10 @@ import org.mockito.Mockito; class AccountPresenceQueryServiceImplTest { + private static final String VIEWER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String ONLINE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000003"; + private static final String OFFLINE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000004"; + @Test void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { GameplayPresenceService presenceService = Mockito.mock(GameplayPresenceService.class); @@ -35,13 +41,16 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of("3", "4")) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) + && ids.size() == 2))) .thenReturn( java.util.Map.of( - "4", + OFFLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "4", + OFFLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -52,10 +61,13 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of("3", "4")) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) + && ids.size() == 2))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -65,7 +77,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -78,10 +90,12 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3", "4")); + var result = + service.queryAccountPresence( + 1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)); assertEquals(2, result.size()); - assertEquals("3", result.get(0).accountId()); + assertEquals(ONLINE_ACCOUNT_ID, result.get(0).accountId()); assertEquals(true, result.get(0).online()); assertEquals(2L, result.get(0).gameInstanceId()); assertEquals("sandbox", result.get(0).worldSlug()); @@ -94,7 +108,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { net.firedevops.firemud.gamesession.service.GameplayPresenceActivityState.EXPLICIT_AFK, result.get(0).activityState()); assertEquals(null, result.get(0).recentDisposition()); - assertEquals("4", result.get(1).accountId()); + assertEquals(OFFLINE_ACCOUNT_ID, result.get(1).accountId()); assertEquals(false, result.get(1).online()); assertEquals(2L, result.get(1).gameInstanceId()); assertEquals("sandbox", result.get(1).worldSlug()); @@ -122,13 +136,13 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 9L, "SHARED", "sandbox", @@ -139,10 +153,10 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -152,7 +166,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { "sandbox", "production", 18L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -165,7 +179,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -188,13 +202,13 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -205,10 +219,10 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -218,7 +232,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin "sandbox", "production", 0L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -231,7 +245,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -257,13 +271,13 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -274,10 +288,10 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -287,7 +301,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna " ", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -300,7 +314,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -326,15 +340,15 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -344,7 +358,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 18L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -360,7 +374,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 100L, "Ben", GameplayPresenceRole.PLAYER, @@ -373,7 +387,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -397,13 +411,13 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -414,10 +428,10 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -427,7 +441,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -441,7 +455,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L), pointer("sandbox", "Builder Sandbox", "preview", "Preview Realm", 1L, 2L, 18L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -467,13 +481,13 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -484,10 +498,10 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -497,7 +511,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -522,7 +536,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "", "ALLOW_NEW"))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -548,15 +562,15 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -566,7 +580,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { "Sandbox", "Production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -579,7 +593,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -604,13 +618,13 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("4") && ids.size() == 1))) + ids -> ids != null && ids.contains(OFFLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "4", + OFFLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "4", + OFFLINE_ACCOUNT_ID, 2L, "SHARED", "Sandbox", @@ -621,14 +635,14 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("4") && ids.size() == 1))) + ids -> ids != null && ids.contains(OFFLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn(Map.of()); when(pointerAuthorityService.listByRuntimeTarget(1L, 2L)) .thenReturn( List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("4")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(OFFLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -638,6 +652,38 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { assertEquals("Live Realm", result.get(0).realmDisplayName()); } + @Test + void queryAccountPresenceRejectsNonCanonicalAccountIdsBeforeReadingPresence() { + GameplayPresenceService presenceService = Mockito.mock(GameplayPresenceService.class); + AccountRecentPresenceService recentPresenceService = + Mockito.mock(AccountRecentPresenceService.class); + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + AccountPresenceQueryServiceImpl service = + new AccountPresenceQueryServiceImpl( + presenceService, + new GameplayPresenceActivityResolver(new PresenceProperties()), + recentPresenceService, + pointerAuthorityService); + + for (String invalidAccountId : + List.of( + "3", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + ONLINE_ACCOUNT_ID, + ONLINE_ACCOUNT_ID + " ")) { + assertThrows( + IllegalArgumentException.class, + () -> service.queryAccountPresence(1L, invalidAccountId, List.of(ONLINE_ACCOUNT_ID))); + assertThrows( + IllegalArgumentException.class, + () -> service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(invalidAccountId))); + } + + verifyNoInteractions(presenceService, recentPresenceService, pointerAuthorityService); + } + private static GameplayAdmissionPointerSnapshot pointer( String worldSlug, String worldDisplayName, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java index 445226cea6..c54efdcfa5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; @@ -34,6 +35,8 @@ @ExtendWith(OutputCaptureExtension.class) class CommandServiceImplTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + @Test void rateLimitFailurePropagatesError() { TickService tickService = Mockito.mock(TickService.class); @@ -181,8 +184,15 @@ void enqueueRejectsNegativeSessionIdBeforeSessionLookup() { } @Test - void enqueueRejectsUnsupportedAccountIdBeforePersistenceOrQueueing() { - for (String accountId : List.of("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "0", "-1")) { + void enqueueRejectsNonCanonicalAccountUuidBeforePersistenceOrQueueing() { + for (String accountId : + List.of( + "42", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), + " " + ACCOUNT_UUID + " ", + "not-a-uuid", + " ")) { TickService tickService = Mockito.mock(TickService.class); SessionRateLimiter rateLimiter = Mockito.mock(SessionRateLimiter.class); GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); @@ -207,11 +217,7 @@ void enqueueRejectsUnsupportedAccountIdBeforePersistenceOrQueueing() { assertTrue(result.hasError()); assertEquals("INVALID_ARGUMENT", result.errorCode()); - assertEquals( - accountId.equals("0") || accountId.equals("-1") - ? "accountId must be positive" - : "accountId must be numeric", - result.errorMessage()); + assertEquals("accountId must be a canonical non-nil UUID", result.errorMessage()); verify(commandRepository, never()).save(Mockito.any()); verify(tickService, never()) .enqueueCommand( @@ -355,7 +361,8 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); CommandServiceImpl service = @@ -374,8 +381,8 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { org.mockito.ArgumentCaptor commandCaptor = org.mockito.ArgumentCaptor.forClass(GameplayCommand.class); verify(commandRepository).save(commandCaptor.capture()); - assertEquals(3L, commandCaptor.getValue().getAccountId()); - assertNull(commandCaptor.getValue().getAccountUuid()); + assertEquals(UUID.fromString(ACCOUNT_UUID), commandCaptor.getValue().getAccountUuid()); + assertNull(commandCaptor.getValue().getAccountId()); verify(tickService, times(1)).enqueueCommand(9L, 99L, result.commandId(), "look", false); verify(scriptEventPublisher, times(1)) .publishCommandEvent(Mockito.any(SessionContext.class), Mockito.any(GameplayCommand.class)); @@ -431,7 +438,7 @@ void gameplayCommandsPersistCurrentRuntimeScopeForDurableCommandEventFallback() new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -484,7 +491,8 @@ void gameplayCommandFailsBeforePersistenceWhenRuntimeOwnershipIsNotEstablished() Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "region-99", "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenReturn(Optional.empty()); CommandServiceImpl service = @@ -526,7 +534,8 @@ void gameplayCommandFailsClosedWhenRuntimeOwnershipReadFails() { Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "region-99", "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenThrow(new IllegalStateException("runtime ownership unavailable")); CommandServiceImpl service = @@ -617,7 +626,21 @@ void staleNormalizedGameplaySessionFailsClosedWithoutBootstrapRoutingBundle() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SessionContext cleared = new SessionContext( - 17L, 9L, "3", "demo", 0L, null, 0L, null, "jwt", null, 99L, null, null, 0L, null); + 17L, + 9L, + ACCOUNT_UUID, + "demo", + 0L, + null, + 0L, + null, + "jwt", + null, + 99L, + null, + null, + 0L, + null); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn(Optional.of(cleared)); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); @@ -660,7 +683,8 @@ void enqueueAddsGameplayLoggingContextWhenSessionIsBound() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doAnswer( invocation -> { @@ -710,7 +734,8 @@ void loginCommandsAreRedactedFromLogs(CapturedOutput output) { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); CommandServiceImpl service = newCommandService( @@ -749,7 +774,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 0L, null, @@ -813,7 +838,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromUnambiguousRuntimeAuthority GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_UUID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -865,7 +890,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenRuntimeAuthorityIsAmbiguous() GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_UUID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -930,7 +955,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenSingularRuntimeAuthorityIsInco GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_UUID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -987,7 +1012,7 @@ void gameplayCommandRepairsPartialSessionRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1054,8 +1079,21 @@ void gameplayCommandRepairsPointerOnlySessionRoutingMetadataFromRuntimeAuthority .thenReturn( Optional.of( new SessionContext( - 17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt", null, 99L, null, null, - 17L, "SHARED"))); + 17L, + 9L, + ACCOUNT_UUID, + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt", + null, + 99L, + null, + null, + 17L, + "SHARED"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -1112,7 +1150,7 @@ void gameplayCommandUsesActiveGameplayRuntimeAuthorityBeforeBootstrapRuntime() { new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1184,7 +1222,7 @@ void gameplayCommandRepairsStaleCompleteSessionRoutingMetadataFromCurrentAuthori new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 0L, null, @@ -1253,7 +1291,7 @@ void gameplayCommandDropsStaleCompleteSessionRoutingMetadataWhenCurrentAuthority new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 0L, null, @@ -1308,7 +1346,7 @@ void gameplayCommandDropsPartialSessionRoutingMetadataWhenAuthorityCannotRepairI new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1363,7 +1401,7 @@ void gameplayCommandDropsSessionRoutingMetadataWhenCurrentSelectorPointerIsIncom new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1428,7 +1466,8 @@ void queueValidationFailureMarksPersistedCommandFailed() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doThrow(new IllegalArgumentException("bad command")) .when(tickService) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 1987b15f4f..5ad3b36c1a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -64,6 +64,9 @@ import org.mockito.Mockito; class GameSessionGrpcServiceTest { + private static final String VIEWER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String TARGET_ACCOUNT_ID = "00000000-0000-4000-8000-000000000007"; + @AfterEach void tearDown() { SessionContext.clear(); @@ -94,6 +97,28 @@ private static GameSessionGrpcService newService( ipConnectionLimiter); } + private static QueryAccountPresenceResponse captureAccountPresenceResponse( + GameSessionGrpcService service, QueryAccountPresenceRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.queryAccountPresence( + request, + new StreamObserver<>() { + @Override + public void onNext(QueryAccountPresenceResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return ref.get(); + } + private static GameSessionGrpcService newService( PingService pingService, GameInstanceService gameInstanceService, @@ -247,12 +272,14 @@ void queryAccountPresenceReturnsMappedSnapshots() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); - Mockito.when(accountPresenceQueryService.queryAccountPresence(1L, "42", List.of("7"))) + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); + Mockito.when( + accountPresenceQueryService.queryAccountPresence( + 1L, VIEWER_ACCOUNT_ID, List.of(TARGET_ACCOUNT_ID))) .thenReturn( List.of( new AccountPresenceSnapshot( - "7", + TARGET_ACCOUNT_ID, true, 9L, "ISOLATED", @@ -279,48 +306,35 @@ void queryAccountPresenceReturnsMappedSnapshots() { meterRegistry, ipLimiter); - AtomicReference ref = new AtomicReference<>(); - service.queryAccountPresence( - QueryAccountPresenceRequest.newBuilder() - .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("7") - .build(), - new StreamObserver<>() { - @Override - public void onNext(QueryAccountPresenceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals(1, ref.get().getPresencesCount()); - assertEquals("7", ref.get().getPresences(0).getAccountId()); - assertEquals(true, ref.get().getPresences(0).getOnline()); - assertEquals("demo", ref.get().getPresences(0).getWorldSlug()); - assertEquals("Demo World", ref.get().getPresences(0).getWorldDisplayName()); - assertEquals(17L, ref.get().getPresences(0).getPointerVersion()); - assertEquals("production", ref.get().getPresences(0).getRealmSlug()); - assertEquals("Live Realm", ref.get().getPresences(0).getRealmDisplayName()); - assertEquals("Ben", ref.get().getPresences(0).getCharacterName()); + QueryAccountPresenceResponse response = + captureAccountPresenceResponse( + service, + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(VIEWER_ACCOUNT_ID) + .addAccountIds(TARGET_ACCOUNT_ID) + .build()); + + assertEquals(1, response.getPresencesCount()); + assertEquals(TARGET_ACCOUNT_ID, response.getPresences(0).getAccountId()); + assertEquals(true, response.getPresences(0).getOnline()); + assertEquals("demo", response.getPresences(0).getWorldSlug()); + assertEquals("Demo World", response.getPresences(0).getWorldDisplayName()); + assertEquals(17L, response.getPresences(0).getPointerVersion()); + assertEquals("production", response.getPresences(0).getRealmSlug()); + assertEquals("Live Realm", response.getPresences(0).getRealmDisplayName()); + assertEquals("Ben", response.getPresences(0).getCharacterName()); assertEquals( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli(), - ref.get().getPresences(0).getLastSeenAtMs()); + response.getPresences(0).getLastSeenAtMs()); assertEquals( net.firedevops.firemud.gamesession.v1.AccountRecentPresenceDisposition .ACCOUNT_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS, - ref.get().getPresences(0).getRecentDisposition()); + response.getPresences(0).getRecentDisposition()); } @Test - void queryAccountPresenceRejectsMalformedAccountId() { + void queryAccountPresenceRejectsMalformedAndLegacyAccountIdsBeforeCallingPresenceService() { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -331,7 +345,7 @@ void queryAccountPresenceRejectsMalformedAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -344,35 +358,30 @@ void queryAccountPresenceRejectsMalformedAccountId() { meterRegistry, ipLimiter); - AtomicReference ref = new AtomicReference<>(); - service.queryAccountPresence( - QueryAccountPresenceRequest.newBuilder() - .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("abc") - .build(), - new StreamObserver<>() { - @Override - public void onNext(QueryAccountPresenceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a number", ref.get().getError().getMessage()); + for (String invalidAccountId : + List.of( + "abc", + "42", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + TARGET_ACCOUNT_ID)) { + QueryAccountPresenceResponse response = + captureAccountPresenceResponse( + service, + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(VIEWER_ACCOUNT_ID) + .addAccountIds(invalidAccountId) + .build()); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals( + "accountId must be a canonical non-nil Account UUID", response.getError().getMessage()); + } Mockito.verifyNoInteractions(accountPresenceQueryService); } @Test - void queryAccountPresenceRejectsZeroAccountId() { + void queryAccountPresenceRejectsMalformedViewerAccountIdsBeforeCallingPresenceService() { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -383,7 +392,7 @@ void queryAccountPresenceRejectsZeroAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -396,30 +405,25 @@ void queryAccountPresenceRejectsZeroAccountId() { meterRegistry, ipLimiter); - AtomicReference ref = new AtomicReference<>(); - service.queryAccountPresence( - QueryAccountPresenceRequest.newBuilder() - .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("0") - .build(), - new StreamObserver<>() { - @Override - public void onNext(QueryAccountPresenceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + for (String invalidViewerAccountId : + List.of( + "42", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + VIEWER_ACCOUNT_ID)) { + QueryAccountPresenceResponse response = + captureAccountPresenceResponse( + service, + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(invalidViewerAccountId) + .addAccountIds(TARGET_ACCOUNT_ID) + .build()); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals( + "viewerAccountId must be a canonical non-nil Account UUID", + response.getError().getMessage()); + } Mockito.verifyNoInteractions(accountPresenceQueryService); } @@ -435,7 +439,7 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -449,9 +453,11 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { ipLimiter); QueryAccountPresenceRequest.Builder request = - QueryAccountPresenceRequest.newBuilder().setTenantId("1").setViewerAccountId("42"); + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(VIEWER_ACCOUNT_ID); for (int index = 0; index < 101; index++) { - request.addAccountIds(index == 100 ? "not-a-number" : Long.toString(index + 1L)); + request.addAccountIds(index == 100 ? "not-a-number" : TARGET_ACCOUNT_ID); } AtomicReference ref = new AtomicReference<>(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java index b8ec61c099..fdde518dea 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.Duration; @@ -34,6 +35,7 @@ import org.springframework.data.redis.serializer.SerializationException; class RedisAccountRecentPresenceServiceTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000123"; @Test void recordDisconnectPersistsRoutingBundleFromLivePresence() { @@ -54,7 +56,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -76,7 +78,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { "demo", "production", 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -101,15 +103,18 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); - verify(redisTemplate).watch("accountrecentpresence:22:123"); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); + verify(redisTemplate).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate).multi(); verify(redisTemplate).exec(); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); assertEquals(22L, state.tenantId()); - assertEquals("123", state.accountId()); + assertEquals(ACCOUNT_ID, state.accountId()); assertEquals(101L, state.gameInstanceId()); assertEquals("demo", state.worldSlug()); assertEquals("production", state.realmSlug()); @@ -137,7 +142,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -159,7 +164,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() "demo", "production", 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -185,7 +190,10 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -214,7 +222,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -236,7 +244,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe "demo", "production", 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -262,7 +270,10 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -291,7 +302,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -313,7 +324,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() "demo", null, 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -339,7 +350,10 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -358,7 +372,7 @@ void unreadableRecentPresenceFailsClosedWithoutOverwritingRetainedEvidence() { ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); stubTransactionExecution(redisTemplate); - when(valueOperations.get("accountrecentpresence:22:123")) + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenThrow(new SerializationException("old AccountRecentPresenceState record shape")); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); @@ -373,9 +387,9 @@ void unreadableRecentPresenceFailsClosedWithoutOverwritingRetainedEvidence() { presenceProperties, () -> 1_700_000_000_000L); SessionContext context = - new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + new SessionContext(41L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "jwt"); - assertEquals(Map.of(), service.findByAccountIds(22L, List.of("123"))); + assertEquals(Map.of(), service.findByAccountIds(22L, List.of(ACCOUNT_ID))); service.recordConnected(context); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); @@ -384,6 +398,96 @@ void unreadableRecentPresenceFailsClosedWithoutOverwritingRetainedEvidence() { verify(redisTemplate, never()).delete(anyString()); } + @Test + void findByAccountIdsDoesNotExposeMalformedRetainedAccountIdentity() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) + .thenReturn( + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS)); + + RedisAccountRecentPresenceService service = + newService(redisTemplate, Mockito.mock(GameplayPresenceService.class)); + + assertEquals(Map.of(), service.findByAccountIds(22L, List.of(ACCOUNT_ID))); + verify(redisTemplate, never()).delete(anyString()); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + } + + @Test + void findByAccountIdsReturnsExactCanonicalAccountState() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + AccountRecentPresenceState state = + new AccountRecentPresenceState( + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn(state); + RedisAccountRecentPresenceService service = + newService(redisTemplate, Mockito.mock(GameplayPresenceService.class)); + + assertEquals(Map.of(ACCOUNT_ID, state), service.findByAccountIds(22L, List.of(ACCOUNT_ID))); + } + + @Test + void recordConnectedPreservesReadableRetainedStateWithMalformedAccountIdentity() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) + .thenReturn( + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS)); + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + + newService(redisTemplate, gameplayPresenceService).recordConnected(testContext()); + + verify(redisTemplate).watch("accountrecentpresence:22:" + ACCOUNT_ID); + verify(redisTemplate).unwatch(); + verify(redisTemplate, never()).multi(); + verify(redisTemplate, never()).exec(); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(redisTemplate, never()).delete(anyString()); + } + + @Test + void malformedCallerAccountIdsDoNotReadOrWriteRecentPresence() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + RedisAccountRecentPresenceService service = newService(redisTemplate, gameplayPresenceService); + + for (String accountId : + List.of( + "123", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + ACCOUNT_ID, + ACCOUNT_ID + " ")) { + assertEquals(Map.of(), service.findByAccountIds(22L, List.of(accountId))); + service.recordConnected( + new SessionContext(41L, 22L, accountId, "demo@example.com", 0L, null, 0L, null, "jwt")); + } + + verify(valueOperations, never()).get(anyString()); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(redisTemplate, never()).watch(anyString()); + verifyNoInteractions(gameplayPresenceService); + } + @Test void recordConnectedRetriesAfterWatchedValueChanges() { @SuppressWarnings("unchecked") @@ -394,11 +498,11 @@ void recordConnectedRetriesAfterWatchedValueChanges() { stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); AccountRecentPresenceState concurrentReplacement = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_500L, AccountRecentPresenceDisposition.LOGOUT); - when(valueOperations.get("accountrecentpresence:22:123")) + 22L, ACCOUNT_ID, 1_699_999_999_500L, AccountRecentPresenceDisposition.LOGOUT); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenReturn(retained, concurrentReplacement); when(redisTemplate.exec()).thenReturn(null, List.of("OK")); @@ -408,12 +512,12 @@ void recordConnectedRetriesAfterWatchedValueChanges() { service.recordConnected(testContext()); - verify(redisTemplate, times(2)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(2)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate, times(2)).multi(); verify(redisTemplate, times(2)).exec(); - verify(valueOperations, times(2)).get("accountrecentpresence:22:123"); + verify(valueOperations, times(2)).get("accountrecentpresence:22:" + ACCOUNT_ID); verify(valueOperations, times(2)) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); } @Test @@ -426,8 +530,8 @@ void recordConnectedStopsAfterEightWatchedConflictsWithoutCommittingTheProjectio stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); - when(valueOperations.get("accountrecentpresence:22:123")).thenReturn(retained); + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn(retained); when(redisTemplate.exec()).thenReturn(null); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); @@ -436,14 +540,14 @@ void recordConnectedStopsAfterEightWatchedConflictsWithoutCommittingTheProjectio service.recordConnected(testContext()); - verify(redisTemplate, times(8)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(8)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate, times(8)).multi(); verify(redisTemplate, times(8)).exec(); - verify(valueOperations, times(8)).get("accountrecentpresence:22:123"); + verify(valueOperations, times(8)).get("accountrecentpresence:22:" + ACCOUNT_ID); // Each null EXEC represents a WATCH conflict, so none of the queued replacement writes // committed. verify(valueOperations, times(8)) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); verify(redisTemplate, never()).delete(anyString()); } @@ -457,8 +561,8 @@ void recordActivityStopsAfterEightWatchedConflictsWithoutCommittingTheProjection stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); - when(valueOperations.get("accountrecentpresence:22:123")).thenReturn(retained); + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn(retained); when(redisTemplate.exec()).thenReturn(null); SessionRoutingNormalizationService sessionRoutingNormalizationService = @@ -472,14 +576,14 @@ void recordActivityStopsAfterEightWatchedConflictsWithoutCommittingTheProjection service.recordActivity(41L); - verify(redisTemplate, times(8)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(8)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate, times(8)).multi(); verify(redisTemplate, times(8)).exec(); - verify(valueOperations, times(8)).get("accountrecentpresence:22:123"); + verify(valueOperations, times(8)).get("accountrecentpresence:22:" + ACCOUNT_ID); // Each null EXEC represents a WATCH conflict, so none of the queued replacement writes // committed. verify(valueOperations, times(8)) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); verify(redisTemplate, never()).delete(anyString()); } @@ -493,8 +597,8 @@ void recordConnectedDoesNotRetryWriteWhenConflictRevealsUnreadableReplacement() stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); - when(valueOperations.get("accountrecentpresence:22:123")) + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenReturn(retained) .thenThrow(new SerializationException("concurrent replacement has old record shape")); when(redisTemplate.exec()).thenReturn(null); @@ -505,13 +609,13 @@ void recordConnectedDoesNotRetryWriteWhenConflictRevealsUnreadableReplacement() service.recordConnected(testContext()); - verify(redisTemplate, times(2)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(2)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate).multi(); verify(redisTemplate).exec(); verify(redisTemplate).unwatch(); // The first queued SET was rejected by EXEC; the unreadable replacement prevents a retry SET. verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); } @Test @@ -522,7 +626,7 @@ void recordConnectedPreservesTypeMismatchedRetainedValue() { ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); stubTransactionExecution(redisTemplate); - when(valueOperations.get("accountrecentpresence:22:123")).thenReturn("legacy value"); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn("legacy value"); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); @@ -530,7 +634,7 @@ void recordConnectedPreservesTypeMismatchedRetainedValue() { service.recordConnected(testContext()); - verify(redisTemplate).watch("accountrecentpresence:22:123"); + verify(redisTemplate).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate).unwatch(); verify(redisTemplate, never()).multi(); verify(redisTemplate, never()).exec(); @@ -546,7 +650,7 @@ void recordConnectedPropagatesRedisReadOutage() { ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); stubTransactionExecution(redisTemplate); - when(valueOperations.get("accountrecentpresence:22:123")) + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenThrow(new IllegalStateException("Redis unavailable")); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); @@ -582,7 +686,7 @@ private static RedisAccountRecentPresenceService newService( } private static SessionContext testContext() { - return new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + return new SessionContext(41L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "jwt"); } @SuppressWarnings("unchecked") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java index 8656e71570..a256ed2b68 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java @@ -25,6 +25,7 @@ @SuppressWarnings("unchecked") class RedisFirstPartyConnectContextRegistryTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; private final ConcurrentMap store = new ConcurrentHashMap<>(); private final RedisTemplate redisTemplate = mock(RedisTemplate.class); private final ValueOperations valueOperations = mock(ValueOperations.class); @@ -59,7 +60,16 @@ void setUp() { void registerStoresContextWithShortTtl() { FirstPartyConnectContext context = new FirstPartyConnectContext( - "77", 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + ACCOUNT_UUID, + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); registry.register(91L, context); @@ -76,7 +86,16 @@ void registerStoresContextWithShortTtl() { void unregisterRemovesStoredContext() { FirstPartyConnectContext context = new FirstPartyConnectContext( - "77", 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + ACCOUNT_UUID, + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); registry.register(91L, context); registry.unregister(91L); @@ -90,7 +109,7 @@ void unreadableRetainedContextFailsClosedWithoutDeletingOrOverwritingEvidence() String key = "sessionctx:first-party:91:connect-context"; when(valueOperations.get(key)).thenThrow(new SerializationException("old record shape")); - assertEquals(Optional.empty(), registry.find(91L)); + assertThrows(SerializationException.class, () -> registry.find(91L)); assertThrows( IllegalStateException.class, @@ -98,7 +117,7 @@ void unreadableRetainedContextFailsClosedWithoutDeletingOrOverwritingEvidence() registry.register( 91L, new FirstPartyConnectContext( - "77", + ACCOUNT_UUID, 22L, "demo", "production", @@ -120,7 +139,7 @@ void wrongRetainedValueFailsClosedWithoutOverwritingEvidence() { Object retainedEvidence = "serialized record from an incompatible shape"; store.put(key, retainedEvidence); - assertEquals(Optional.empty(), registry.find(91L)); + assertThrows(ClassCastException.class, () -> registry.find(91L)); assertThrows( IllegalStateException.class, @@ -128,7 +147,7 @@ void wrongRetainedValueFailsClosedWithoutOverwritingEvidence() { registry.register( 91L, new FirstPartyConnectContext( - "77", + ACCOUNT_UUID, 22L, "demo", "production", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 424f99490f..b13b383af4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -27,6 +27,9 @@ @SuppressWarnings("unchecked") class RedisGameplayPresenceServiceTest { + private static final String GOD_ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; + private static final String PLAYER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String OTHER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000003"; private static final Duration TTL = Duration.ofMillis(1000L); private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); @@ -46,7 +49,8 @@ void setUp() { @Test void registerConnectedStoresPresenceAndIndexesByGameInstance() { SessionContext context = - new SessionContext(1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", null); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", null); service.registerConnected(context); @@ -61,16 +65,37 @@ void registerConnectedStoresPresenceAndIndexesByGameInstance() { .equals("Ben")), org.mockito.Mockito.eq(TTL)); verify(setOperations).add("gameplaypresence:22:7:sessions", "1"); - verify(setOperations).add("gameplaypresence:22:account:102:sessions", "1"); + verify(setOperations) + .add("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", "1"); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", TTL); + } + + @Test + void registerAndQueryRejectNonCanonicalAccountIdsWithoutPresenceMutation() { + for (String accountId : + List.of( + "102", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + PLAYER_ACCOUNT_ID, + PLAYER_ACCOUNT_ID + " ")) { + service.registerConnected( + new SessionContext( + 1L, 22L, accountId, "player@example.com", 202L, "Ben", 7L, "R-1", null)); + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(accountId))); + } + + verifyNoPresenceMutation(); + Mockito.verifyNoInteractions(setOperations, valueOperations); } @Test void registerConnectedClassifiesInvalidJwtAsPlayer() { SessionContext context = new SessionContext( - 1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); + 1L, 22L, PLAYER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); service.registerConnected(context); @@ -90,16 +115,17 @@ void registerConnectedClassifiesInvalidJwtAsPlayer() { void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { String godJwt = jwtUtil.generateToken( - "1", + GOD_ACCOUNT_ID, Map.of( "accountId", - "1", + GOD_ACCOUNT_ID, "globalRoles", List.of("platformAdmin"), "scopedRoles", Map.of())); SessionContext godContext = - new SessionContext(1L, 22L, "1", "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); + new SessionContext( + 1L, 22L, GOD_ACCOUNT_ID, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); service.registerConnected(godContext); when(setOperations.members("gameplaypresence:22:7:sessions")) @@ -112,7 +138,7 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { 7L, "demo", "production", - "1", + GOD_ACCOUNT_ID, 101L, "Aster", GameplayPresenceRole.GOD, @@ -142,7 +168,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { 7L, "demo", "production", - "1", + GOD_ACCOUNT_ID, 101L, "Aster", GameplayPresenceRole.GOD, @@ -168,7 +194,7 @@ void removeBySessionIdRemovesValueAndSetMembership() { 7L, "demo", "production", - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -181,7 +207,8 @@ void removeBySessionIdRemovesValueAndSetMembership() { verify(redisTemplate).delete("gameplaypresence:session:3"); verify(setOperations).remove("gameplaypresence:22:7:sessions", "3"); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "3"); + verify(setOperations) + .remove("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", "3"); } @Test @@ -194,7 +221,7 @@ void findConnectedBySessionIdReadsPresenceRecordDirectly() { 7L, "demo", "production", - "2", + OTHER_ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -221,7 +248,7 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest 7L, "demo", "production", - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -249,7 +276,8 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest == null), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", TTL); } @Test @@ -264,7 +292,7 @@ void setExplicitAfkRefreshesPresenceRecord() { 7L, "demo", "production", - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -289,12 +317,13 @@ void setExplicitAfkRefreshesPresenceRecord() { .explicitAfkSinceEpochMs())), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", TTL); } @Test void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("3", "4"))); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( @@ -306,7 +335,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -324,7 +353,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -333,18 +362,74 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of("102")); + var result = service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID)); assertEquals(1, result.size()); - assertEquals(2, result.get("102").size()); - assertEquals(4L, result.get("102").get(0).sessionId()); - assertEquals(3L, result.get("102").get(1).sessionId()); + assertEquals(2, result.get(PLAYER_ACCOUNT_ID).size()); + assertEquals(4L, result.get(PLAYER_ACCOUNT_ID).get(0).sessionId()); + assertEquals(3L, result.get(PLAYER_ACCOUNT_ID).get(1).sessionId()); } @Test - void listConnectedByAccountIdsUsesOpaqueAccountTextForIndexAndResultKey() { - String accountId = "account-uuid-opaque-v1"; - String accountIndexKey = "gameplaypresence:22:account:account-uuid-opaque-v1:sessions"; + void listConnectedByAccountIdsDoesNotAdmitAnotherAccountPresence() { + String accountIndexKey = "gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions"; + when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenReturn( + new net.firedevops.firemud.gamesession.service.GameplayPresence( + 5L, + 22L, + 7L, + "SHARED", + "demo", + "production", + 17L, + OTHER_ACCOUNT_ID, + 202L, + "Ben", + GameplayPresenceRole.PLAYER, + 90L, + null, + 110L, + 120L)); + + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID))); + + verify(setOperations).remove(accountIndexKey, "5"); + } + + @Test + void listConnectedByAccountIdsRetainsReadableLegacyNumericAccountCarrier() { + String accountIndexKey = "gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions"; + when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenReturn( + new net.firedevops.firemud.gamesession.service.GameplayPresence( + 5L, + 22L, + 7L, + "SHARED", + "demo", + "production", + 17L, + "102", + 202L, + "Ben", + GameplayPresenceRole.PLAYER, + 90L, + null, + 110L, + 120L)); + + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID))); + + verify(setOperations, Mockito.never()).remove(accountIndexKey, "5"); + } + + @Test + void listConnectedByAccountIdsUsesCanonicalAccountUuidForIndexAndResultKey() { + String accountId = OTHER_ACCOUNT_ID; + String accountIndexKey = "gameplaypresence:22:account:" + accountId + ":sessions"; String presenceKey = "gameplaypresence:session:9"; var presence = new net.firedevops.firemud.gamesession.service.GameplayPresence( @@ -375,7 +460,7 @@ void listConnectedByAccountIdsUsesOpaqueAccountTextForIndexAndResultKey() { @Test void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("bad-session", "4"))); when(valueOperations.get("gameplaypresence:session:4")) .thenReturn( @@ -387,7 +472,7 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { "demo", "production", 17L, - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -396,23 +481,24 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of("102")); + var result = service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID)); assertEquals(1, result.size()); - assertEquals(1, result.get("102").size()); - assertEquals(4L, result.get("102").get(0).sessionId()); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "bad-session"); + assertEquals(1, result.get(PLAYER_ACCOUNT_ID).size()); + assertEquals(4L, result.get(PLAYER_ACCOUNT_ID).get(0).sessionId()); + verify(setOperations) + .remove("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", "bad-session"); } @Test void unreadablePresenceIsNotReturnedOrPrunedFromIndexesDuringFailureCleanup() { String presenceKey = "gameplaypresence:session:3"; - String accountIndexKey = "gameplaypresence:22:account:102:sessions"; + String accountIndexKey = "gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions"; when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("3"))); when(valueOperations.get(presenceKey)) .thenThrow(new SerializationException("old GameplayPresence record shape")); - assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of("102"))); + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID))); assertEquals(java.util.Optional.empty(), service.findConnectedBySessionId(3L)); assertThrows(IllegalStateException.class, () -> service.removeBySessionId(3L)); @@ -467,7 +553,8 @@ void registerConnectedRejectsUnreadableAndWrongTypePresenceBeforeWriting() { .thenThrow(new SerializationException("old GameplayPresence record shape")) .thenReturn("incompatible retained presence"); SessionContext context = - new SessionContext(3L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", null); + new SessionContext( + 3L, 22L, PLAYER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", null); assertThrows(IllegalStateException.class, () -> service.registerConnected(context)); assertThrows(IllegalStateException.class, () -> service.registerConnected(context)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 18517fb38e..741679d2a3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -24,6 +24,9 @@ @SuppressWarnings("unchecked") class RedisSessionContextServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + private static final String OTHER_ACCOUNT_UUID = "2b23537d-c5cc-4fa8-8c0d-dc4c38c77a92"; + private static final String THIRD_ACCOUNT_UUID = "f0381e18-4931-4660-9bc4-4a4f73a7ea6d"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -45,7 +48,7 @@ void setUp() { @Test void saveStoresContextInSessionAndIdentityKeys() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); service.save(context); @@ -57,8 +60,8 @@ void saveStoresContextInSessionAndIdentityKeys() { @Test void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { - SessionContext existing = new SessionContext(1L, 10L, "20", 30L, 40L, "old-jwt"); - SessionContext replacement = new SessionContext(2L, 10L, "20", 30L, 40L, "new-jwt"); + SessionContext existing = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "old-jwt"); + SessionContext replacement = new SessionContext(2L, 10L, ACCOUNT_UUID, 30L, 40L, "new-jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(existing); service.save(replacement); @@ -71,9 +74,11 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { @Test void savePreservesForeignTenantIndexesFromSessionAlias() { SessionContext incoming = - new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + new SessionContext( + 1L, 10L, ACCOUNT_UUID, "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); SessionContext foreignTenant = - new SessionContext(1L, 99L, "30", "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); + new SessionContext( + 1L, 99L, OTHER_ACCOUNT_UUID, "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(foreignTenant); service.save(incoming); @@ -92,9 +97,11 @@ void savePreservesForeignTenantIndexesFromSessionAlias() { @Test void savePreservesForeignSessionIndexesFromSessionAlias() { SessionContext incoming = - new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + new SessionContext( + 1L, 10L, ACCOUNT_UUID, "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); SessionContext foreignSession = - new SessionContext(2L, 10L, "30", "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); + new SessionContext( + 2L, 10L, OTHER_ACCOUNT_UUID, "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(foreignSession); service.save(incoming); @@ -113,12 +120,14 @@ void savePreservesForeignSessionIndexesFromSessionAlias() { @Test void saveCleansDistinctSessionAliasIndexesForSameTenantAndSession() { SessionContext incoming = - new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + new SessionContext( + 1L, 10L, ACCOUNT_UUID, "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); SessionContext existingContext = new SessionContext( - 1L, 10L, "30", "context-login", 31L, "ContextOld", 41L, "R-2", "ctx-jwt"); + 1L, 10L, OTHER_ACCOUNT_UUID, "context-login", 31L, "ContextOld", 41L, "R-2", "ctx-jwt"); SessionContext existingSessionAlias = - new SessionContext(1L, 10L, "31", "alias-login", 32L, "AliasOld", 42L, "R-3", "alias-jwt"); + new SessionContext( + 1L, 10L, THIRD_ACCOUNT_UUID, "alias-login", 32L, "AliasOld", 42L, "R-3", "alias-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(existingContext); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(existingSessionAlias); @@ -137,7 +146,7 @@ void saveCleansDistinctSessionAliasIndexesForSameTenantAndSession() { @Test void findByTenantAndSessionIdReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); Optional result = service.findByTenantAndSessionId(10L, 1L); @@ -147,7 +156,7 @@ void findByTenantAndSessionIdReturnsPersistedContext() { @Test void findByGameplayIdentityReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(context); Optional result = service.findByGameplayIdentity(10L, 40L, 30L); @@ -168,7 +177,8 @@ void unreadableRetainedContextFailsClosedAndDoesNotBlockFreshReauthentication() "unreadable retained state must stop cleanup before its evidence can be deleted"); SessionContext reauthenticated = - new SessionContext(2L, 10L, "77", "demo@example.com", 0L, null, 0L, null, "fresh-jwt"); + new SessionContext( + 2L, 10L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, null, "fresh-jwt"); service.save(reauthenticated); verify(valueOperations).set("sessionctx:10:2:context", reauthenticated, TTL); @@ -186,7 +196,9 @@ void unreadableSessionAliasIsNotOverwrittenOrDeletedWhenTenantContextIsAbsent() assertThrows(SerializationException.class, () -> service.deleteBySessionId(10L, 1L)); assertThrows( SerializationException.class, - () -> service.save(new SessionContext(1L, 10L, "77", null, 0L, null, 0L, null, null))); + () -> + service.save( + new SessionContext(1L, 10L, ACCOUNT_UUID, null, 0L, null, 0L, null, null))); verify(redisTemplate, never()).multi(); verify(redisTemplate, never()).exec(); @@ -197,7 +209,7 @@ void unreadableSessionAliasIsNotOverwrittenOrDeletedWhenTenantContextIsAbsent() @Test void deleteBySessionIdRemovesBothKeys() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); service.deleteBySessionId(10L, 1L); @@ -210,7 +222,8 @@ void deleteBySessionIdRemovesBothKeys() { @Test void deleteBySessionIdPreservesDifferentTenantAliasIndexes() { - SessionContext differentTenant = new SessionContext(1L, 99L, "30", 31L, 41L, "other-jwt"); + SessionContext differentTenant = + new SessionContext(1L, 99L, OTHER_ACCOUNT_UUID, 31L, 41L, "other-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(null); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(differentTenant); @@ -223,8 +236,9 @@ void deleteBySessionIdPreservesDifferentTenantAliasIndexes() { @Test void deleteBySessionIdPreservesDifferentSessionAliasIndexes() { - SessionContext requested = new SessionContext(1L, 10L, "20", 30L, 40L, "requested-jwt"); - SessionContext differentSession = new SessionContext(2L, 10L, "21", 31L, 41L, "other-jwt"); + SessionContext requested = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "requested-jwt"); + SessionContext differentSession = + new SessionContext(2L, 10L, OTHER_ACCOUNT_UUID, 31L, 41L, "other-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(requested); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(differentSession); @@ -239,8 +253,8 @@ void deleteBySessionIdPreservesDifferentSessionAliasIndexes() { @Test void deleteBySessionIdCleansDistinctContextForSameTenantAndSession() { - SessionContext requested = new SessionContext(1L, 10L, "20", 30L, 40L, "requested-jwt"); - SessionContext sameOwner = new SessionContext(1L, 10L, "20", 31L, 41L, "other-jwt"); + SessionContext requested = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "requested-jwt"); + SessionContext sameOwner = new SessionContext(1L, 10L, ACCOUNT_UUID, 31L, 41L, "other-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(requested); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(sameOwner); @@ -255,7 +269,7 @@ void deleteBySessionIdCleansDistinctContextForSameTenantAndSession() { @Test void savePreservesLocaleTagInStoredContext() { SessionContext context = - new SessionContext(1L, 10L, "20", null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); + new SessionContext(1L, 10L, ACCOUNT_UUID, null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); service.save(context); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java index 3a5946fdf7..24158add6f 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java @@ -179,7 +179,7 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { JwtClaims.SignedGameplayRoutingClaims routingClaims = JwtClaims.requireSignedGameplayRoutingClaims( payload, "Connect token account subject mismatch"); - String accountId = Long.toString(routingClaims.accountId()); + String accountId = routingClaims.accountId(); RoutingBundle routingBundle = parseRuntimeRoutingBundleFromClaims(routingClaims); String tenantId = Long.toString(routingClaims.tenantId()); String gameInstanceId = Long.toString(routingClaims.gameInstanceId()); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java index 71abccd271..9cb6a7ab50 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java @@ -30,6 +30,8 @@ import reactor.core.publisher.Mono; class GameplayHandshakeFilterTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3"; private static final String SECRET = "testsecretkeytestsecretkeytest1234"; private static final RuntimeIdentity TEST_RUNTIME_IDENTITY = new RuntimeIdentity( @@ -86,10 +88,10 @@ void rejectsMatrixParameterGameplayRoutesEvenWithCookieCarrier() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -182,10 +184,10 @@ void rejectsFirstPartyHandshakeWithMalformedNumericClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "not-a-number", "worldSlug", "demo", "realmSlug", "production", @@ -221,7 +223,7 @@ void rejectsFirstPartyHandshakeWithZeroAccountIdClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", "accountId", "0", @@ -260,10 +262,10 @@ void rejectsFirstPartyHandshakeWhenSubjectDoesNotMatchAccountIdClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "8", + OTHER_ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -288,6 +290,48 @@ void rejectsFirstPartyHandshakeWhenSubjectDoesNotMatchAccountIdClaim() { .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_INVALID_CONTENT); } + @Test + void rejectsNumericAccountCarrierWithoutForwardingConnectContext() { + GameplayHandshakeFilter filter = + new GameplayHandshakeFilter( + new JwtUtil(SECRET, 30_000L), + TEST_RUNTIME_IDENTITY, + null, + environmentWithProfiles("test")); + String token = + new JwtUtil(SECRET, 30_000L) + .generateToken( + "42", + Map.of( + "aud", "gameplay-connect", + "accountId", "42", + "tenantId", "1", + "worldSlug", "demo", + "realmSlug", "production", + "gameInstanceId", "42", + "pointerVersion", "17", + "connectScopeId", "scope-numeric-account", + "requestId", "req-numeric-account", + "jti", "jti-numeric-account")); + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get("/ws/game/test") + .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) + .build()); + + filter.filter(exchange, e -> Mono.empty()).block(); + + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) + .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); + assertThat( + exchange + .getRequest() + .getHeaders() + .getFirst(GameplayHandshakeFilter.CONNECT_CONTEXT_HEADER)) + .isNull(); + } + @Test void rejectsFirstPartyHandshakeWithZeroPointerVersion() { GameplayHandshakeFilter filter = @@ -299,10 +343,10 @@ void rejectsFirstPartyHandshakeWithZeroPointerVersion() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -336,10 +380,10 @@ void rejectsFirstPartyHandshakeWithMissingRequiredClaim() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "realmSlug", "production", "gameInstanceId", "42", @@ -393,10 +437,10 @@ void rejectsScopeMismatchWhenRequestHeadersDisagreeWithTokenClaims() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -431,10 +475,10 @@ void promotesFirstPartyHandshakeWithCookieCarrier() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -472,10 +516,10 @@ void removesConnectTokenFromMalformedQuotedCookiePair() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -509,10 +553,10 @@ void rejectsPublicHeaderCarrierEvenWhenCookieCarrierIsAlsoPresent() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -573,10 +617,10 @@ void promotesFirstPartyHandshakeWithValidToken() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -638,6 +682,8 @@ void promotesFirstPartyHandshakeWithValidToken() { .parseToken( mutatedExchange.getRequest().getHeaders().getFirst("X-Firemud-Connect-Context")) .getPayload(); + assertThat(connectContextClaims.getSubject()).isEqualTo(ACCOUNT_UUID); + assertThat(connectContextClaims.get("accountId")).isEqualTo(ACCOUNT_UUID); assertThat(connectContextClaims.get("worldSlug")).isEqualTo("demo"); assertThat(connectContextClaims.get("realmSlug")).isEqualTo("production"); assertThat(connectContextClaims.get("pointerVersion")).isEqualTo("18"); @@ -1011,10 +1057,10 @@ void rejectsExpiredConnectToken() { JwtUtil expiredJwtUtil = new JwtUtil(SECRET, -1L); String token = expiredJwtUtil.generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -1057,10 +1103,10 @@ void rejectsReplayedConnectToken() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", @@ -1100,10 +1146,10 @@ void rejectsWhenReplayProtectionStorageIsMissingOutsideDevOrTest() { String token = new JwtUtil(SECRET, 30_000L) .generateToken( - "7", + ACCOUNT_UUID, Map.of( "aud", "gameplay-connect", - "accountId", "7", + "accountId", ACCOUNT_UUID, "tenantId", "1", "worldSlug", "demo", "realmSlug", "production", From 96664a1e5d60751d393e11c3da1ab08e615ad9fc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:06:33 +1300 Subject: [PATCH 055/105] Align Account identity capability status with UUID carrier candidate --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index e4b3bc707b..df035f12fb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -35,7 +35,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. Lifecycle-state retention remains tracked under AA-1.3. | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. The current candidate now emits canonical Account UUID identity in the covered authentication/bootstrap/profile producers and binds matching JWT subject/account claims, with the cross-service carriers and focused proof summarized above; owner-local numeric source-row storage is retained. Tenant identifiers and unrelated numeric-only account consumers remain unconverted, while full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. | From 26732e931f076b2b3980394d5de66f56cbc813c4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:47:28 +1300 Subject: [PATCH 056/105] Prove signed retained Game Session tenant associations --- .../game-design-service/api-contracts.md | 9 + .../game-session-service/api-contracts.md | 8 + .../game-session-service/runtime-and-data.md | 1 + .../player-access-and-session.md | 2 + gradle/libs.versions.toml | 2 + .../v1/tenant_identity_service.proto | 34 + .../common-platform-core/build.gradle.kts | 1 + .../common/json/Rfc8785CanonicalJson.java | 16 + .../GameSessionTenantAssociationEvidence.java | 197 ++++++ .../common/json/Rfc8785CanonicalJsonTest.java | 79 +++ ...eSessionTenantAssociationEvidenceTest.java | 408 ++++++++++++ ...sionTenantAssociationManifestVerifier.java | 68 ++ ...ameSessionTenantAssociationRepository.java | 321 ++++++++++ .../impl/TenantIdentityGrpcService.java | 115 ++++ .../src/main/resources/application-prod.yml | 5 + .../src/main/resources/application.yml | 1 + ..._session_tenant_association_operations.sql | 112 ++++ ...tAssociationRepositoryIntegrationTest.java | 567 ++++++++++++++++ ...TenantAssociationManifestVerifierTest.java | 474 ++++++++++++++ .../TenantIdentityGrpcAuthWiringTest.java | 13 +- .../GameSessionTenantAssociationGrpcTest.java | 263 ++++++++ .../impl/TenantIdentityGrpcServiceTest.java | 9 +- ...GameDesignRuntimeTenantIdentityClient.java | 142 ++++ ...onRetainedTenantAssociationRepository.java | 530 +++++++++++++++ .../GameSessionRetainedTenantSnapshot.java | 528 +++++++++++++++ ...ssionRetainedTenantSnapshotRepository.java | 306 +++++++++ ...ssionRetainedTenantAssociationService.java | 186 ++++++ .../V12__retained_tenant_association.sql | 105 +++ ...tAssociationRepositoryIntegrationTest.java | 606 ++++++++++++++++++ ...nantSnapshotRepositoryIntegrationTest.java | 559 ++++++++++++++++ ...DesignRuntimeTenantIdentityClientTest.java | 315 +++++++++ ...GameSessionRetainedTenantSnapshotTest.java | 290 +++++++++ ...nRetainedTenantAssociationServiceTest.java | 260 ++++++++ 33 files changed, 6527 insertions(+), 5 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJson.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJsonTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V30__game_session_tenant_association_operations.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V12__retained_tenant_association.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 5c8b76dd0a..eb85566bbf 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -37,6 +37,8 @@ The release-attestation, launch-resolution, version-state, settings, asset-purge Game Design now issues a canonical tenant UUID on its owner `game` row and serves the authenticated owner-local `ResolveRuntimeTenantIdentity` read. Migration V29 records exact source-row/key provenance for valid retained keys and leaves blank or out-of-bounds retained keys quarantined without a canonical identity; row identity and provenance are immutable after issuance. This evidence is only a tenant-owner read: it does not publish realm-entry policy or resolve a realm descriptor/template, current realm pointer, playable-state namespace/scope, or actor admission. Reported focused proof: compilation and `generateJooq` succeeded, `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2; the PostgreSQL integration test compiled, but PostgreSQL execution remains unproved because Docker was unavailable. +Migration V30 adds immutable, namespace-scoped Game Design receipts for explicitly signed retained Game Session tenant associations. The owner repository verifies the closed v1 manifest and purpose-specific trusted public-key map, locks and rereads the exact canonical-UUID `game` source row, then makes one-to-one operation, tenant, and retained-key claims with exact retry/readback. `TenantIdentityService.ResolveLegacyGameSessionTenantAssociation` is a separate same-namespace Game Session mTLS read; this does not add a public approval route, generate signing keys, or enable runtime catalog/admission use. Candidate focused tests are present; consolidated execution remains pending. + The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. @@ -72,6 +74,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. - `ResolveRuntimeTenantIdentity` – returns Game Design's persisted canonical tenant UUID and exact source-row/key provenance to Game Session; this owner-local metadata read does not resolve realm policy, realm routing, playable-state namespace/scope, or actor entry. +- `ResolveLegacyGameSessionTenantAssociation` – returns the complete immutable signed Game Design approval for an exact retained Game Session tenant key and canonical tenant UUID to the same-namespace Game Session workload; it is a read-only, nonactivating owner receipt. - `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. @@ -112,6 +115,12 @@ The response fields are `schema_version` (currently `1`), `target_namespace` (th Bounded transport outcomes are: `NOT_FOUND` when no owner row exists for the exact UUID; `FAILED_PRECONDITION` for missing, ambiguous, malformed, or inconsistent persisted provenance; `UNAVAILABLE` for unavailable storage/connection failures; and `INTERNAL` for other read failures. No partial evidence is returned on error. This method does not return a version-bound realm-entry policy, descriptor/template identity, current Game Session pointer, or playable-state namespace/scope; those owner compositions and [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md) actor-entry behavior remain separate, incomplete work. +### Audited retained Game Session tenant association + +The distinct `game-design/game-session-retained-tenant-association/v1` approval binds the exact positive Game Session tenant key, Game Design canonical tenant UUID, source row/key/provenance, namespace, approval labels and timestamp, and Game Session snapshot digest. Its fixed-order UTF-8 length-framed manifest digest and Ed25519 signature are verified by the V30 owner repository against a purpose-specific trusted public-key map before an immutable association claim. Game Design source provenance accepts only `NEW_GAME_ROW` or the current `RETAINED_GAME_V29`; a Game Design row ID or legacy-key string is never substituted for the approved Game Session key. + +The read request carries a separate canonical non-nil `requestId`, approval `operationId`, canonical tenant UUID and canonical positive-decimal retained Game Session tenant key. The response echoes that read request separately and returns the complete approval manifest, recomputed manifest digest, and stored signature. Only the verified same-namespace Game Session workload may read it. Unknown fields and malformed or contradictory exact bindings fail closed; a digest or JWT claim is not workload authentication. The repository's immutable signed-manifest application is an owner maintenance boundary, not a public creator route or runtime activation path; signing-key custody and operational approval materialization remain outside this code slice. + These gRPC entries are the discoverability index for the control-plane contracts described in [Game Templates and Configuration Tools](game-templates.md) and related architecture docs. When request/response schemas evolve, the proto contract and those architecture sections must be updated in the same change so launch-resolution and template-phase semantics do not drift. ## REST & gRPC Endpoints diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..ad9c5abe1e 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -12,6 +12,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat Realm-catalog identity status: Game Session pointer and audit rows persist a separately advancing positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; player-facing catalog and runtime pointer projections fail closed when identity is incomplete or a tenant catalog is ambiguous. The control-plane `SetAdmissionPointer` and `ExecutePreparedVersionCutover` paths remain closed pending catalog-revision and durable-identity preconditions. The configuration-driven pointer initializer validates seed shape but does not write authority rows while World-owned lifecycle proof is unavailable; raw seed inputs do not establish that proof or an owner-validated initial bind. Current implementation and proof gaps are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md). +V12 adds the retained tenant-association receiver and a closed schema-3 snapshot codec for the current Game Session database shape. The candidate service performs the authenticated Game Design read before opening its short owner transaction, fences and re-captures the retained identity projection, and stores exact signed approval plus snapshot evidence under immutable one-to-one constraints. `owner_account_id` is included as the actual nullable current field; no canonical Account UUID is inferred. This receipt is audited retained identity only: it is not a pointer seed, admission result, membership, actor promotion, or `PLAY` authorization. The service remains explicitly unwired pending consolidated Gradle and PostgreSQL proof and operational approval custody. + This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: - the shipped pause/resume control path is `PauseTicksForScope` / `ResumeTicksForScope` at the current `{tenantId, gameInstanceId}` runtime boundary; @@ -34,6 +36,12 @@ For target gameplay forwarding, `PlayerExecutionContext` carries the server-reso It also communicates game lifecycle changes to other microservices over gRPC so they can react to game instances starting, stopping, or changing runtime configuration. +### Audited retained-tenant association (nonactivating) + +For one explicitly approved retained Game Session tenant key, the candidate service first reads Game Design's exact signed approval over the authenticated owner client with no Game Session transaction open. It then starts a short read-write `READ COMMITTED` owner transaction, locks the captured tenant's retained identity table families with `SHARE MODE NOWAIT`, captures one deterministic projection, verifies its digest equals the signed approval's `gameSessionEvidenceDigest`, and inserts/readbacks one immutable namespace-qualified local association. Missing, unreadable, contradictory or concurrently changing evidence fails closed; exact stable request retries return the original persisted receipt without recapturing or changing it. + +The current-tree snapshot uses `schemaVersion=3` and digest domain `game-session/retained-tenant-identity-snapshot/v3`; its SHA-256 preimage is the UTF-8 byte-length-framed pair `(domain, RFC 8785 canonical JSON)`. The JSON contains the exact projection envelope and ordered rows for `instances`, `pointers`, `sharedNamespaces`, empty `backfillIssues`, `pointerEvents`, and `preparedUpgrades`; each row has a closed current-schema fieldset. `instances.owner_account_id` is retained as its actual required numeric value. There is no `owner_account_uuid` field, numeric Game Session tenant keys are never derived from Game Design row IDs, and schema-v2 receipts are incompatible and rejected. This local association is an audited identity bridge only: it does not create or seed a runtime pointer, activate `PLAY`, promote an actor, or grant membership or entitlement. The service is not wired into startup or an activation path; approval materialization/key custody and consolidated Gradle/PostgreSQL execution remain pending. + ## World Lifecycle and Admission Boundary The World Management database row and monotonic lifecycle epoch are the admission authority under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Game Session reads that owner state and epoch at lifecycle-sensitive boundaries; it does not use Temporal workflow status, worker memory, or a projection to admit an instance. `PREPARING` is non-admissible, `ACTIVE` is admissible only after the final version-state and owner checks, `FAILED_PRE_ACTIVATION` is terminal for admission, `TERMINATING` rejects new and reconnected bindings, and `TERMINATED` remains closed. 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 af40c9fcbb..aa4d8a4ba2 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -11,6 +11,7 @@ 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: - 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). +- Game Session V12 adds an immutable local receipt for an approved retained-tenant association. Before its short read-write `READ COMMITTED` transaction, the unwired service reads the exact Game Design approval over the authenticated owner channel; within the transaction it captures the closed retained-row projection behind `SHARE MODE NOWAIT`, compares its digest with the signed approval, then inserts and reads back the one-to-one local association. Snapshot schema 3 binds the current schema's required numeric `game_instances.owner_account_id` without inventing `owner_account_uuid`; its digest domain is `game-session/retained-tenant-identity-snapshot/v3`, so schema-v2 receipts are rejected. This audit prerequisite does not seed a runtime pointer, promote an actor, enable `PLAY`, or activate gameplay. Focused tests are present; consolidated Gradle and PostgreSQL proof are pending. - 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. - **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control. 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 df035f12fb..f67770b225 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ This candidate now carries Account UUID through Account authentication, bootstra Game Design now exposes an authenticated owner-local canonical tenant UUID/provenance read intended for Game Session; this slice claims no Game Session caller wiring. The producer is independent of Account UUID authentication and does not establish the current Game Session pointer, playable-state namespace/scope, published actor-entry policy, Entity selection, or actor creation. Its contract and focused proof status are recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#runtime-tenant-identity-owner-read) and the [Game authoring, publishing, and activation tracker](./game-authoring-publishing-and-activation.md). `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +The retained-tenant association candidate now has a signed Game Design owner receipt/read (V30) and a Game Session local immutable association/snapshot receiver (V12). Its schema-3 snapshot binds the current required numeric `owner_account_id` and rejects older schema-2 receipts rather than implying a canonical owner UUID. This audited mapping is not wired into runtime pointer creation, actor selection, membership, or `PLAY`; approval signing-key custody/materialization, consolidated Gradle execution, PostgreSQL readback proof, and any later explicit activation decision remain dependencies. `AA-2.1` status is unchanged. + Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 246cffd8af..a027b767eb 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -27,6 +27,7 @@ fabric8-kubernetes-client = "7.9.0" # Keep these pins split: bcprov-jdk18on has 1.85.2, but bcpkix-jdk18on and bcutil-jdk18on 1.85.2 artifacts are unpublished. bcprov = "1.86" bcpkix = "1.86" +java-json-canonicalization = "1.1" [libraries] # Spring Boot Starters @@ -100,6 +101,7 @@ java-operator-sdk-spring-boot-starter = { module = "io.javaoperatorsdk:operator- fabric8-kubernetes-client = { module = "io.fabric8:kubernetes-client", version.ref = "fabric8-kubernetes-client" } bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bcprov" } bouncycastle-pkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bcpkix" } +java-json-canonicalization = { module = "io.github.erdtman:java-json-canonicalization", version.ref = "java-json-canonicalization" } testcontainers = { module = "org.testcontainers:testcontainers", version.ref = "testcontainers" } testcontainers-junit-jupiter = { module = "org.testcontainers:testcontainers-junit-jupiter", version.ref = "testcontainers" } diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 9d88ce123e..71cee1b983 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -9,6 +9,9 @@ option java_multiple_files = true; service TenantIdentityService { rpc ResolveRuntimeTenantIdentity(ResolveRuntimeTenantIdentityRequest) returns (ResolveRuntimeTenantIdentityResponse); + // Exact audited retained Game Session association; never an Account manifest or admission. + rpc ResolveLegacyGameSessionTenantAssociation(ResolveLegacyGameSessionTenantAssociationRequest) + returns (ResolveLegacyGameSessionTenantAssociationResponse); } message ResolveRuntimeTenantIdentityRequest { @@ -25,3 +28,34 @@ message ResolveRuntimeTenantIdentityResponse { string source_game_tenant_key = 6; string provenance_kind = 7; } + +message ResolveLegacyGameSessionTenantAssociationRequest { + string request_id = 1; + string operation_id = 2; + string canonical_tenant_id = 3; + // Canonical positive decimal BIGINT provenance, not a public tenant identifier. + string legacy_game_session_tenant_id = 4; +} + +message GameSessionTenantAssociationManifestEvidence { + int32 schema_version = 1; + string operation_id = 2; + string target_namespace = 3; + string signer_key_id = 4; + string approved_by = 5; + string approval_reference = 6; + string signed_at = 7; + string legacy_game_session_tenant_id = 8; + string canonical_tenant_id = 9; + string source_game_row_id = 10; + string source_game_tenant_key = 11; + string provenance_kind = 12; + string game_session_evidence_digest = 13; +} + +message ResolveLegacyGameSessionTenantAssociationResponse { + string request_id = 1; + GameSessionTenantAssociationManifestEvidence manifest = 2; + string manifest_digest = 3; + string ed25519_signature = 4; +} diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 53f7284080..7e67ecc121 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -10,6 +10,7 @@ dependencies { compileOnly(libs.lombok) implementation("com.fasterxml.jackson.core:jackson-databind") + implementation(libs.java.json.canonicalization) implementation(libs.micrometer.core) implementation(libs.opentelemetry.api) implementation(libs.opentelemetry.sdk) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJson.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJson.java new file mode 100644 index 0000000000..5f6d40cf9f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJson.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.common.json; + +import java.io.IOException; +import java.util.Objects; +import org.erdtman.jcs.JsonCanonicalizer; + +/** RFC 8785 JSON Canonicalization Scheme support shared across service boundaries. */ +public final class Rfc8785CanonicalJson { + private Rfc8785CanonicalJson() {} + + /** Returns the RFC 8785 canonical UTF-8 bytes for a JSON object or array. */ + public static byte[] canonicalizeUtf8(String json) throws IOException { + Objects.requireNonNull(json, "json must not be null"); + return new JsonCanonicalizer(json).getEncodedUTF8(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java new file mode 100644 index 0000000000..dbdc07791d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.common.tenant; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable, length-framed evidence for an audited retained Game Session tenant association. */ +public record GameSessionTenantAssociationEvidence( + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + String legacyGameSessionTenantId, + UUID canonicalTenantId, + String sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String gameSessionEvidenceDigest) { + private static final String DOMAIN = "game-design/game-session-retained-tenant-association/v1"; + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public GameSessionTenantAssociationEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported Game Session tenant association evidence schema version"); + } + requireNonNil(operationId, "operationId"); + requireNamespace(targetNamespace); + requireLabel(signerKeyId, 128, "signerKeyId"); + requireLabel(approvedBy, 256, "approvedBy"); + requireLabel(approvalReference, 512, "approvalReference"); + requireCanonicalInstant(signedAt); + requirePositiveBigintText(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requirePositiveBigintText(sourceGameRowId, "sourceGameRowId"); + requireSourceGameTenantKey(sourceGameTenantKey); + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { + throw new IllegalArgumentException("Game Design tenant provenance kind is not recognized"); + } + if (!isDigest(gameSessionEvidenceDigest)) { + throw new IllegalArgumentException( + "gameSessionEvidenceDigest must be a lowercase SHA-256 digest"); + } + } + + /** Returns the exact shared bytes signed by Game Design and hashed by every consumer. */ + public byte[] preimage() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, DOMAIN); + writeSegment(output, Integer.toString(schemaVersion)); + writeSegment(output, operationId.toString()); + writeSegment(output, targetNamespace); + writeSegment(output, signerKeyId); + writeSegment(output, approvedBy); + writeSegment(output, approvalReference); + writeSegment(output, signedAt); + writeSegment(output, legacyGameSessionTenantId); + writeSegment(output, canonicalTenantId.toString()); + writeSegment(output, sourceGameRowId); + writeSegment(output, sourceGameTenantKey); + writeSegment(output, provenanceKind); + writeSegment(output, gameSessionEvidenceDigest); + return output.toByteArray(); + } + + /** SHA-256 of {@link #preimage()}, excluding the signature and this derived digest. */ + public String manifestDigest() { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage()); + return "sha256:" + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Returns the retained Game Session tenant key as its exact positive PostgreSQL BIGINT value. */ + public long legacyGameSessionTenantIdValue() { + return Long.parseLong(legacyGameSessionTenantId); + } + + /** Returns the Game Design source row key as its exact positive PostgreSQL BIGINT value. */ + public long sourceGameRowIdValue() { + return Long.parseLong(sourceGameRowId); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + int byteLength = utf8ByteLength(value); + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + if (encoded.length != byteLength) { + throw new IllegalStateException("UTF-8 segment length changed after validation"); + } + output.writeBytes(Integer.toString(byteLength).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(encoded); + } + + private static void requireNamespace(String value) { + Objects.requireNonNull(value, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(value)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + utf8ByteLength(value); + } + + private static void requireLabel(String value, int maxUtf8Bytes, String label) { + Objects.requireNonNull(value, label); + int byteLength = utf8ByteLength(value); + if (value.isBlank() + || byteLength > maxUtf8Bytes + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " is outside the owner evidence bounds"); + } + } + + private static void requireCanonicalInstant(String value) { + Objects.requireNonNull(value, "signedAt"); + try { + if (!Instant.parse(value).toString().equals(value)) { + throw new IllegalArgumentException("signedAt must be canonical UTC Instant text"); + } + } catch (DateTimeParseException exception) { + throw new IllegalArgumentException("signedAt must be canonical UTC Instant text", exception); + } + } + + private static void requirePositiveBigintText(String value, String label) { + Objects.requireNonNull(value, label); + if (value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + label + " must fit a positive PostgreSQL BIGINT", exception); + } + } + + private static void requireSourceGameTenantKey(String value) { + Objects.requireNonNull(value, "sourceGameTenantKey"); + utf8ByteLength(value); + if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + } + + private static int utf8ByteLength(String value) { + Objects.requireNonNull(value, "value"); + int byteLength = 0; + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException("Evidence must contain valid Unicode"); + } + byteLength += 4; + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException("Evidence must contain valid Unicode"); + } else if (current <= 0x7f) { + byteLength++; + } else if (current <= 0x7ff) { + byteLength += 2; + } else { + byteLength += 3; + } + } + return byteLength; + } + + private static boolean isDigest(String value) { + return value != null && SHA256.matcher(value).matches(); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJsonTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJsonTest.java new file mode 100644 index 0000000000..ec498185de --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJsonTest.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.common.json; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class Rfc8785CanonicalJsonTest { + @Test + void sortsObjectKeysByUtf16CodeUnitsAndPreservesArrayOrder() throws Exception { + String input = + """ + [ + 56, + { + "d": true, + "10": null, + "1": [] + } + ] + """; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo("[56,{\"1\":[],\"10\":null,\"d\":true}]".getBytes(StandardCharsets.UTF_8)); + } + + @Test + void sortsUnicodeObjectKeysByRawUtf16CodeUnits() throws Exception { + String input = + """ + { + "\\u20ac": "Euro Sign", + "\\r": "Carriage Return", + "\\u000a": "Newline", + "1": "One", + "\\u0080": "Control\\u007f", + "\\ud83d\\ude02": "Smiley", + "\\u00f6": "Latin Small Letter O With Diaeresis", + "\\ufb33": "Hebrew Letter Dalet With Dagesh", + "": "Browser Challenge" + } + """; + String expected = + "{\"\\n\":\"Newline\",\"\\r\":\"Carriage Return\",\"1\":\"One\"," + + "\"\":\"Browser Challenge\",\"\u0080\":\"Control\u007f\"," + + "\"\u00f6\":\"Latin Small Letter O With Diaeresis\",\"\u20ac\":\"Euro Sign\"," + + "\"\ud83d\ude02\":\"Smiley\",\"\ufb33\":\"Hebrew Letter Dalet With Dagesh\"}"; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo(expected.getBytes(StandardCharsets.UTF_8)); + } + + @Test + void preservesUnicodeCodePointsWithoutNormalization() throws Exception { + String input = "{\"decomposed\":\"e\\u0301\",\"composed\":\"\\u00e9\"}"; + String expected = "{\"composed\":\"\u00e9\",\"decomposed\":\"e\u0301\"}"; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo(expected.getBytes(StandardCharsets.UTF_8)); + } + + @Test + void rejectsDuplicateObjectProperties() { + assertThatThrownBy(() -> Rfc8785CanonicalJson.canonicalizeUtf8("{\"a\":1,\"a\":2}")) + .isInstanceOf(java.io.IOException.class) + .hasMessageContaining("Duplicate property: a"); + } + + @Test + void rendersNumbersUsingJcsEcmascriptRules() throws Exception { + String input = + "{\"numbers\":[333333333.33333329,1E30,4.50,2e-3,0.000000000000000000000000001]}"; + String expected = "{\"numbers\":[333333333.3333333,1e+30,4.5,0.002,1e-27]}"; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo(expected.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java new file mode 100644 index 0000000000..178b6a9674 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java @@ -0,0 +1,408 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class GameSessionTenantAssociationEvidenceTest { + private static final UUID OPERATION_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String GAME_SESSION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void emitsFixedCompleteUtf8FramingAndManifestDigestVector() { + GameSessionTenantAssociationEvidence evidence = evidence(); + + assertThat(new String(evidence.preimage(), java.nio.charset.StandardCharsets.UTF_8)) + .isEqualTo( + "55:game-design/game-session-retained-tenant-association/v1" + + "1:1" + + "36:11111111-1111-4111-8111-111111111111" + + "7:firemud" + + "14:owner-key-2026" + + "10:owner 🧙" + + "17:review café-🐉" + + "20:2026-10-01T00:00:00Z" + + "16:9007199254740993" + + "36:22222222-2222-4222-8222-222222222222" + + "2:42" + + "18:legacy-game-key-42" + + "17:RETAINED_GAME_V29" + + "71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + assertThat(evidence.manifestDigest()) + .isEqualTo("sha256:8dbc7e33a24d4e6d577a381276df0a9b0168b78363749a37f05cc76f0e9c152c"); + } + + @Test + void exposesLargeCanonicalBigintTextsWithoutFloatingPointLoss() { + GameSessionTenantAssociationEvidence aboveExactDoubleInteger = evidence(); + assertThat(aboveExactDoubleInteger.legacyGameSessionTenantIdValue()) + .isEqualTo(9_007_199_254_740_993L); + + GameSessionTenantAssociationEvidence maxBigint = + copyIds(evidence(), Long.toString(Long.MAX_VALUE), Long.toString(Long.MAX_VALUE)); + assertThat(maxBigint.legacyGameSessionTenantIdValue()).isEqualTo(Long.MAX_VALUE); + assertThat(maxBigint.sourceGameRowIdValue()).isEqualTo(Long.MAX_VALUE); + } + + @Test + void changedValidFieldChangesSharedPreimageAndDigest() { + GameSessionTenantAssociationEvidence source = evidence(); + for (GameSessionTenantAssociationEvidence changed : changedFields(source)) { + assertThat(changed.preimage()).isNotEqualTo(source.preimage()); + assertThat(changed.manifestDigest()).isNotEqualTo(source.manifestDigest()); + } + assertThatThrownBy(() -> copyWithSchemaVersion(source, 2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schema version"); + } + + @Test + void preservesApprovalTextExactlyAndRequiresCanonicalUtcInstant() { + GameSessionTenantAssociationEvidence spaced = + new GameSessionTenantAssociationEvidence( + 1, + OPERATION_ID, + "firemud", + "owner-key-2026", + " owner ", + " reference ", + "2026-10-01T00:00:00Z", + "41", + TENANT_ID, + "42", + " legacy-game-key ", + "RETAINED_GAME_V29", + GAME_SESSION_DIGEST); + assertThat(spaced.approvedBy()).isEqualTo(" owner "); + assertThat(spaced.approvalReference()).isEqualTo(" reference "); + assertThat(spaced.sourceGameTenantKey()).isEqualTo(" legacy-game-key "); + + assertInvalid(() -> copySignedAt(evidence(), "2026-10-01T00:00:00+00:00")); + assertInvalid(() -> copySignedAt(evidence(), "2026-10-01T00:00:00.000Z")); + assertInvalid(() -> copySignedAt(evidence(), "not-an-instant")); + } + + @Test + void acceptsUtf8ApprovalLimitsAndTheRuntimeTenantSourceKeyBounds() { + GameSessionTenantAssociationEvidence source = evidence(); + GameSessionTenantAssociationEvidence maximumLabels = + copyWithLabels(source, "é".repeat(64), "é".repeat(128), "é".repeat(256)); + GameSessionTenantAssociationEvidence maximumSourceKey = + copyWithSourceKey(source, "🐉".repeat(36)); + + assertThat(maximumLabels.signerKeyId()).hasSize(64); + assertThat(maximumLabels.approvedBy()).hasSize(128); + assertThat(maximumLabels.approvalReference()).hasSize(256); + assertThat(maximumSourceKey.sourceGameTenantKey()).hasSize(72); + } + + @Test + void rejectsMalformedIdentifiersBoundsUnicodeAndClosedEnums() { + GameSessionTenantAssociationEvidence source = evidence(); + assertInvalid(() -> withIds(source, "0", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, "01", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, "+1", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, "9223372036854775808", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, source.legacyGameSessionTenantId(), "00")); + assertInvalid(() -> withIds(source, source.legacyGameSessionTenantId(), "9223372036854775808")); + assertInvalid(() -> copyWithUuid(source, new UUID(0L, 0L), source.canonicalTenantId())); + assertInvalid(() -> copyWithUuid(source, source.operationId(), new UUID(0L, 0L))); + assertInvalid(() -> copyWithNamespace(source, "firemud.invalid")); + assertInvalid(() -> copyWithSourceKey(source, " ")); + assertInvalid(() -> copyWithSourceKey(source, "x".repeat(37))); + assertInvalid(() -> copyWithSourceKey(source, "x" + (char) 0xd800)); + assertInvalid( + () -> + copyWithLabels( + source, "k".repeat(129), source.approvedBy(), source.approvalReference())); + assertInvalid( + () -> + copyWithLabels( + source, source.signerKeyId(), "a".repeat(257), source.approvalReference())); + assertInvalid( + () -> copyWithLabels(source, source.signerKeyId(), source.approvedBy(), "r".repeat(513))); + assertInvalid( + () -> + copyWithLabels( + source, source.signerKeyId(), "owner\nname", source.approvalReference())); + assertInvalid(() -> copyWithProvenance(source, "OTHER")); + assertInvalid(() -> copyWithEvidenceDigest(source, "SHA256:" + "a".repeat(64))); + } + + private static GameSessionTenantAssociationEvidence evidence() { + return new GameSessionTenantAssociationEvidence( + 1, + OPERATION_ID, + "firemud", + "owner-key-2026", + "owner 🧙", + "review café-🐉", + Instant.parse("2026-10-01T00:00:00Z").toString(), + "9007199254740993", + TENANT_ID, + "42", + "legacy-game-key-42", + "RETAINED_GAME_V29", + GAME_SESSION_DIGEST); + } + + private static GameSessionTenantAssociationEvidence copySignedAt( + GameSessionTenantAssociationEvidence source, String signedAt) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + signedAt, + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyIds( + GameSessionTenantAssociationEvidence source, + String legacyGameSessionTenantId, + String sourceGameRowId) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + legacyGameSessionTenantId, + source.canonicalTenantId(), + sourceGameRowId, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSchemaVersion( + GameSessionTenantAssociationEvidence source, int schemaVersion) { + return copy( + source, + schemaVersion, + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithNamespace( + GameSessionTenantAssociationEvidence source, String namespace) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + namespace, + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithUuid( + GameSessionTenantAssociationEvidence source, UUID operationId, UUID canonicalTenantId) { + return copy( + source, + source.schemaVersion(), + operationId, + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + canonicalTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSourceKey( + GameSessionTenantAssociationEvidence source, String sourceGameTenantKey) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + sourceGameTenantKey, + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithLabels( + GameSessionTenantAssociationEvidence source, + String signerKeyId, + String approvedBy, + String approvalReference) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + signerKeyId, + approvedBy, + approvalReference, + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithProvenance( + GameSessionTenantAssociationEvidence source, String provenanceKind) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + provenanceKind, + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithEvidenceDigest( + GameSessionTenantAssociationEvidence source, String gameSessionEvidenceDigest) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + gameSessionEvidenceDigest); + } + + private static GameSessionTenantAssociationEvidence withIds( + GameSessionTenantAssociationEvidence source, + String legacyGameSessionTenantId, + String sourceGameRowId) { + return copyIds(source, legacyGameSessionTenantId, sourceGameRowId); + } + + private static GameSessionTenantAssociationEvidence copy( + GameSessionTenantAssociationEvidence source, + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + String legacyGameSessionTenantId, + UUID canonicalTenantId, + String sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String gameSessionEvidenceDigest) { + return new GameSessionTenantAssociationEvidence( + schemaVersion, + operationId, + targetNamespace, + signerKeyId, + approvedBy, + approvalReference, + signedAt, + legacyGameSessionTenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + gameSessionEvidenceDigest); + } + + private static void assertInvalid(Runnable construction) { + assertThatThrownBy(construction::run).isInstanceOf(IllegalArgumentException.class); + } + + private static java.util.List changedFields( + GameSessionTenantAssociationEvidence source) { + return java.util.List.of( + copyIds(source, "9007199254740994", source.sourceGameRowId()), + copyWithNamespace(source, "firemud-dev"), + copyWithLabels(source, "owner-key-2027", source.approvedBy(), source.approvalReference()), + copyWithLabels(source, source.signerKeyId(), "another owner", source.approvalReference()), + copyWithLabels( + source, source.signerKeyId(), source.approvedBy(), "another-review-reference"), + copySignedAt(source, "2026-10-01T00:00:01Z"), + copyWithOperationId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), + copyWithUuid( + source, source.operationId(), UUID.fromString("33333333-3333-4333-8333-333333333333")), + copyIds(source, source.legacyGameSessionTenantId(), "43"), + copyWithSourceKey(source, "another-source-key"), + copyWithProvenance(source, "NEW_GAME_ROW"), + copyWithEvidenceDigest(source, "sha256:" + "b".repeat(64))); + } + + private static GameSessionTenantAssociationEvidence copyWithOperationId( + GameSessionTenantAssociationEvidence source, UUID operationId) { + return copy( + source, + source.schemaVersion(), + operationId, + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java new file mode 100644 index 0000000000..15d39c0bf2 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import java.util.Map; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; + +/** Verifies Game Design owner approval for one retained Game Session tenant association. */ +public final class GameSessionTenantAssociationManifestVerifier { + private GameSessionTenantAssociationManifestVerifier() {} + + /** + * Verifies canonical signed evidence with the protected, purpose-specific Game Design owner + * approval public-key allowlist. This map is not an Account key ring or a general JWKS. + */ + public static Verified verify(Signed signed, Map trustedOwnerApprovalPublicKeys) { + if (signed == null || signed.manifest() == null || trustedOwnerApprovalPublicKeys == null) { + throw new IllegalArgumentException("signed Game Session tenant association is required"); + } + GameSessionTenantAssociationEvidence manifest = signed.manifest(); + String encodedKey = trustedOwnerApprovalPublicKeys.get(manifest.signerKeyId()); + if (encodedKey == null || encodedKey.isBlank()) { + throw new IllegalArgumentException("manifest signer is not trusted for owner approval"); + } + + try { + byte[] encodedKeyBytes = Base64.getDecoder().decode(encodedKey); + if (!Base64.getEncoder().encodeToString(encodedKeyBytes).equals(encodedKey)) { + throw new IllegalArgumentException("owner approval public key encoding is not canonical"); + } + PublicKey publicKey = + KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(encodedKeyBytes)); + byte[] preimage = manifest.preimage(); + byte[] signatureBytes = decodeCanonicalSignature(signed.ed25519Signature()); + Signature verifier = Signature.getInstance("Ed25519"); + verifier.initVerify(publicKey); + verifier.update(preimage); + if (!verifier.verify(signatureBytes)) { + throw new IllegalArgumentException("manifest owner signature is invalid"); + } + return new Verified(manifest, manifest.manifestDigest()); + } catch (IllegalArgumentException exception) { + throw exception; + } catch (Exception exception) { + throw new IllegalArgumentException("manifest owner signature cannot be verified", exception); + } + } + + private static byte[] decodeCanonicalSignature(String encodedSignature) { + if (encodedSignature == null || encodedSignature.isBlank()) { + throw new IllegalArgumentException("manifest owner signature is required"); + } + byte[] signatureBytes = Base64.getDecoder().decode(encodedSignature); + if (signatureBytes.length != 64 + || !Base64.getEncoder().encodeToString(signatureBytes).equals(encodedSignature)) { + throw new IllegalArgumentException( + "manifest owner signature must be canonical 64-byte Ed25519"); + } + return signatureBytes; + } + + public record Signed(GameSessionTenantAssociationEvidence manifest, String ed25519Signature) {} + + public record Verified(GameSessionTenantAssociationEvidence manifest, String manifestDigest) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java new file mode 100644 index 0000000000..85e859dc05 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java @@ -0,0 +1,321 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Signed; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Verified; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable Game Design owner receipt for an audited retained Game Session tenant association. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext and GameRepository are internal owner collaborators.") +public class GameSessionTenantAssociationRepository { + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + private static final Table ASSOCIATION = + DSL.table(DSL.name("game_design_game_session_tenant_association_operations")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field SIGNER_KEY_ID = + DSL.field(DSL.name("signer_key_id"), String.class); + private static final Field APPROVED_BY = DSL.field(DSL.name("approved_by"), String.class); + private static final Field APPROVAL_REFERENCE = + DSL.field(DSL.name("approval_reference"), String.class); + private static final Field SIGNED_AT = DSL.field(DSL.name("signed_at"), String.class); + private static final Field LEGACY_GAME_SESSION_TENANT_ID = + DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field GAME_SESSION_EVIDENCE_DIGEST = + DSL.field(DSL.name("game_session_evidence_digest"), String.class); + private static final Field MANIFEST_DIGEST = + DSL.field(DSL.name("manifest_digest"), String.class); + private static final Field SIGNATURE = DSL.field(DSL.name("signature"), String.class); + + private final DSLContext dsl; + private final GameRepository gameRepository; + + public GameSessionTenantAssociationRepository(DSLContext dsl, GameRepository gameRepository) { + this.dsl = dsl; + this.gameRepository = gameRepository; + } + + /** + * Verifies and atomically records the approved association inside its caller's owner transaction. + * + *

The actual canonical-UUID game row is locked before source validation and the one-row claim. + * A uniqueness conflict is resolved by exact persisted operation readback after the insert + * attempt, so no preflight lookup can race into a false successful claim. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AssociationReceipt apply( + Signed signed, Map trustedPublicKeys, String exactNamespace) { + Verified verified = + GameSessionTenantAssociationManifestVerifier.verify(signed, trustedPublicKeys); + GameSessionTenantAssociationEvidence manifest = verified.manifest(); + if (exactNamespace == null || !exactNamespace.equals(manifest.targetNamespace())) { + throw new IllegalArgumentException("manifest targets a different namespace"); + } + requireActiveOwnerTransaction(); + + GameTenantIdentity source = lockAndReadSource(manifest.canonicalTenantId()); + requireManifestSource(manifest, source); + + int inserted = + dsl.insertInto(ASSOCIATION) + .set(OPERATION_ID, manifest.operationId()) + .set(SCHEMA_VERSION, manifest.schemaVersion()) + .set(TARGET_NAMESPACE, manifest.targetNamespace()) + .set(SIGNER_KEY_ID, manifest.signerKeyId()) + .set(APPROVED_BY, manifest.approvedBy()) + .set(APPROVAL_REFERENCE, manifest.approvalReference()) + .set(SIGNED_AT, manifest.signedAt()) + .set(LEGACY_GAME_SESSION_TENANT_ID, manifest.legacyGameSessionTenantIdValue()) + .set(CANONICAL_TENANT_ID, manifest.canonicalTenantId()) + .set(SOURCE_GAME_ROW_ID, manifest.sourceGameRowIdValue()) + .set(SOURCE_GAME_TENANT_KEY, manifest.sourceGameTenantKey()) + .set(PROVENANCE_KIND, manifest.provenanceKind()) + .set(GAME_SESSION_EVIDENCE_DIGEST, manifest.gameSessionEvidenceDigest()) + .set(MANIFEST_DIGEST, verified.manifestDigest()) + .set(SIGNATURE, signed.ed25519Signature()) + .onConflictDoNothing() + .execute(); + + Record persisted = findByOperationId(manifest.operationId()); + if (persisted == null) { + if (inserted == 0) { + throw new AssociationConflictException( + "canonical tenant or retained Game Session key is already associated"); + } + throw new InvalidAssociationEvidenceException( + "committed Game Session tenant association operation is missing"); + } + + AssociationReceipt receipt = toValidatedReceipt(persisted); + requireExactReceipt(verified, signed.ed25519Signature(), receipt); + requireManifestSource(receipt.manifest(), source); + return receipt; + } + + /** + * Reads exact committed owner evidence without allocation, repair, or signature reauthorization. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID operationId, + UUID canonicalTenantId, + long legacyGameSessionTenantId, + String exactNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session tenant association read requires a committed-outcome owner read"); + } + if (operationId == null || operationId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("operationId must be a canonical non-nil UUID"); + } + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("canonicalTenantId must be a canonical non-nil UUID"); + } + if (legacyGameSessionTenantId <= 0) { + throw new IllegalArgumentException("legacy Game Session tenant key must be positive"); + } + if (exactNamespace == null || exactNamespace.isBlank()) { + throw new IllegalArgumentException("exact namespace is required"); + } + + Record row = + dsl.selectFrom(ASSOCIATION) + .where( + OPERATION_ID + .eq(operationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(LEGACY_GAME_SESSION_TENANT_ID.eq(legacyGameSessionTenantId)) + .and(TARGET_NAMESPACE.eq(exactNamespace))) + .fetchOne(); + if (row == null) { + return Optional.empty(); + } + + AssociationReceipt receipt = toValidatedReceipt(row); + GameTenantIdentity source = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId(receipt.manifest().canonicalTenantId()) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "persisted Game Session tenant association source is missing")); + requireManifestSource(receipt.manifest(), source); + return Optional.of(receipt); + } + + private GameTenantIdentity lockAndReadSource(UUID canonicalTenantId) { + Long lockedGameId = + dsl.select(GAME_ID) + .from(GAME) + .where(GAME_CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .forUpdate() + .fetchOne(GAME_ID); + if (lockedGameId == null) { + throw new AssociationConflictException("canonical tenant source game row is missing"); + } + GameTenantIdentity source = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId(canonicalTenantId) + .orElseThrow( + () -> + new AssociationConflictException( + "canonical tenant source game row is missing")); + if (source.sourceGameId() == null || !lockedGameId.equals(source.sourceGameId())) { + throw new InvalidAssociationEvidenceException( + "locked Game Design source row changed during canonical tenant readback"); + } + return source; + } + + private Record findByOperationId(UUID operationId) { + return dsl.selectFrom(ASSOCIATION).where(OPERATION_ID.eq(operationId)).fetchOne(); + } + + private AssociationReceipt toValidatedReceipt(Record row) { + try { + GameSessionTenantAssociationEvidence manifest = + new GameSessionTenantAssociationEvidence( + row.get(SCHEMA_VERSION), + row.get(OPERATION_ID), + row.get(TARGET_NAMESPACE), + row.get(SIGNER_KEY_ID), + row.get(APPROVED_BY), + row.get(APPROVAL_REFERENCE), + row.get(SIGNED_AT), + Long.toString(row.get(LEGACY_GAME_SESSION_TENANT_ID)), + row.get(CANONICAL_TENANT_ID), + Long.toString(row.get(SOURCE_GAME_ROW_ID)), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(PROVENANCE_KIND), + row.get(GAME_SESSION_EVIDENCE_DIGEST)); + String signature = row.get(SIGNATURE); + requireCanonicalSignatureShape(signature); + String persistedDigest = row.get(MANIFEST_DIGEST); + if (!manifest.manifestDigest().equals(persistedDigest)) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association digest does not match its manifest"); + } + return new AssociationReceipt(manifest, signature, persistedDigest); + } catch (InvalidAssociationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association evidence is invalid", exception); + } + } + + private void requireManifestSource( + GameSessionTenantAssociationEvidence manifest, GameTenantIdentity source) { + if (source == null) { + throw new InvalidAssociationEvidenceException( + "Game Session tenant association source no longer matches its Game Design game row"); + } + Long sourceGameId = source.sourceGameId(); + GameTenantIdentity.ProvenanceKind provenanceKind = source.provenanceKind(); + if (sourceGameId == null + || provenanceKind == null + || !manifest.canonicalTenantId().equals(source.canonicalTenantId()) + || manifest.sourceGameRowIdValue() != sourceGameId + || !manifest.sourceGameTenantKey().equals(source.sourceLegacyTenantId()) + || !manifest.provenanceKind().equals(provenanceKind.name())) { + throw new InvalidAssociationEvidenceException( + "Game Session tenant association source no longer matches its Game Design game row"); + } + } + + private void requireExactReceipt(Verified verified, String signature, AssociationReceipt actual) { + if (!verified.manifest().equals(actual.manifest()) + || !verified.manifestDigest().equals(actual.manifestDigest()) + || !signature.equals(actual.ed25519Signature())) { + throw new AssociationConflictException( + "Game Session tenant association operation was reused with changed signed evidence"); + } + } + + private void requireCanonicalSignatureShape(String signature) { + if (signature == null || signature.isBlank()) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association signature is missing"); + } + byte[] signatureBytes; + try { + signatureBytes = Base64.getDecoder().decode(signature); + } catch (IllegalArgumentException exception) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association signature is not canonical Ed25519", + exception); + } + if (signatureBytes.length != 64 + || !Base64.getEncoder().encodeToString(signatureBytes).equals(signature)) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association signature is not canonical Ed25519"); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session tenant association apply requires an active Game Design owner transaction"); + } + } + + public record AssociationReceipt( + GameSessionTenantAssociationEvidence manifest, + String ed25519Signature, + String manifestDigest) { + public AssociationReceipt { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(ed25519Signature, "ed25519Signature"); + Objects.requireNonNull(manifestDigest, "manifestDigest"); + } + } + + public static final class AssociationConflictException extends IllegalStateException { + public AssociationConflictException(String message) { + super(message); + } + } + + public static final class InvalidAssociationEvidenceException extends IllegalStateException { + public InvalidAssociationEvidenceException(String message) { + super(message); + } + + public InvalidAssociationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index 15a26369a6..d0f1cb8ca3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -6,9 +6,14 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.v1.GameSessionTenantAssociationManifestEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -23,12 +28,15 @@ public class TenantIdentityGrpcService extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { private final GameRepository gameRepository; + private final GameSessionTenantAssociationRepository gameSessionAssociationRepository; private final String workloadNamespace; public TenantIdentityGrpcService( GameRepository gameRepository, + GameSessionTenantAssociationRepository gameSessionAssociationRepository, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.gameRepository = gameRepository; + this.gameSessionAssociationRepository = gameSessionAssociationRepository; this.workloadNamespace = workloadNamespace; } @@ -134,6 +142,100 @@ public void resolveRuntimeTenantIdentity( responseObserver.onCompleted(); } + @Override + public void resolveLegacyGameSessionTenantAssociation( + ResolveLegacyGameSessionTenantAssociationRequest request, + StreamObserver responseObserver) { + if (!isGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID operationId = parseCanonicalNonNilUuid(request.getOperationId()); + UUID tenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + long legacyTenantId; + try { + if (requestId == null + || operationId == null + || tenantId == null + || !request.getUnknownFields().asMap().isEmpty() + || !request.getLegacyGameSessionTenantId().matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact association request is required"); + } + legacyTenantId = Long.parseLong(request.getLegacyGameSessionTenantId()); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical exact association request is required") + .asRuntimeException()); + return; + } + Optional resolved; + try { + resolved = + gameSessionAssociationRepository.read( + operationId, tenantId, legacyTenantId, workloadNamespace); + } catch (IllegalArgumentException | IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Retained Game Session association evidence is inconsistent") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Retained Game Session association could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No approved retained Game Session association for the exact scope") + .asRuntimeException()); + return; + } + var receipt = resolved.orElseThrow(); + GameSessionTenantAssociationEvidence evidence = receipt.manifest(); + if (!operationId.equals(evidence.operationId()) + || !tenantId.equals(evidence.canonicalTenantId()) + || !workloadNamespace.equals(evidence.targetNamespace()) + || !request.getLegacyGameSessionTenantId().equals(evidence.legacyGameSessionTenantId()) + || !evidence.manifestDigest().equals(receipt.manifestDigest()) + || !validSignature(receipt.ed25519Signature())) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Retained association readback does not match the exact request") + .asRuntimeException()); + return; + } + responseObserver.onNext( + ResolveLegacyGameSessionTenantAssociationResponse.newBuilder() + .setRequestId(requestId.toString()) + .setManifest( + GameSessionTenantAssociationManifestEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setOperationId(evidence.operationId().toString()) + .setTargetNamespace(evidence.targetNamespace()) + .setSignerKeyId(evidence.signerKeyId()) + .setApprovedBy(evidence.approvedBy()) + .setApprovalReference(evidence.approvalReference()) + .setSignedAt(evidence.signedAt()) + .setLegacyGameSessionTenantId(evidence.legacyGameSessionTenantId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setGameSessionEvidenceDigest(evidence.gameSessionEvidenceDigest())) + .setManifestDigest(receipt.manifestDigest()) + .setEd25519Signature(receipt.ed25519Signature()) + .build()); + responseObserver.onCompleted(); + } + private boolean isGameSessionPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null @@ -165,4 +267,17 @@ private static boolean hasConnectionFailureSqlState(Throwable failure) { } return false; } + + private static boolean validSignature(String value) { + if (value == null) { + return false; + } + try { + byte[] signature = java.util.Base64.getDecoder().decode(value); + return signature.length == 64 + && java.util.Base64.getEncoder().encodeToString(signature).equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } } 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 15cca178a6..800591b8b2 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -47,6 +47,11 @@ server: min-response-size: 1024 firemud: + auth: + grpc: + public-methods: + - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity + - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index d1bce34ed8..13b9520bb1 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -62,6 +62,7 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity + - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/main/resources/db/migration/V30__game_session_tenant_association_operations.sql b/services/game-design-service/src/main/resources/db/migration/V30__game_session_tenant_association_operations.sql new file mode 100644 index 0000000000..fe893c4417 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V30__game_session_tenant_association_operations.sql @@ -0,0 +1,112 @@ +CREATE TABLE game_design_game_session_tenant_association_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + game_session_evidence_digest VARCHAR(71) NOT NULL, + manifest_digest VARCHAR(71) NOT NULL, + signature VARCHAR(88) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_game_session_association_canonical + UNIQUE (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_game_session_association_retained_key + UNIQUE (target_namespace, legacy_game_session_tenant_id), + CONSTRAINT chk_gd_game_session_association_schema CHECK (schema_version = 1), + CONSTRAINT chk_gd_game_session_association_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_game_session_association_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_game_session_association_approval_labels CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_game_session_association_signed_at CHECK ( + char_length(signed_at) BETWEEN 1 AND 64 + ), + CONSTRAINT chk_gd_game_session_association_retained_key CHECK ( + legacy_game_session_tenant_id > 0 + ), + CONSTRAINT chk_gd_game_session_association_canonical CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_game_session_association_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_game_session_association_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_game_session_association_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ), + CONSTRAINT chk_gd_game_session_association_digests CHECK ( + game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND manifest_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_game_session_association_signature CHECK ( + signature ~ '^[A-Za-z0-9+/]{86}==$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_game_session_tenant_association() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Session tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Session tenant association source does not match its Game Design row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_association_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_game_session_tenant_association_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_game_session_tenant_association(); + +CREATE FUNCTION reject_gd_game_session_tenant_association_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_association_no_truncate + BEFORE TRUNCATE ON game_design_game_session_tenant_association_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_game_session_tenant_association_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..8d0ceb9b8a --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -0,0 +1,567 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Signed; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameSessionTenantAssociationRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "game-session-association-test"; + private static final String SIGNER_KEY_ID = "gd-owner-approval-test"; + private static final String GAME_SESSION_EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table ASSOCIATIONS = + DSL.table(DSL.name("game_design_game_session_tenant_association_operations")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field APPROVED_BY = + DSL.field(DSL.name("approved_by"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void appliesAuditedAssociationForFreshAndRetainedGameSources() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed retainedSigned = fixture.signed(fixture.retainedSource(), 901L, uuid(1)); + Signed freshSigned = fixture.signed(fixture.freshSource(), 902L, uuid(2)); + + AssociationReceipt retained = fixture.apply(retainedSigned, NAMESPACE); + AssociationReceipt fresh = fixture.apply(freshSigned, NAMESPACE); + + assertThat(retained.manifest().provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retained.manifest().sourceGameRowIdValue()) + .isEqualTo(fixture.retainedSource().sourceGameId()); + assertThat(retained.manifest().legacyGameSessionTenantIdValue()).isEqualTo(901L); + assertThat(fresh.manifest().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(fresh.manifest().sourceGameRowIdValue()) + .isEqualTo(fixture.freshSource().sourceGameId()); + assertThat(fresh.manifest().legacyGameSessionTenantIdValue()).isEqualTo(902L); + assertThat(fixture.read(retained)).contains(retained); + assertThat(fixture.read(fresh)).contains(fresh); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReturnsSameSignedEvidenceWithoutMutatingSourceOrAssociation() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 910L, uuid(10)); + AssociationReceipt first = fixture.apply(signed, NAMESPACE); + String originalGameXmin = fixture.gameXmin(fixture.freshSource().sourceGameId()); + + AssociationReceipt retry = fixture.apply(signed, NAMESPACE); + + assertThat(retry).isEqualTo(first); + assertThat(fixture.gameXmin(fixture.freshSource().sourceGameId())).isEqualTo(originalGameXmin); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.read(first)).contains(first); + } + + @Test + void changedSignedFieldUnderSameOperationConflictsWithoutReplacingReceipt() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed original = fixture.signed(fixture.freshSource(), 920L, uuid(20)); + AssociationReceipt committed = fixture.apply(original, NAMESPACE); + GameSessionTenantAssociationEvidence changedManifest = + withApprovalReference(original.manifest(), "changed-approved-reference"); + Signed changed = fixture.sign(changedManifest); + + assertThatThrownBy(() -> fixture.apply(changed, NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("reused with changed signed evidence"); + + assertThat(fixture.read(committed)).contains(committed); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void canonicalAndRetainedKeyCollisionsFailWithoutPartialAssociationClaims() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed first = fixture.signed(fixture.freshSource(), 930L, uuid(30)); + AssociationReceipt committed = fixture.apply(first, NAMESPACE); + Signed sameCanonicalDifferentRetainedKey = + fixture.signed(fixture.freshSource(), 931L, uuid(31)); + Signed sameRetainedKeyDifferentCanonical = + fixture.signed(fixture.retainedSource(), 930L, uuid(32)); + + assertThatThrownBy(() -> fixture.apply(sameCanonicalDifferentRetainedKey, NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("already associated"); + assertThatThrownBy(() -> fixture.apply(sameRetainedKeyDifferentCanonical, NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("already associated"); + + assertThat(fixture.read(committed)).contains(committed); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + } + + @Test + void absentOrContradictoryGameDesignSourcesFailWithoutAssociationMutation() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + GameSessionTenantAssociationEvidence absentSource = + fixture.evidence( + uuid(40), + 940L, + UUID.randomUUID(), + fixture.freshSource().sourceGameId(), + "unrelated-game-key", + "NEW_GAME_ROW"); + GameSessionTenantAssociationEvidence contradictorySource = + fixture.evidence( + uuid(41), + 941L, + fixture.freshSource().canonicalTenantId(), + fixture.retainedSource().sourceGameId(), + fixture.freshSource().sourceLegacyTenantId(), + "NEW_GAME_ROW"); + + assertThatThrownBy(() -> fixture.apply(fixture.sign(absentSource), NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("source game row is missing"); + assertThatThrownBy(() -> fixture.apply(fixture.sign(contradictorySource), NAMESPACE)) + .isInstanceOf( + GameSessionTenantAssociationRepository.InvalidAssociationEvidenceException.class) + .hasMessageContaining("source no longer matches"); + + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + } + + @Test + void concurrentExactFirstWritersReturnOneImmutableReceipt() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 950L, uuid(50)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> concurrentApply(fixture, signed, ready, start)); + Future second = + executor.submit(() -> concurrentApply(fixture, signed, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AssociationReceipt firstReceipt = first.get(10, TimeUnit.SECONDS); + AssociationReceipt secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(fixture.read(firstReceipt)).contains(firstReceipt); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void ownerRollbackLeavesNoClaimAndLostAcknowledgementRetryReadsExactReceipt() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 960L, uuid(60)); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + fixture.repository().apply(signed, fixture.trustedKeys(), NAMESPACE); + throw new IllegalStateException("simulate owner commit rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate owner commit rollback"); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isZero(); + + fixture.apply(signed, NAMESPACE); // The commit response is intentionally discarded. + AssociationReceipt exactReadback = fixture.apply(signed, NAMESPACE); + + assertThat(exactReadback.manifest()).isEqualTo(signed.manifest()); + assertThat(exactReadback.ed25519Signature()).isEqualTo(signed.ed25519Signature()); + assertThat(exactReadback.manifestDigest()).isEqualTo(signed.manifest().manifestDigest()); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void applyRequiresOwnerTransactionAndReadRequiresExactCommittedScope() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 970L, uuid(70)); + + assertThatThrownBy(() -> fixture.repository().apply(signed, fixture.trustedKeys(), NAMESPACE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> + fixture + .repository() + .read( + signed.manifest().operationId(), + signed.manifest().canonicalTenantId(), + signed.manifest().legacyGameSessionTenantIdValue(), + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThatThrownBy(() -> fixture.apply(signed, "another-namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("different namespace"); + Signed malformedSignature = + new Signed(signed.manifest(), signed.ed25519Signature().substring(0, 84) + "AA=="); + assertThatThrownBy(() -> fixture.apply(malformedSignature, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature"); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isZero(); + + AssociationReceipt committed = fixture.apply(signed, NAMESPACE); + assertThat(fixture.read(committed)).contains(committed); + assertThat( + fixture + .repository() + .read( + uuid(71), + committed.manifest().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue(), + NAMESPACE)) + .isEmpty(); + assertThat( + fixture + .repository() + .read( + committed.manifest().operationId(), + fixture.retainedSource().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue(), + NAMESPACE)) + .isEmpty(); + assertThat( + fixture + .repository() + .read( + committed.manifest().operationId(), + committed.manifest().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue() + 1, + NAMESPACE)) + .isEmpty(); + assertThat( + fixture + .repository() + .read( + committed.manifest().operationId(), + committed.manifest().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue(), + "another-namespace")) + .isEmpty(); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInsert() + throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + AssociationReceipt receipt = + fixture.apply(fixture.signed(fixture.freshSource(), 980L, uuid(80)), NAMESPACE); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(ASSOCIATIONS) + .set(APPROVED_BY, "changed-owner") + .where(OPERATION_ID.eq(receipt.manifest().operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .deleteFrom(ASSOCIATIONS) + .where(OPERATION_ID.eq(receipt.manifest().operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("TRUNCATE game_design_game_session_tenant_association_operations")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .insertInto(ASSOCIATIONS) + .set(OPERATION_ID, uuid(81)) + .set(DSL.field(DSL.name("schema_version"), Integer.class), 1) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set(DSL.field(DSL.name("signer_key_id"), String.class), SIGNER_KEY_ID) + .set(DSL.field(DSL.name("approved_by"), String.class), "owner@example.test") + .set( + DSL.field(DSL.name("approval_reference"), String.class), + "source-contradiction-test") + .set(DSL.field(DSL.name("signed_at"), String.class), "2026-10-01T00:00:00Z") + .set(DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class), 981L) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + receipt.manifest().canonicalTenantId()) + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshSource().sourceGameId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "contradictory-source-key") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .set( + DSL.field(DSL.name("game_session_evidence_digest"), String.class), + GAME_SESSION_EVIDENCE_DIGEST) + .set( + DSL.field(DSL.name("manifest_digest"), String.class), + receipt.manifestDigest()) + .set(DSL.field(DSL.name("signature"), String.class), receipt.ed25519Signature()) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its Game Design row"); + + assertThat(fixture.read(receipt)).contains(receipt); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + private AssociationReceipt concurrentApply( + Fixture fixture, Signed signed, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return fixture.apply(signed, NAMESPACE); + } + + private Fixture fixtureWithFreshAndRetainedSources() throws Exception { + String schema = "game_design_gs_assoc_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("29")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-game-design-owner-source") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Persisted before canonical tenant identities") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameSessionTenantAssociationRepository repository = + new GameSessionTenantAssociationRepository(dsl, gameRepository); + UUID retainedCanonicalTenantId = + dsl.select(DSL.field(DSL.name("canonical_tenant_id"), UUID.class)) + .from(GAME) + .where(GAME_ID.eq(retainedGameId)) + .fetchOne(DSL.field(DSL.name("canonical_tenant_id"), UUID.class)); + GameTenantIdentity retainedSource = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId(retainedCanonicalTenantId) + .orElseThrow(); + + Game freshGame = new Game(); + freshGame.setTenantId("fresh-game-design-owner-source"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Persisted after canonical tenant identities"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + GameTenantIdentity freshSource = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId( + Objects.requireNonNull(persistedFreshGame).getCanonicalTenantId()) + .orElseThrow(); + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + Map trustedKeys = + Map.of( + SIGNER_KEY_ID, Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + return new Fixture( + dsl, repository, transactionTemplate, ownerKey, trustedKeys, retainedSource, freshSource); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private GameSessionTenantAssociationEvidence withApprovalReference( + GameSessionTenantAssociationEvidence original, String approvalReference) { + return new GameSessionTenantAssociationEvidence( + original.schemaVersion(), + original.operationId(), + original.targetNamespace(), + original.signerKeyId(), + original.approvedBy(), + approvalReference, + original.signedAt(), + original.legacyGameSessionTenantId(), + original.canonicalTenantId(), + original.sourceGameRowId(), + original.sourceGameTenantKey(), + original.provenanceKind(), + original.gameSessionEvidenceDigest()); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-2222-4222-8222-222222222222", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent association apply"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent association apply", exception); + } + } + + private record Fixture( + DSLContext dsl, + GameSessionTenantAssociationRepository repository, + TransactionTemplate transactionTemplate, + KeyPair ownerKey, + Map trustedKeys, + GameTenantIdentity retainedSource, + GameTenantIdentity freshSource) { + Signed signed(GameTenantIdentity source, long retainedGameSessionTenantId, UUID operationId) + throws Exception { + return sign( + evidence( + operationId, + retainedGameSessionTenantId, + source.canonicalTenantId(), + source.sourceGameId(), + source.sourceLegacyTenantId(), + source.provenanceKind().name())); + } + + GameSessionTenantAssociationEvidence evidence( + UUID operationId, + long retainedGameSessionTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + return new GameSessionTenantAssociationEvidence( + 1, + operationId, + NAMESPACE, + SIGNER_KEY_ID, + "approved-owner@example.test", + "retained-session-audit-" + operationId, + "2026-10-01T00:00:00Z", + Long.toString(retainedGameSessionTenantId), + canonicalTenantId, + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind, + GAME_SESSION_EVIDENCE_DIGEST); + } + + Signed sign(GameSessionTenantAssociationEvidence manifest) throws Exception { + Signature signer = Signature.getInstance("Ed25519"); + signer.initSign(ownerKey.getPrivate()); + signer.update(manifest.preimage()); + return new Signed(manifest, Base64.getEncoder().encodeToString(signer.sign())); + } + + AssociationReceipt apply(Signed signed, String exactNamespace) { + AssociationReceipt receipt = + transactionTemplate.execute( + status -> repository.apply(signed, trustedKeys, exactNamespace)); + return Objects.requireNonNull(receipt); + } + + Optional read(AssociationReceipt receipt) { + return repository.read( + receipt.manifest().operationId(), + receipt.manifest().canonicalTenantId(), + receipt.manifest().legacyGameSessionTenantIdValue(), + receipt.manifest().targetNamespace()); + } + + String gameXmin(long gameId) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId) + .getFirst() + .get("xmin", String.class); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java new file mode 100644 index 0000000000..4bf2023132 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java @@ -0,0 +1,474 @@ +package unit.net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Signed; +import org.junit.jupiter.api.Test; + +class GameSessionTenantAssociationManifestVerifierTest { + @Test + void verifiesExactOwnerSignedReadbackAndRecomputesDigest() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence manifest = evidence(); + Map trustedKeys = trustedKeys("owner-key-2026", ownerKey); + Signed signed = signed(manifest, ownerKey); + + var verified = GameSessionTenantAssociationManifestVerifier.verify(signed, trustedKeys); + assertThat(verified.manifest()).isEqualTo(manifest); + assertThat(verified.manifestDigest()).isEqualTo(manifest.manifestDigest()); + assertThat(GameSessionTenantAssociationManifestVerifier.verify(signed, trustedKeys)) + .isEqualTo(verified); + } + + @Test + void everyMutableManifestFieldIsSignatureBound() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence manifest = evidence(); + Signed signed = signed(manifest, ownerKey); + String publicKey = Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded()); + Map trustedKeys = + Map.of("owner-key-2026", publicKey, "owner-key-2027", publicKey); + + for (GameSessionTenantAssociationEvidence changed : changedFields(manifest)) { + assertThat(changed.preimage()).isNotEqualTo(manifest.preimage()); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(changed, signed.ed25519Signature()), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + } + assertThatThrownBy(() -> copyWithSchemaVersion(manifest, 2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schema version"); + } + + @Test + void rejectsAbsentUntrustedWrongPurposeMalformedAndInvalidSignatures() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair unrelatedKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence manifest = evidence(); + Signed signed = signed(manifest, ownerKey); + Map trustedKeys = trustedKeys("owner-key-2026", ownerKey); + + assertThatThrownBy(() -> GameSessionTenantAssociationManifestVerifier.verify(null, trustedKeys)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(null, signed.ed25519Signature()), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> GameSessionTenantAssociationManifestVerifier.verify(signed, Map.of())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not trusted"); + + GameSessionTenantAssociationEvidence wrongPurpose = + copyWithSignerKeyId(manifest, "account-owner-key"); + Signed accountPurposeSignature = signed(wrongPurpose, unrelatedKey); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + accountPurposeSignature, trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not trusted"); + + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + signed, Map.of("owner-key-2026", "not base64"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + signed, + Map.of("owner-key-2026", Base64.getEncoder().encodeToString(new byte[32])))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot be verified"); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(manifest, "%%%"), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(manifest, Base64.getEncoder().encodeToString(new byte[63])), + trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("64-byte"); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + signed(manifest, unrelatedKey), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + } + + @Test + void rejectsSignatureOverDistinctAccountAssociationDomain() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence gameSessionManifest = evidence(); + Map trustedKeys = trustedKeys("owner-key-2026", ownerKey); + Signed correctDomainSignature = signed(gameSessionManifest, ownerKey); + assertThat( + GameSessionTenantAssociationManifestVerifier.verify(correctDomainSignature, trustedKeys) + .manifest()) + .isEqualTo(gameSessionManifest); + + byte[] correctDomainPreimage = gameSessionManifest.preimage(); + byte[] accountAssociationPreimage = + replaceFirstLengthFramedSegment( + correctDomainPreimage, "account/game-session-tenant-association/v1"); + assertThat(bytesAfterFirstLengthFramedSegment(accountAssociationPreimage)) + .isEqualTo(bytesAfterFirstLengthFramedSegment(correctDomainPreimage)); + + Signature accountAssociationSigner = Signature.getInstance("Ed25519"); + accountAssociationSigner.initSign(ownerKey.getPrivate()); + accountAssociationSigner.update(accountAssociationPreimage); + Signed wrongDomainSignature = + new Signed( + gameSessionManifest, + Base64.getEncoder().encodeToString(accountAssociationSigner.sign())); + + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + wrongDomainSignature, trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + } + + private static byte[] replaceFirstLengthFramedSegment(byte[] source, String replacement) { + int colonIndex = 0; + while (source[colonIndex] != ':') { + colonIndex++; + } + int originalLength = + Integer.parseInt(new String(source, 0, colonIndex, StandardCharsets.US_ASCII)); + int suffixStart = colonIndex + 1 + originalLength; + byte[] replacementBytes = replacement.getBytes(StandardCharsets.UTF_8); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + output.writeBytes( + Integer.toString(replacementBytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(replacementBytes); + output.write(source, suffixStart, source.length - suffixStart); + return output.toByteArray(); + } + + private static byte[] bytesAfterFirstLengthFramedSegment(byte[] source) { + int colonIndex = 0; + while (source[colonIndex] != ':') { + colonIndex++; + } + int firstSegmentLength = + Integer.parseInt(new String(source, 0, colonIndex, StandardCharsets.US_ASCII)); + return Arrays.copyOfRange(source, colonIndex + 1 + firstSegmentLength, source.length); + } + + private static GameSessionTenantAssociationEvidence evidence() { + return new GameSessionTenantAssociationEvidence( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "firemud", + "owner-key-2026", + "owner 🧙", + "review café-🐉", + Instant.parse("2026-10-01T00:00:00Z").toString(), + "9007199254740993", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "42", + "legacy-game-key-42", + "RETAINED_GAME_V29", + "sha256:" + "a".repeat(64)); + } + + private static java.util.List changedFields( + GameSessionTenantAssociationEvidence source) { + return java.util.List.of( + copy(source, "9007199254740994", source.sourceGameRowId()), + copyWithTargetNamespace(source, "firemud-dev"), + copyWithSignerKeyId(source, "owner-key-2027"), + copyWithApproval(source, "another owner", source.approvalReference()), + copyWithApproval(source, source.approvedBy(), "another-review-reference"), + copyWithSignedAt(source, "2026-10-01T00:00:01Z"), + copyWithOperationId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), + copyWithTenantId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), + copy(source, source.legacyGameSessionTenantId(), "43"), + copyWithSourceGameTenantKey(source, "another-source-key"), + copyWithProvenanceKind(source, "NEW_GAME_ROW"), + copyWithGameSessionEvidenceDigest(source, "sha256:" + "b".repeat(64))); + } + + private static Map trustedKeys(String keyId, KeyPair keyPair) { + return Map.of(keyId, Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); + } + + private static Signed signed(GameSessionTenantAssociationEvidence manifest, KeyPair keyPair) + throws Exception { + Signature signer = Signature.getInstance("Ed25519"); + signer.initSign(keyPair.getPrivate()); + signer.update(manifest.preimage()); + return new Signed(manifest, Base64.getEncoder().encodeToString(signer.sign())); + } + + private static GameSessionTenantAssociationEvidence copy( + GameSessionTenantAssociationEvidence source, + String legacyGameSessionTenantId, + String sourceGameRowId) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + legacyGameSessionTenantId, + source.canonicalTenantId(), + sourceGameRowId, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSchemaVersion( + GameSessionTenantAssociationEvidence source, int schemaVersion) { + return make( + source, + schemaVersion, + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithTargetNamespace( + GameSessionTenantAssociationEvidence source, String targetNamespace) { + return make( + source, + source.schemaVersion(), + source.operationId(), + targetNamespace, + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSignerKeyId( + GameSessionTenantAssociationEvidence source, String signerKeyId) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + signerKeyId, + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithOperationId( + GameSessionTenantAssociationEvidence source, UUID operationId) { + return make( + source, + source.schemaVersion(), + operationId, + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithApproval( + GameSessionTenantAssociationEvidence source, String approvedBy, String approvalReference) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + approvedBy, + approvalReference, + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSignedAt( + GameSessionTenantAssociationEvidence source, String signedAt) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + signedAt, + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithTenantId( + GameSessionTenantAssociationEvidence source, UUID canonicalTenantId) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + canonicalTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSourceGameTenantKey( + GameSessionTenantAssociationEvidence source, String sourceGameTenantKey) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + sourceGameTenantKey, + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithProvenanceKind( + GameSessionTenantAssociationEvidence source, String provenanceKind) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + provenanceKind, + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithGameSessionEvidenceDigest( + GameSessionTenantAssociationEvidence source, String gameSessionEvidenceDigest) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + gameSessionEvidenceDigest); + } + + private static GameSessionTenantAssociationEvidence make( + GameSessionTenantAssociationEvidence source, + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + String legacyGameSessionTenantId, + UUID canonicalTenantId, + String sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String gameSessionEvidenceDigest) { + return new GameSessionTenantAssociationEvidence( + schemaVersion, + operationId, + targetNamespace, + signerKeyId, + approvedBy, + approvalReference, + signedAt, + legacyGameSessionTenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + gameSessionEvidenceDigest); + } + + private static GameSessionTenantAssociationEvidence copyWithProvenance( + GameSessionTenantAssociationEvidence source, String provenanceKind) { + return copyWithProvenanceKind(source, provenanceKind); + } +} 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 91007bb76b..0b1c968fc7 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 @@ -24,6 +24,7 @@ import net.firedevops.firemud.common.security.AuthTokenInterceptor; import net.firedevops.firemud.common.security.GrpcAuthProperties; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; import net.firedevops.firemud.gamedesign.v1.PingRequest; @@ -42,6 +43,8 @@ class TenantIdentityGrpcAuthWiringTest { private static final String TENANT_METHOD = "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity"; + private static final String ASSOCIATION_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"; private static final String PING_METHOD = "gamedesign.v1.GameDesignService/Ping"; private static final String TENANT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; @@ -70,7 +73,9 @@ void noTokenWithValidSameNamespacePeerReachesTenantIdentityService() { GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, 42L, "legacy-owner-key-42"))); - TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + repository, mock(GameSessionTenantAssociationRepository.class), "test"); DispatchResult result = dispatchTenantMethod(interceptor, service, GAME_SESSION_URI); @@ -87,7 +92,9 @@ void noTokenWithAbsentOrWrongPeerIsDeniedBeforeOwnerRead() { withConfiguredInterceptor( interceptor -> { GameRepository repository = mock(GameRepository.class); - TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + repository, mock(GameSessionTenantAssociationRepository.class), "test"); DispatchResult absent = dispatchTenantMethod(interceptor, service, null); DispatchResult wrong = @@ -200,7 +207,7 @@ private static void withConfiguredInterceptor( context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(TENANT_METHOD); + .containsExactly(TENANT_METHOD, ASSOCIATION_METHOD); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java new file mode 100644 index 0000000000..e1f52c1a3b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Base64; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class GameSessionTenantAssociationGrpcTest { + private static final UUID OPERATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String READ_REQUEST = "33333333-3333-4333-8333-333333333333"; + private static final String GAME_SESSION = "spiffe://firemud/ns/test/sa/game-session-service"; + private final GameSessionTenantAssociationRepository repository = + mock(GameSessionTenantAssociationRepository.class); + private final TenantIdentityGrpcService service = + new TenantIdentityGrpcService(mock(GameRepository.class), repository, "test"); + + @Test + void exactGameSessionPeerPrecedesSyntaxAndOwnerReads() { + for (String peer : + new String[] { + null, + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service" + }) { + Observer observer = + call(ResolveLegacyGameSessionTenantAssociationRequest.getDefaultInstance(), peer); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + verifyNoInteractions(repository); + } + + @Test + void aliasesOverflowNilAndUnknownFieldsDenyBeforeOwnerAccess() { + for (String key : new String[] {"", "0", "01", "-1", "1.0", "9223372036854775808", " 41"}) { + assertThat( + call(request().toBuilder().setLegacyGameSessionTenantId(key).build(), GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + assertThat( + call( + request().toBuilder() + .setOperationId("00000000-0000-0000-0000-000000000000") + .build(), + GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + request().toBuilder() + .setRequestId("33333333-3333-4333-8333-33333333333") + .build(), + GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(), + GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void exactReadCarriesCompleteImmutableManifestAndSeparateReadEcho() { + GameSessionTenantAssociationEvidence evidence = evidence(); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenReturn( + Optional.of(new AssociationReceipt(evidence, signature, evidence.manifestDigest()))); + Observer observer = call(request(), GAME_SESSION); + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getRequestId()).isEqualTo(READ_REQUEST); + var manifest = observer.value.getManifest(); + assertThat(manifest.getSchemaVersion()).isEqualTo(1); + assertThat(manifest.getOperationId()).isEqualTo(OPERATION.toString()); + assertThat(manifest.getTargetNamespace()).isEqualTo("test"); + assertThat(manifest.getSignerKeyId()).isEqualTo(evidence.signerKeyId()); + assertThat(manifest.getApprovedBy()).isEqualTo(evidence.approvedBy()); + assertThat(manifest.getApprovalReference()).isEqualTo(evidence.approvalReference()); + assertThat(manifest.getSignedAt()).isEqualTo(evidence.signedAt()); + assertThat(manifest.getLegacyGameSessionTenantId()).isEqualTo("41"); + assertThat(manifest.getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(manifest.getSourceGameRowId()).isEqualTo(evidence.sourceGameRowId()); + assertThat(manifest.getSourceGameTenantKey()).isEqualTo(evidence.sourceGameTenantKey()); + assertThat(manifest.getProvenanceKind()).isEqualTo(evidence.provenanceKind()); + assertThat(manifest.getGameSessionEvidenceDigest()) + .isEqualTo(evidence.gameSessionEvidenceDigest()); + assertThat(observer.value.getManifestDigest()).isEqualTo(evidence.manifestDigest()); + assertThat(observer.value.getEd25519Signature()).isEqualTo(signature); + } + + @Test + void absentContradictoryAndUnavailableEvidenceNeverReturnsPartialContent() { + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenReturn(Optional.empty()) + .thenThrow(new IllegalStateException("contradictory stored evidence")) + .thenThrow(new org.jooq.exception.DataAccessException("storage unavailable")); + assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.NOT_FOUND); + assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.FAILED_PRECONDITION); + Observer unavailable = call(request(), GAME_SESSION); + assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.value).isNull(); + assertThat(unavailable.completed).isFalse(); + } + + @Test + void changedReadScopeDigestAndSignatureDenyWithoutPartialContent() { + GameSessionTenantAssociationEvidence exact = evidence(); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + for (AssociationReceipt wrong : + new AssociationReceipt[] { + receipt(withScope(UUID.randomUUID(), TENANT, "test", "41"), signature), + receipt(withScope(OPERATION, UUID.randomUUID(), "test", "41"), signature), + receipt(withScope(OPERATION, TENANT, "other", "41"), signature), + receipt(withScope(OPERATION, TENANT, "test", "42"), signature), + new AssociationReceipt(exact, signature, "sha256:" + "b".repeat(64)), + new AssociationReceipt(exact, "invalid-signature", exact.manifestDigest()) + }) { + when(repository.read(OPERATION, TENANT, 41L, "test")).thenReturn(Optional.of(wrong)); + Observer observer = call(request(), GAME_SESSION); + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + } + + @Test + void productionAndDefaultBearerBypassKeepExactProtectedSourceReadsAligned() throws Exception { + Set required = + Set.of( + "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity", + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"); + for (String name : new String[] {"application.yml", "application-prod.yml"}) { + Set methods = new HashSet<>(); + for (PropertySource source : + new YamlPropertySourceLoader() + .load(name, new FileSystemResource("src/main/resources/" + name))) { + for (int index = 0; index < 20; index++) { + Object method = source.getProperty("firemud.auth.grpc.public-methods[" + index + "]"); + if (method != null) { + methods.add(method.toString()); + } + } + } + assertThat(methods).containsAll(required); + } + } + + private ResolveLegacyGameSessionTenantAssociationRequest request() { + return ResolveLegacyGameSessionTenantAssociationRequest.newBuilder() + .setRequestId(READ_REQUEST) + .setOperationId(OPERATION.toString()) + .setCanonicalTenantId(TENANT.toString()) + .setLegacyGameSessionTenantId("41") + .build(); + } + + private GameSessionTenantAssociationEvidence evidence() { + return new GameSessionTenantAssociationEvidence( + 1, + OPERATION, + "test", + "owner-key", + "owner", + "approval-41", + "2026-10-01T00:00:00Z", + "41", + TENANT, + "7", + "source-key", + "RETAINED_GAME_V29", + "sha256:" + "a".repeat(64)); + } + + private GameSessionTenantAssociationEvidence withScope( + UUID operation, UUID tenant, String namespace, String legacyKey) { + GameSessionTenantAssociationEvidence source = evidence(); + return new GameSessionTenantAssociationEvidence( + source.schemaVersion(), + operation, + namespace, + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + legacyKey, + tenant, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private AssociationReceipt receipt( + GameSessionTenantAssociationEvidence manifest, String signature) { + return new AssociationReceipt(manifest, signature, manifest.manifestDigest()); + } + + private Observer call(ResolveLegacyGameSessionTenantAssociationRequest request, String peer) { + Observer observer = new Observer(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + peer == null ? null : GrpcPeerIdentity.parseUri(peer).orElseThrow()) + .run(() -> service.resolveLegacyGameSessionTenantAssociation(request, observer)); + return observer; + } + + private static final class Observer + implements StreamObserver { + private ResolveLegacyGameSessionTenantAssociationResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ResolveLegacyGameSessionTenantAssociationResponse value) { + this.value = value; + } + + @Override + public void onError(Throwable error) { + this.error = Status.fromThrowable(error).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index 79336c6cce..2add931163 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -15,6 +15,7 @@ import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; @@ -28,8 +29,10 @@ class TenantIdentityGrpcServiceTest { private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private final GameRepository repository = mock(GameRepository.class); + private final GameSessionTenantAssociationRepository associationRepository = + mock(GameSessionTenantAssociationRepository.class); private final TenantIdentityGrpcService service = - new TenantIdentityGrpcService(repository, "test"); + new TenantIdentityGrpcService(repository, associationRepository, "test"); @Test void resolvesExactOwnerIdentityForAuthenticatedGameSessionPeer() { @@ -74,11 +77,13 @@ void rejectsUnauthenticatedWrongNamespaceAndWrongServiceBeforeOwnerRead() { "spiffe://firemud/ns/test/sa/account-service"))) .isEqualTo(Status.Code.PERMISSION_DENIED); verifyNoInteractions(repository); + verifyNoInteractions(associationRepository); } @Test void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { - TenantIdentityGrpcService inactiveService = new TenantIdentityGrpcService(repository, ""); + TenantIdentityGrpcService inactiveService = + new TenantIdentityGrpcService(repository, associationRepository, ""); TestObserver observer = new TestObserver(); GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java index 2eb99d9bcf..6e76306598 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java @@ -2,6 +2,7 @@ import io.grpc.ManagedChannel; import java.io.IOException; +import java.util.Base64; import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -11,7 +12,10 @@ 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.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -21,9 +25,16 @@ public final class GameDesignRuntimeTenantIdentityClient extends AbstractReloadingBlockingGrpcClient< TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; + private static final int ED25519_SIGNATURE_BYTES = 64; private final String workloadNamespace; + /** Validated owner evidence; it does not prove retained-row agreement or catalog admission. */ + public record LegacyGameSessionTenantAssociationReceipt( + GameSessionTenantAssociationEvidence evidence, + String manifestDigest, + String ed25519Signature) {} + public GameDesignRuntimeTenantIdentityClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, @@ -118,6 +129,121 @@ public RuntimeTenantIdentityEvidence resolveRuntimeTenantIdentity( return evidence; } + /** + * Reads one exact approved retained Game Session association through the authenticated Game + * Design workload channel. This validates owner evidence only; it does not inspect or persist + * Game Session's retained rows, enroll a catalog entry, or grant admission. + */ + public LegacyGameSessionTenantAssociationReceipt resolveLegacyGameSessionTenantAssociation( + String canonicalTenantId, + String operationId, + String legacyGameSessionTenantId, + String requestId) { + UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); + UUID operationUuid = parseCanonicalNonNilUuid(operationId, "operation ID"); + String retainedTenantKey = + parseCanonicalPositiveBigint(legacyGameSessionTenantId, "legacy Game Session tenant ID"); + UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association client is not initialized"); + } + + ResolveLegacyGameSessionTenantAssociationResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveLegacyGameSessionTenantAssociation( + ResolveLegacyGameSessionTenantAssociationRequest.newBuilder() + .setRequestId(requestUuid.toString()) + .setOperationId(operationUuid.toString()) + .setCanonicalTenantId(tenantUuid.toString()) + .setLegacyGameSessionTenantId(retainedTenantKey) + .build()); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response contains " + + "unsupported fields"); + } + if (!response.hasManifest()) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response has no manifest"); + } + UUID echoedRequestId; + try { + echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response request echo is invalid", + exception); + } + if (!requestUuid.equals(echoedRequestId)) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response does not match " + + "the exact request echo"); + } + + var manifest = response.getManifest(); + if (!manifest.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association manifest contains " + + "unsupported fields"); + } + GameSessionTenantAssociationEvidence evidence; + try { + evidence = + new GameSessionTenantAssociationEvidence( + manifest.getSchemaVersion(), + parseCanonicalNonNilUuid(manifest.getOperationId(), "manifest operation ID"), + manifest.getTargetNamespace(), + manifest.getSignerKeyId(), + manifest.getApprovedBy(), + manifest.getApprovalReference(), + manifest.getSignedAt(), + manifest.getLegacyGameSessionTenantId(), + parseCanonicalNonNilUuid( + manifest.getCanonicalTenantId(), "manifest canonical tenant ID"), + manifest.getSourceGameRowId(), + manifest.getSourceGameTenantKey(), + manifest.getProvenanceKind(), + manifest.getGameSessionEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association manifest is invalid", exception); + } + + String signature = response.getEd25519Signature(); + byte[] signatureBytes; + try { + signatureBytes = Base64.getDecoder().decode(signature); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association signature is invalid", exception); + } + if (signatureBytes.length != ED25519_SIGNATURE_BYTES + || !Base64.getEncoder().encodeToString(signatureBytes).equals(signature)) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association signature is not canonical " + + "Ed25519 base64"); + } + + String manifestDigest = response.getManifestDigest(); + if (!evidence.manifestDigest().equals(manifestDigest)) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association manifest digest does not match " + + "its evidence"); + } + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !operationUuid.equals(evidence.operationId()) + || !tenantUuid.equals(evidence.canonicalTenantId()) + || !retainedTenantKey.equals(evidence.legacyGameSessionTenantId())) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response does not match " + + "the exact request"); + } + return new LegacyGameSessionTenantAssociationReceipt(evidence, manifestDigest, signature); + } + private static UUID parseCanonicalNonNilUuid(String value, String label) { if (value == null) { throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); @@ -134,6 +260,22 @@ private static UUID parseCanonicalNonNilUuid(String value, String label) { return parsed; } + private static String parseCanonicalPositiveBigint(String value, String label) { + if (value == null || value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + label + " must fit a positive PostgreSQL BIGINT", exception); + } + return value; + } + private static CommonGrpcClientProperties requireGameSessionMtls( CommonGrpcClientProperties tlsProps) { if (tlsProps == null) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java new file mode 100644 index 0000000000..c68a76c97e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java @@ -0,0 +1,530 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired immutable local receipt for an approved association to retained Game Session rows. + * + *

The Game Design receipt is obtained by the service before the owner transaction begins. This + * repository only commits it after the local retained-row snapshot has been recaptured under its + * source fence. + */ +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Owner collaborators and namespace are validated before use; construction performs no" + + " database or network I/O and the caller explicitly owns local activation.") +public class GameSessionRetainedTenantAssociationRepository { + private static final int SCHEMA_VERSION = 1; + private static final int SIGNATURE_BYTES = 64; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DOMAIN = + "game-session/retained-tenant-association-request/v1"; + private static final String RECEIPT_DOMAIN = + "game-session/retained-tenant-association-receipt/v1"; + + private static final Table ASSOCIATION = + DSL.table(DSL.name("game_session_retained_tenant_association")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field APPROVAL_SCHEMA_VERSION = + DSL.field(DSL.name("approval_schema_version"), Integer.class); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field ASSOCIATION_REQUEST_ID = + DSL.field(DSL.name("association_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field APPROVAL_OPERATION_ID = + DSL.field(DSL.name("approval_operation_id"), UUID.class); + private static final Field SIGNER_KEY_ID = + DSL.field(DSL.name("signer_key_id"), String.class); + private static final Field APPROVED_BY = DSL.field(DSL.name("approved_by"), String.class); + private static final Field APPROVAL_REFERENCE = + DSL.field(DSL.name("approval_reference"), String.class); + private static final Field SIGNED_AT = DSL.field(DSL.name("signed_at"), String.class); + private static final Field LEGACY_GAME_SESSION_TENANT_ID = + DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field GAME_SESSION_EVIDENCE_DIGEST = + DSL.field(DSL.name("game_session_evidence_digest"), String.class); + private static final Field APPROVAL_MANIFEST_DIGEST = + DSL.field(DSL.name("approval_manifest_digest"), String.class); + private static final Field APPROVAL_SIGNATURE = + DSL.field(DSL.name("approval_signature"), String.class); + private static final Field SNAPSHOT_CANONICAL_JSON = + DSL.field(DSL.name("snapshot_canonical_json"), String.class); + private static final Field SNAPSHOT_EVIDENCE_DIGEST = + DSL.field(DSL.name("snapshot_evidence_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + + private final DSLContext dsl; + private final GameSessionRetainedTenantSnapshotRepository snapshotRepository; + private final String workloadNamespace; + + public GameSessionRetainedTenantAssociationRepository( + DSLContext dsl, + GameSessionRetainedTenantSnapshotRepository snapshotRepository, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.snapshotRepository = + Objects.requireNonNull(snapshotRepository, "snapshotRepository must not be null"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * Captures and commits one exact retained-tenant association under the caller's owner + * transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AssociationReceipt register( + UUID associationRequestId, LegacyGameSessionTenantAssociationReceipt sourceReceipt) { + requireWritableReadCommittedOwnerTransaction(); + requireNonNil(associationRequestId, "associationRequestId"); + ValidatedApproval approval = validateApproval(sourceReceipt); + GameSessionTenantAssociationEvidence evidence = approval.evidence(); + if (!workloadNamespace.equals(evidence.targetNamespace())) { + throw new InvalidAssociationEvidenceException( + "Game Design approval targets a different Game Session namespace"); + } + + String requestDigest = + requestDigest( + workloadNamespace, + associationRequestId, + approval.manifestDigest(), + approval.signature()); + Record existing = findByRequest(workloadNamespace, associationRequestId); + if (existing != null) { + return requireExactRetry(existing, associationRequestId, requestDigest, approval); + } + + GameSessionRetainedTenantSnapshot snapshot = + snapshotRepository.capture(workloadNamespace, evidence.legacyGameSessionTenantId()); + requireSnapshotMatchesApproval(snapshot, evidence); + + UUID localOperationId = UUID.randomUUID(); + String receiptDigest = + receiptDigest( + localOperationId, requestDigest, approval.manifestDigest(), snapshot.evidenceDigest()); + int inserted = + dsl.insertInto(ASSOCIATION) + .set(OPERATION_ID, localOperationId) + .set(APPROVAL_SCHEMA_VERSION, evidence.schemaVersion()) + .set(TARGET_NAMESPACE, workloadNamespace) + .set(ASSOCIATION_REQUEST_ID, associationRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(APPROVAL_OPERATION_ID, evidence.operationId()) + .set(SIGNER_KEY_ID, evidence.signerKeyId()) + .set(APPROVED_BY, evidence.approvedBy()) + .set(APPROVAL_REFERENCE, evidence.approvalReference()) + .set(SIGNED_AT, evidence.signedAt()) + .set(LEGACY_GAME_SESSION_TENANT_ID, evidence.legacyGameSessionTenantIdValue()) + .set(CANONICAL_TENANT_ID, evidence.canonicalTenantId()) + .set(SOURCE_GAME_ROW_ID, evidence.sourceGameRowIdValue()) + .set(SOURCE_GAME_TENANT_KEY, evidence.sourceGameTenantKey()) + .set(PROVENANCE_KIND, evidence.provenanceKind()) + .set(GAME_SESSION_EVIDENCE_DIGEST, evidence.gameSessionEvidenceDigest()) + .set(APPROVAL_MANIFEST_DIGEST, approval.manifestDigest()) + .set(APPROVAL_SIGNATURE, approval.signature()) + .set(SNAPSHOT_CANONICAL_JSON, snapshot.canonicalJson()) + .set(SNAPSHOT_EVIDENCE_DIGEST, snapshot.evidenceDigest()) + .set(RECEIPT_DIGEST, receiptDigest) + .onConflictDoNothing() + .execute(); + + Record byLocalOperation = findByOperationId(localOperationId); + if (byLocalOperation != null) { + AssociationReceipt stored = toValidatedReceipt(byLocalOperation); + requireExactInsertedReceipt(stored, associationRequestId, requestDigest, approval, snapshot); + return stored; + } + + Record racedRequest = findByRequest(workloadNamespace, associationRequestId); + if (racedRequest != null) { + return requireExactRetry(racedRequest, associationRequestId, requestDigest, approval); + } + if (inserted == 1) { + throw new InvalidAssociationEvidenceException( + "Committed retained-tenant association readback is missing"); + } + throw new AssociationConflictException( + "Canonical tenant or retained Game Session key is already associated"); + } + + /** Reads one exact committed association without source recapture, repair, or allocation. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID localOperationId, + UUID associationRequestId, + UUID canonicalTenantId, + long legacyGameSessionTenantId, + String exactNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association read requires a committed-outcome owner read"); + } + requireNonNil(localOperationId, "localOperationId"); + requireNonNil(associationRequestId, "associationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requirePositive(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + requireNamespace(exactNamespace); + if (!workloadNamespace.equals(exactNamespace)) { + throw new IllegalArgumentException( + "exactNamespace must match the configured Game Session workload namespace"); + } + + Record row = findByOperationId(localOperationId); + if (row != null) { + AssociationReceipt receipt = toValidatedReceipt(row); + if (!receipt.operationId().equals(localOperationId) + || !receipt.associationRequestId().equals(associationRequestId) + || !receipt.approval().canonicalTenantId().equals(canonicalTenantId) + || receipt.approval().legacyGameSessionTenantIdValue() != legacyGameSessionTenantId + || !receipt.approval().targetNamespace().equals(exactNamespace)) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant association readback contradicts its exact identity request"); + } + return Optional.of(receipt); + } + + if (findByRequest(exactNamespace, associationRequestId) != null + || findByCanonicalTenant(exactNamespace, canonicalTenantId) != null + || findByLegacyKey(exactNamespace, legacyGameSessionTenantId) != null) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant association exists under contradictory local identity"); + } + return Optional.empty(); + } + + private AssociationReceipt requireExactRetry( + Record row, + UUID associationRequestId, + String requestDigest, + ValidatedApproval expectedApproval) { + AssociationReceipt stored = toValidatedReceipt(row); + if (!stored.associationRequestId().equals(associationRequestId) + || !stored.requestDigest().equals(requestDigest) + || !stored.approval().equals(expectedApproval.evidence()) + || !stored.approvalManifestDigest().equals(expectedApproval.manifestDigest()) + || !stored.approvalSignature().equals(expectedApproval.signature())) { + throw new AssociationConflictException( + "Retained-tenant association request was reused with changed signed evidence"); + } + return stored; + } + + private void requireExactInsertedReceipt( + AssociationReceipt actual, + UUID associationRequestId, + String requestDigest, + ValidatedApproval approval, + GameSessionRetainedTenantSnapshot snapshot) { + if (!actual.associationRequestId().equals(associationRequestId) + || !actual.requestDigest().equals(requestDigest) + || !actual.approval().equals(approval.evidence()) + || !actual.approvalManifestDigest().equals(approval.manifestDigest()) + || !actual.approvalSignature().equals(approval.signature()) + || !actual.snapshot().equals(snapshot)) { + throw new InvalidAssociationEvidenceException( + "Committed retained-tenant association differs from its exact registration input"); + } + } + + private AssociationReceipt toValidatedReceipt(Record row) { + try { + UUID localOperationId = Objects.requireNonNull(row.get(OPERATION_ID)); + UUID associationRequestId = Objects.requireNonNull(row.get(ASSOCIATION_REQUEST_ID)); + String namespace = Objects.requireNonNull(row.get(TARGET_NAMESPACE)); + if (!Integer.valueOf(SCHEMA_VERSION).equals(row.get(APPROVAL_SCHEMA_VERSION))) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association schema is unsupported"); + } + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + row.get(APPROVAL_SCHEMA_VERSION), + Objects.requireNonNull(row.get(APPROVAL_OPERATION_ID)), + namespace, + Objects.requireNonNull(row.get(SIGNER_KEY_ID)), + Objects.requireNonNull(row.get(APPROVED_BY)), + Objects.requireNonNull(row.get(APPROVAL_REFERENCE)), + Objects.requireNonNull(row.get(SIGNED_AT)), + Long.toString(Objects.requireNonNull(row.get(LEGACY_GAME_SESSION_TENANT_ID))), + Objects.requireNonNull(row.get(CANONICAL_TENANT_ID)), + Long.toString(Objects.requireNonNull(row.get(SOURCE_GAME_ROW_ID))), + Objects.requireNonNull(row.get(SOURCE_GAME_TENANT_KEY)), + Objects.requireNonNull(row.get(PROVENANCE_KIND)), + Objects.requireNonNull(row.get(GAME_SESSION_EVIDENCE_DIGEST))); + String manifestDigest = Objects.requireNonNull(row.get(APPROVAL_MANIFEST_DIGEST)); + String signature = Objects.requireNonNull(row.get(APPROVAL_SIGNATURE)); + requireSignatureShape(signature); + if (!evidence.manifestDigest().equals(manifestDigest)) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant approval digest does not match its closed manifest"); + } + + GameSessionRetainedTenantSnapshot snapshot = + new GameSessionRetainedTenantSnapshot( + namespace, + evidence.legacyGameSessionTenantId(), + Objects.requireNonNull(row.get(SNAPSHOT_CANONICAL_JSON)), + Objects.requireNonNull(row.get(SNAPSHOT_EVIDENCE_DIGEST))); + requireSnapshotMatchesApproval(snapshot, evidence); + + String requestDigest = Objects.requireNonNull(row.get(REQUEST_DIGEST)); + if (!requestDigest.equals( + requestDigest(namespace, associationRequestId, manifestDigest, signature))) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association request digest is invalid"); + } + String receiptDigest = Objects.requireNonNull(row.get(RECEIPT_DIGEST)); + if (!receiptDigest.equals( + receiptDigest( + localOperationId, requestDigest, manifestDigest, snapshot.evidenceDigest()))) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association receipt digest is invalid"); + } + requireNonNil(localOperationId, "localOperationId"); + requireNonNil(associationRequestId, "associationRequestId"); + return new AssociationReceipt( + localOperationId, + associationRequestId, + requestDigest, + evidence, + manifestDigest, + signature, + snapshot, + receiptDigest); + } catch (InvalidAssociationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association evidence is invalid", exception); + } + } + + private ValidatedApproval validateApproval( + LegacyGameSessionTenantAssociationReceipt sourceReceipt) { + if (sourceReceipt == null || sourceReceipt.evidence() == null) { + throw new InvalidAssociationEvidenceException("Game Design approval receipt is missing"); + } + GameSessionTenantAssociationEvidence source = sourceReceipt.evidence(); + GameSessionTenantAssociationEvidence evidence; + try { + evidence = + new GameSessionTenantAssociationEvidence( + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } catch (RuntimeException exception) { + throw new InvalidAssociationEvidenceException( + "Game Design approval manifest is invalid", exception); + } + String signature = sourceReceipt.ed25519Signature(); + requireSignatureShape(signature); + String manifestDigest = sourceReceipt.manifestDigest(); + if (manifestDigest == null || !evidence.manifestDigest().equals(manifestDigest)) { + throw new InvalidAssociationEvidenceException( + "Game Design approval digest does not match its closed manifest"); + } + return new ValidatedApproval(evidence, manifestDigest, signature); + } + + private void requireSnapshotMatchesApproval( + GameSessionRetainedTenantSnapshot snapshot, GameSessionTenantAssociationEvidence evidence) { + if (snapshot == null + || !workloadNamespace.equals(snapshot.targetNamespace()) + || !evidence.legacyGameSessionTenantId().equals(snapshot.legacyGameSessionTenantId()) + || !evidence.gameSessionEvidenceDigest().equals(snapshot.evidenceDigest())) { + throw new InvalidAssociationEvidenceException( + "Retained Game Session snapshot does not match the approved owner evidence"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association registration requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Retained-tenant association registration requires a writable owner transaction"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Retained-tenant association registration requires writable READ COMMITTED"); + } + } + + private Record findByOperationId(UUID operationId) { + return dsl.selectFrom(ASSOCIATION) + .where(OPERATION_ID.eq(operationId).and(TARGET_NAMESPACE.eq(workloadNamespace))) + .fetchOne(); + } + + private Record findByRequest(String namespace, UUID requestId) { + return dsl.selectFrom(ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(ASSOCIATION_REQUEST_ID.eq(requestId))) + .fetchOne(); + } + + private Record findByCanonicalTenant(String namespace, UUID tenantId) { + return dsl.selectFrom(ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(CANONICAL_TENANT_ID.eq(tenantId))) + .fetchOne(); + } + + private Record findByLegacyKey(String namespace, long legacyKey) { + return dsl.selectFrom(ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(LEGACY_GAME_SESSION_TENANT_ID.eq(legacyKey))) + .fetchOne(); + } + + private static String requestDigest( + String exactNamespace, UUID associationRequestId, String manifestDigest, String signature) { + return framedDigest( + REQUEST_DOMAIN, exactNamespace, associationRequestId.toString(), manifestDigest, signature); + } + + private static String receiptDigest( + UUID localOperationId, + String requestDigest, + String manifestDigest, + String snapshotEvidenceDigest) { + return framedDigest( + RECEIPT_DOMAIN, + localOperationId.toString(), + requestDigest, + manifestDigest, + snapshotEvidenceDigest); + } + + private static String framedDigest(String... segments) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(output.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireSignatureShape(String signature) { + if (signature == null) { + throw new InvalidAssociationEvidenceException("Game Design approval signature is missing"); + } + final byte[] bytes; + try { + bytes = Base64.getDecoder().decode(signature); + } catch (IllegalArgumentException exception) { + throw new InvalidAssociationEvidenceException( + "Game Design approval signature is not canonical Ed25519 base64", exception); + } + if (bytes.length != SIGNATURE_BYTES + || !Base64.getEncoder().encodeToString(bytes).equals(signature)) { + throw new InvalidAssociationEvidenceException( + "Game Design approval signature is not canonical 64-byte Ed25519 base64"); + } + } + + private static void requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("exactNamespace must be one canonical DNS label"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be a positive BIGINT"); + } + } + + private record ValidatedApproval( + GameSessionTenantAssociationEvidence evidence, String manifestDigest, String signature) {} + + /** Complete immutable local evidence; it contains no credential or approval private key. */ + public record AssociationReceipt( + UUID operationId, + UUID associationRequestId, + String requestDigest, + GameSessionTenantAssociationEvidence approval, + String approvalManifestDigest, + String approvalSignature, + GameSessionRetainedTenantSnapshot snapshot, + String receiptDigest) {} + + public static class AssociationConflictException extends RuntimeException { + public AssociationConflictException(String message) { + super(message); + } + } + + public static class InvalidAssociationEvidenceException extends RuntimeException { + public InvalidAssociationEvidenceException(String message) { + super(message); + } + + public InvalidAssociationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java new file mode 100644 index 0000000000..5c880fea9f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java @@ -0,0 +1,528 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Closed, immutable evidence for Game Session's retained-tenant identity projection. */ +public record GameSessionRetainedTenantSnapshot( + String targetNamespace, + String legacyGameSessionTenantId, + String canonicalJson, + String evidenceDigest) { + private static final String DIGEST_DOMAIN = "game-session/retained-tenant-identity-snapshot/v3"; + private static final Pattern CANONICAL_DECIMAL = + Pattern.compile("(?:0|[1-9][0-9]*|-[1-9][0-9]*)"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); + private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private static final Set ENVELOPE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "legacyGameSessionTenantId", + "instances", + "pointers", + "sharedNamespaces", + "backfillIssues", + "pointerEvents", + "preparedUpgrades"); + private static final Set INSTANCE_FIELDS = + Set.of( + "id", + "tenant_id", + "runtime_version", + "script_patch_version", + "owner_account_id", + "status", + "row_version", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "generation_config_revision", + "remap_set_id", + "script_patch_pinned_control_plane_request_id", + "script_pin_epoch"); + private static final Set POINTER_FIELDS = + Set.of( + "id", + "tenant_id", + "game_instance_id", + "world_slug", + "realm_slug", + "pointer_version", + "catalog_revision", + "visible", + "requires_character_selection", + "state_scope", + "character_creation_policy", + "public_production_realm", + "realm_id", + "playable_state_namespace_id"); + private static final Set SHARED_NAMESPACE_FIELDS = + Set.of("tenant_id", "playable_state_namespace_id"); + private static final Set POINTER_EVENT_FIELDS = + Set.of( + "id", + "tenant_id", + "game_instance_id", + "world_slug", + "realm_slug", + "pointer_version", + "visible", + "requires_character_selection", + "state_scope", + "character_creation_policy", + "control_plane_request_id", + "prepared_version_upgrade_id", + "public_production_realm"); + private static final Set PREPARED_UPGRADE_FIELDS = + Set.of( + "id", + "tenant_id", + "preparation_id", + "control_plane_request_id", + "source_game_instance_id", + "source_version_id", + "target_version_id", + "target_launch_descriptor_id", + "remap_set_id", + "result", + "executed_target_game_instance_id", + "executed_pointer_version", + "execution_control_plane_request_id"); + private static final Set NULLABLE_INSTANCE_FIELDS = + Set.of( + "script_patch_version", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "generation_config_revision", + "remap_set_id", + "script_patch_pinned_control_plane_request_id", + "script_pin_epoch"); + private static final Set NULLABLE_POINTER_EVENT_FIELDS = + Set.of("prepared_version_upgrade_id"); + private static final Set NULLABLE_PREPARED_UPGRADE_FIELDS = + Set.of( + "remap_set_id", + "executed_target_game_instance_id", + "executed_pointer_version", + "execution_control_plane_request_id"); + + public GameSessionRetainedTenantSnapshot { + validateIdentity(targetNamespace, legacyGameSessionTenantId); + if (canonicalJson == null) { + throw new IllegalArgumentException("canonicalJson must not be null"); + } + if (evidenceDigest == null || !SHA256.matcher(evidenceDigest).matches()) { + throw new IllegalArgumentException("A canonical SHA-256 digest is required"); + } + validateCanonicalSnapshot(targetNamespace, legacyGameSessionTenantId, canonicalJson); + String expectedDigest = digest(canonicalJson); + if (!expectedDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Retained-tenant snapshot digest does not match its JSON"); + } + } + + /** Revalidates stored canonical JSON and its digest without accepting caller-built maps. */ + public static GameSessionRetainedTenantSnapshot fromCanonicalJson( + String targetNamespace, + String legacyGameSessionTenantId, + String canonicalJson, + String evidenceDigest) { + return new GameSessionRetainedTenantSnapshot( + targetNamespace, legacyGameSessionTenantId, canonicalJson, evidenceDigest); + } + + static GameSessionRetainedTenantSnapshot fromProjection( + String targetNamespace, String legacyGameSessionTenantId, ObjectNode projection) { + validateIdentity(targetNamespace, legacyGameSessionTenantId); + if (projection == null) { + throw new IllegalArgumentException("projection must not be null"); + } + String canonicalJson = canonicalize(projection); + return new GameSessionRetainedTenantSnapshot( + targetNamespace, legacyGameSessionTenantId, canonicalJson, digest(canonicalJson)); + } + + static void validateIdentity(String targetNamespace, String legacyGameSessionTenantId) { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + BigInteger tenantId = parseDecimal(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + if (tenantId.signum() <= 0 || tenantId.compareTo(LONG_MAX) > 0) { + throw new IllegalArgumentException("legacyGameSessionTenantId must be a positive BIGINT"); + } + } + + private static String canonicalize(ObjectNode projection) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Retained-tenant snapshot is not canonical JSON", exception); + } + } + + private static void validateCanonicalSnapshot( + String targetNamespace, String legacyGameSessionTenantId, String canonicalJson) { + final JsonNode envelope; + final byte[] canonicalBytes; + try { + envelope = JSON.readTree(canonicalJson); + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(canonicalJson); + } catch (IOException exception) { + throw new IllegalArgumentException("Retained-tenant snapshot JSON is malformed", exception); + } + if (envelope == null || !envelope.isObject()) { + throw new IllegalArgumentException("Retained-tenant snapshot must be a JSON object"); + } + if (!Arrays.equals(canonicalBytes, canonicalJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Retained-tenant snapshot JSON is not RFC 8785 canonical"); + } + ObjectNode object = (ObjectNode) envelope; + requireExactFields(object, ENVELOPE_FIELDS, "snapshot"); + JsonNode schemaVersion = object.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != 3) { + throw new IllegalArgumentException("snapshot.schemaVersion must be integer 3"); + } + requireExactText(object, "targetNamespace", targetNamespace, "snapshot"); + requireExactText(object, "legacyGameSessionTenantId", legacyGameSessionTenantId, "snapshot"); + + JsonNode instances = requireArray(object, "instances", "snapshot"); + JsonNode pointers = requireArray(object, "pointers", "snapshot"); + JsonNode sharedNamespaces = requireArray(object, "sharedNamespaces", "snapshot"); + JsonNode backfillIssues = requireArray(object, "backfillIssues", "snapshot"); + JsonNode pointerEvents = requireArray(object, "pointerEvents", "snapshot"); + JsonNode preparedUpgrades = requireArray(object, "preparedUpgrades", "snapshot"); + + if (!backfillIssues.isEmpty()) { + throw new IllegalArgumentException( + "snapshot.backfillIssues must be empty for valid evidence"); + } + + String tenantId = legacyGameSessionTenantId; + validateRows( + instances, + INSTANCE_FIELDS, + Set.of( + "id", + "tenant_id", + "owner_account_id", + "row_version", + "game_template_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "script_pin_epoch"), + Set.of("row_version"), + Set.of(), + Set.of(), + NULLABLE_INSTANCE_FIELDS, + "id", + tenantId, + "instances"); + validateRows( + pointers, + POINTER_FIELDS, + Set.of("id", "tenant_id", "game_instance_id", "pointer_version", "catalog_revision"), + Set.of(), + Set.of("realm_id", "playable_state_namespace_id"), + Set.of("visible", "requires_character_selection", "public_production_realm"), + Set.of(), + "id", + tenantId, + "pointers"); + validateRows( + sharedNamespaces, + SHARED_NAMESPACE_FIELDS, + Set.of("tenant_id"), + Set.of(), + Set.of("playable_state_namespace_id"), + Set.of(), + Set.of(), + "tenant_id", + tenantId, + "sharedNamespaces"); + validateRows( + pointerEvents, + POINTER_EVENT_FIELDS, + Set.of("id", "tenant_id", "game_instance_id", "pointer_version"), + Set.of(), + Set.of(), + Set.of("visible", "requires_character_selection", "public_production_realm"), + NULLABLE_POINTER_EVENT_FIELDS, + "id", + tenantId, + "pointerEvents"); + validateRows( + preparedUpgrades, + PREPARED_UPGRADE_FIELDS, + Set.of( + "id", + "tenant_id", + "source_game_instance_id", + "source_version_id", + "target_version_id", + "executed_target_game_instance_id", + "executed_pointer_version"), + Set.of(), + Set.of(), + Set.of(), + NULLABLE_PREPARED_UPGRADE_FIELDS, + "id", + tenantId, + "preparedUpgrades"); + + validatePointerRelationships(instances, pointers, sharedNamespaces, tenantId); + if (instances.isEmpty() + && pointers.isEmpty() + && sharedNamespaces.isEmpty() + && pointerEvents.isEmpty() + && preparedUpgrades.isEmpty()) { + throw new IllegalArgumentException("snapshot contains no retained tenant evidence"); + } + } + + private static void validateRows( + JsonNode rows, + Set fields, + Set numericFields, + Set nonnegativeNumericFields, + Set uuidFields, + Set booleanFields, + Set nullableFields, + String sortField, + String tenantId, + String path) { + BigInteger previousSortValue = null; + for (int index = 0; index < rows.size(); index++) { + JsonNode row = rows.get(index); + String rowPath = path + "[" + index + "]"; + if (row == null || !row.isObject()) { + throw new IllegalArgumentException(rowPath + " must be an object"); + } + ObjectNode object = (ObjectNode) row; + requireExactFields(object, fields, rowPath); + Iterator fieldNames = fields.iterator(); + while (fieldNames.hasNext()) { + String field = fieldNames.next(); + JsonNode value = object.get(field); + if (value == null) { + throw new IllegalArgumentException(rowPath + "." + field + " is required"); + } + if (value.isNull()) { + if (!nullableFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " may not be null"); + } + continue; + } + if (numericFields.contains(field)) { + BigInteger parsed = parseDecimalNode(value, rowPath + "." + field); + if (parsed.compareTo(LONG_MIN) < 0 || parsed.compareTo(LONG_MAX) > 0) { + throw new IllegalArgumentException( + rowPath + "." + field + " is outside SQL BIGINT bounds"); + } + if (parsed.signum() <= 0 && !nonnegativeNumericFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " must be positive"); + } + if (parsed.signum() < 0 && nonnegativeNumericFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " must be nonnegative"); + } + } else if (uuidFields.contains(field)) { + requireUuid(value, rowPath + "." + field); + } else if (booleanFields.contains(field)) { + if (!value.isBoolean()) { + throw new IllegalArgumentException(rowPath + "." + field + " must be a JSON boolean"); + } + } else if (!value.isTextual()) { + throw new IllegalArgumentException(rowPath + "." + field + " must be a JSON string"); + } + } + + JsonNode tenantNode = object.get("tenant_id"); + if (tenantNode != null && !tenantId.equals(tenantNode.textValue())) { + throw new IllegalArgumentException(rowPath + ".tenant_id contradicts the snapshot key"); + } + BigInteger sortValue = parseDecimalNode(object.get(sortField), rowPath + "." + sortField); + if (previousSortValue != null && sortValue.compareTo(previousSortValue) <= 0) { + throw new IllegalArgumentException(path + " must be strictly sorted by " + sortField); + } + previousSortValue = sortValue; + } + } + + private static void validatePointerRelationships( + JsonNode instances, JsonNode pointers, JsonNode sharedNamespaces, String tenantId) { + Set instanceIds = new java.util.HashSet<>(); + for (JsonNode instance : instances) { + instanceIds.add(instance.get("id").textValue()); + } + String sharedNamespaceId = + sharedNamespaces.isEmpty() + ? null + : sharedNamespaces.get(0).get("playable_state_namespace_id").textValue(); + if (sharedNamespaces.size() > 1) { + throw new IllegalArgumentException( + "sharedNamespaces may contain only the tenant's single allocation"); + } + Set realmIds = new java.util.HashSet<>(); + Set pointerInstanceIds = new java.util.HashSet<>(); + Set selectors = new java.util.HashSet<>(); + Set isolatedNamespaceIds = new java.util.HashSet<>(); + for (int index = 0; index < pointers.size(); index++) { + JsonNode pointer = pointers.get(index); + String path = "pointers[" + index + "]"; + if (!tenantId.equals(pointer.get("tenant_id").textValue())) { + throw new IllegalArgumentException(path + ".tenant_id contradicts the snapshot key"); + } + if (!instanceIds.contains(pointer.get("game_instance_id").textValue())) { + throw new IllegalArgumentException( + path + ".game_instance_id has no retained tenant instance"); + } + if (!realmIds.add(pointer.get("realm_id").textValue())) { + throw new IllegalArgumentException(path + ".realm_id contradicts another current pointer"); + } + if (!pointerInstanceIds.add(pointer.get("game_instance_id").textValue())) { + throw new IllegalArgumentException( + path + ".game_instance_id is bound by multiple current pointers"); + } + String selector = + pointer.get("world_slug").textValue() + "\u0000" + pointer.get("realm_slug").textValue(); + if (!selectors.add(selector)) { + throw new IllegalArgumentException(path + " duplicates another current pointer selector"); + } + String scope = pointer.get("state_scope").textValue(); + String pointerNamespace = pointer.get("playable_state_namespace_id").textValue(); + if ("SHARED".equals(scope)) { + if (sharedNamespaceId == null || !sharedNamespaceId.equals(pointerNamespace)) { + throw new IllegalArgumentException( + path + " does not match the tenant SHARED namespace allocation"); + } + } else if ("ISOLATED".equals(scope)) { + if (sharedNamespaceId != null && sharedNamespaceId.equals(pointerNamespace)) { + throw new IllegalArgumentException( + path + " uses the tenant SHARED allocation as ISOLATED state"); + } + if (!isolatedNamespaceIds.add(pointerNamespace)) { + throw new IllegalArgumentException( + path + " reuses another ISOLATED playable-state namespace"); + } + } else { + throw new IllegalArgumentException( + path + ".state_scope must be exactly SHARED or ISOLATED"); + } + } + } + + private static JsonNode requireArray(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException(path + "." + field + " must be an array"); + } + return value; + } + + private static void requireExactFields(ObjectNode object, Set expected, String path) { + if (object.size() != expected.size()) { + throw new IllegalArgumentException(path + " has missing or undeclared fields"); + } + Iterator fields = object.fieldNames(); + while (fields.hasNext()) { + String field = fields.next(); + if (!expected.contains(field)) { + throw new IllegalArgumentException( + path + "." + field + " is not declared by schema version 3"); + } + } + for (String field : expected) { + if (!object.has(field)) { + throw new IllegalArgumentException(path + "." + field + " is required"); + } + } + } + + private static void requireExactText( + ObjectNode object, String field, String expected, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw new IllegalArgumentException( + path + "." + field + " does not match its snapshot selector"); + } + } + + private static BigInteger parseDecimalNode(JsonNode node, String path) { + if (node == null || !node.isTextual()) { + throw new IllegalArgumentException(path + " must be a canonical decimal string"); + } + return parseDecimal(node.textValue(), path); + } + + private static BigInteger parseDecimal(String value, String path) { + if (value == null || !CANONICAL_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(path + " must be a canonical decimal string"); + } + return new BigInteger(value); + } + + private static void requireUuid(JsonNode value, String path) { + if (!value.isTextual() || !CANONICAL_UUID.matcher(value.textValue()).matches()) { + throw new IllegalArgumentException(path + " must be a lowercase canonical UUID string"); + } + UUID parsed = UUID.fromString(value.textValue()); + if (parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(path + " must not be a nil UUID"); + } + } + + private static String digest(String canonicalJson) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + updateFrame(hash, DIGEST_DOMAIN); + updateFrame(hash, canonicalJson); + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void updateFrame(MessageDigest hash, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java new file mode 100644 index 0000000000..38ef7824b7 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java @@ -0,0 +1,306 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Captures all retained Game Session tenant identity rows behind a short database write fence. */ +@Repository +public class GameSessionRetainedTenantSnapshotRepository { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String LOCK_SOURCE_FAMILIES = + "LOCK TABLE game_instances, gameplay_admission_pointer, " + + "gameplay_tenant_shared_playable_state_namespace, " + + "gameplay_admission_pointer_identity_backfill_issue, " + + "gameplay_admission_pointer_event, prepared_version_upgrade " + + "IN SHARE MODE NOWAIT"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted Spring collaborator is validated before use; no resources or finalizer are acquired." + + " The repository remains non-final for transaction proxying.") + public GameSessionRetainedTenantSnapshotRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Captures the retained owner projection under a caller-owned READ COMMITTED transaction. + * + *

The one-time SHARE fence conflicts with ordinary writes on each included relation and is + * retained until the caller's transaction commits or rolls back. Callers must not perform a + * network request while this owner transaction remains open. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GameSessionRetainedTenantSnapshot capture( + String targetNamespace, String legacyGameSessionTenantId) { + GameSessionRetainedTenantSnapshot.validateIdentity(targetNamespace, legacyGameSessionTenantId); + requireOwnerTransaction(); + + long tenantId = Long.parseLong(legacyGameSessionTenantId); + dsl.execute(LOCK_SOURCE_FAMILIES); + if (hasBackfillIssue(tenantId)) { + throw new InvalidRetainedTenantSnapshotException( + "Game Session retained tenant has an unresolved admission-pointer identity backfill issue"); + } + + ObjectNode envelope = JSON.createObjectNode(); + envelope.put("schemaVersion", 3); + envelope.put("targetNamespace", targetNamespace); + envelope.put("legacyGameSessionTenantId", legacyGameSessionTenantId); + envelope.set("instances", readInstances(tenantId)); + envelope.set("pointers", readPointers(tenantId)); + envelope.set("sharedNamespaces", readSharedNamespaces(tenantId)); + envelope.set("backfillIssues", JSON.createArrayNode()); + envelope.set("pointerEvents", readPointerEvents(tenantId)); + envelope.set("preparedUpgrades", readPreparedUpgrades(tenantId)); + return GameSessionRetainedTenantSnapshot.fromProjection( + targetNamespace, legacyGameSessionTenantId, envelope); + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant snapshot requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Retained-tenant snapshot requires a read-write owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Retained-tenant snapshot requires the DSL connection to join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Retained-tenant snapshot requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + String isolation = isolationRow == null ? null : isolationRow.get(0, String.class); + if (isolation == null || !"read committed".equalsIgnoreCase(isolation.trim())) { + throw new IllegalStateException("Retained-tenant snapshot requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + String readOnly = readOnlyRow == null ? null : readOnlyRow.get(0, String.class); + if (readOnly == null || !"off".equalsIgnoreCase(readOnly.trim())) { + throw new IllegalStateException( + "Retained-tenant snapshot requires a read-write owner transaction"); + } + } + + private boolean hasBackfillIssue(long tenantId) { + return !dsl.fetch( + "SELECT 1 FROM gameplay_admission_pointer_identity_backfill_issue " + + "WHERE tenant_id = ? LIMIT 1", + tenantId) + .isEmpty(); + } + + private ArrayNode readInstances(long tenantId) { + return readRows( + "SELECT id, tenant_id, runtime_version, script_patch_version, owner_account_id, status, " + + "row_version, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "version_state_epoch, generation_config_revision, remap_set_id, " + + "script_patch_pinned_control_plane_request_id, script_pin_epoch " + + "FROM game_instances WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putText(row, record, "runtime_version"); + putNullableText(row, record, "script_patch_version"); + putLong(row, record, "owner_account_id"); + putText(row, record, "status"); + putLong(row, record, "row_version"); + putNullableLong(row, record, "game_template_id"); + putNullableText(row, record, "launch_descriptor_id"); + putNullableLong(row, record, "version_id"); + putNullableLong(row, record, "release_bundle_id"); + putNullableLong(row, record, "version_state_epoch"); + putNullableText(row, record, "generation_config_revision"); + putNullableText(row, record, "remap_set_id"); + putNullableText(row, record, "script_patch_pinned_control_plane_request_id"); + putNullableLong(row, record, "script_pin_epoch"); + return row; + }); + } + + private ArrayNode readPointers(long tenantId) { + return readRows( + "SELECT id, tenant_id, game_instance_id, world_slug, realm_slug, pointer_version, " + + "catalog_revision, visible, requires_character_selection, state_scope, " + + "character_creation_policy, public_production_realm, realm_id, " + + "playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putLong(row, record, "game_instance_id"); + putText(row, record, "world_slug"); + putText(row, record, "realm_slug"); + putLong(row, record, "pointer_version"); + putLong(row, record, "catalog_revision"); + putBoolean(row, record, "visible"); + putBoolean(row, record, "requires_character_selection"); + putText(row, record, "state_scope"); + putText(row, record, "character_creation_policy"); + putBoolean(row, record, "public_production_realm"); + putUuid(row, record, "realm_id"); + putUuid(row, record, "playable_state_namespace_id"); + return row; + }); + } + + private ArrayNode readSharedNamespaces(long tenantId) { + return readRows( + "SELECT tenant_id, playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ? ORDER BY tenant_id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "tenant_id"); + putUuid(row, record, "playable_state_namespace_id"); + return row; + }); + } + + private ArrayNode readPointerEvents(long tenantId) { + return readRows( + "SELECT id, tenant_id, game_instance_id, world_slug, realm_slug, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, " + + "control_plane_request_id, prepared_version_upgrade_id, public_production_realm " + + "FROM gameplay_admission_pointer_event WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putLong(row, record, "game_instance_id"); + putText(row, record, "world_slug"); + putText(row, record, "realm_slug"); + putLong(row, record, "pointer_version"); + putBoolean(row, record, "visible"); + putBoolean(row, record, "requires_character_selection"); + putText(row, record, "state_scope"); + putText(row, record, "character_creation_policy"); + putText(row, record, "control_plane_request_id"); + putNullableText(row, record, "prepared_version_upgrade_id"); + putBoolean(row, record, "public_production_realm"); + return row; + }); + } + + private ArrayNode readPreparedUpgrades(long tenantId) { + return readRows( + "SELECT id, tenant_id, preparation_id, control_plane_request_id, source_game_instance_id, " + + "source_version_id, target_version_id, target_launch_descriptor_id, remap_set_id, " + + "result, executed_target_game_instance_id, executed_pointer_version, " + + "execution_control_plane_request_id FROM prepared_version_upgrade " + + "WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putText(row, record, "preparation_id"); + putText(row, record, "control_plane_request_id"); + putLong(row, record, "source_game_instance_id"); + putLong(row, record, "source_version_id"); + putLong(row, record, "target_version_id"); + putText(row, record, "target_launch_descriptor_id"); + putNullableText(row, record, "remap_set_id"); + putText(row, record, "result"); + putNullableLong(row, record, "executed_target_game_instance_id"); + putNullableLong(row, record, "executed_pointer_version"); + putNullableText(row, record, "execution_control_plane_request_id"); + return row; + }); + } + + private ArrayNode readRows(String query, long tenantId, Function mapper) { + ArrayNode rows = JSON.createArrayNode(); + Result records = dsl.fetch(query, tenantId); + for (Record record : records) { + rows.add(mapper.apply(record)); + } + return rows; + } + + private static void putLong(ObjectNode node, Record record, String field) { + Long value = record.get(field, Long.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, Long.toString(value)); + } + } + + private static void putNullableLong(ObjectNode node, Record record, String field) { + Long value = record.get(field, Long.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, Long.toString(value)); + } + } + + private static void putText(ObjectNode node, Record record, String field) { + String value = record.get(field, String.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, value); + } + } + + private static void putNullableText(ObjectNode node, Record record, String field) { + putText(node, record, field); + } + + private static void putBoolean(ObjectNode node, Record record, String field) { + Boolean value = record.get(field, Boolean.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, value); + } + } + + private static void putUuid(ObjectNode node, Record record, String field) { + UUID value = record.get(field, UUID.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, value.toString()); + } + } + + /** Fail-closed owner evidence error for malformed or unresolved retained rows. */ + public static final class InvalidRetainedTenantSnapshotException extends IllegalStateException { + public InvalidRetainedTenantSnapshotException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java new file mode 100644 index 0000000000..ded5ce90df --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Base64; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unwired source-to-owner transaction boundary for audited retained-tenant association. */ +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner dependencies and namespace are validated before use; no resource or" + + " finalizer is acquired and this class is intentionally not a Spring bean.") +public class GameSessionRetainedTenantAssociationService { + private static final int SIGNATURE_BYTES = 64; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final GameDesignRuntimeTenantIdentityClient sourceClient; + private final GameSessionRetainedTenantAssociationRepository repository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + public GameSessionRetainedTenantAssociationService( + GameDesignRuntimeTenantIdentityClient sourceClient, + GameSessionRetainedTenantAssociationRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Resolves the authenticated Game Design owner receipt before opening a short local owner + * transaction, then commits its retained-row association. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED) + public AssociationReceipt associate( + String associationRequestId, + String canonicalTenantId, + String approvalOperationId, + String legacyGameSessionTenantId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association source read must begin outside an owner transaction"); + } + UUID requestUuid = parseCanonicalNonNilUuid(associationRequestId, "associationRequestId"); + UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonicalTenantId"); + UUID approvalOperationUuid = + parseCanonicalNonNilUuid(approvalOperationId, "approvalOperationId"); + String legacyKey = parseCanonicalPositiveBigint(legacyGameSessionTenantId); + + UUID readRequestUuid; + do { + readRequestUuid = UUID.randomUUID(); + } while (readRequestUuid.equals(requestUuid) || readRequestUuid.equals(approvalOperationUuid)); + + LegacyGameSessionTenantAssociationReceipt ownerReceipt = + sourceClient.resolveLegacyGameSessionTenantAssociation( + tenantUuid.toString(), + approvalOperationUuid.toString(), + legacyKey, + readRequestUuid.toString()); + LegacyGameSessionTenantAssociationReceipt validatedReceipt = + validateOwnerReceipt(ownerReceipt, tenantUuid, approvalOperationUuid, legacyKey); + + return ownerTransaction.execute(status -> repository.register(requestUuid, validatedReceipt)); + } + + private LegacyGameSessionTenantAssociationReceipt validateOwnerReceipt( + LegacyGameSessionTenantAssociationReceipt receipt, + UUID canonicalTenantId, + UUID approvalOperationId, + String legacyTenantKey) { + if (receipt == null || receipt.evidence() == null) { + throw new IllegalStateException("Authenticated Game Design approval receipt is missing"); + } + GameSessionTenantAssociationEvidence received = receipt.evidence(); + GameSessionTenantAssociationEvidence evidence; + try { + evidence = + new GameSessionTenantAssociationEvidence( + received.schemaVersion(), + received.operationId(), + received.targetNamespace(), + received.signerKeyId(), + received.approvedBy(), + received.approvalReference(), + received.signedAt(), + received.legacyGameSessionTenantId(), + received.canonicalTenantId(), + received.sourceGameRowId(), + received.sourceGameTenantKey(), + received.provenanceKind(), + received.gameSessionEvidenceDigest()); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Authenticated Game Design approval manifest is invalid", exception); + } + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !approvalOperationId.equals(evidence.operationId()) + || !canonicalTenantId.equals(evidence.canonicalTenantId()) + || !legacyTenantKey.equals(evidence.legacyGameSessionTenantId())) { + throw new IllegalStateException( + "Authenticated Game Design approval receipt does not match the exact association"); + } + String manifestDigest = receipt.manifestDigest(); + if (manifestDigest == null || !evidence.manifestDigest().equals(manifestDigest)) { + throw new IllegalStateException( + "Authenticated Game Design approval digest does not match its manifest"); + } + requireCanonicalSignature(receipt.ed25519Signature()); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, manifestDigest, receipt.ed25519Signature()); + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static String parseCanonicalPositiveBigint(String value) { + if (value == null || value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "legacyGameSessionTenantId must be canonical positive BIGINT text"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "legacyGameSessionTenantId must be canonical positive BIGINT text"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "legacyGameSessionTenantId must fit a positive PostgreSQL BIGINT", exception); + } + return value; + } + + private static void requireCanonicalSignature(String signature) { + if (signature == null) { + throw new IllegalStateException("Authenticated Game Design approval signature is missing"); + } + try { + byte[] bytes = Base64.getDecoder().decode(signature); + if (bytes.length != SIGNATURE_BYTES + || !Base64.getEncoder().encodeToString(bytes).equals(signature)) { + throw new IllegalStateException( + "Authenticated Game Design approval signature is not canonical Ed25519 base64"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Authenticated Game Design approval signature is invalid", exception); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V12__retained_tenant_association.sql b/services/game-session-service/src/main/resources/db/migration/V12__retained_tenant_association.sql new file mode 100644 index 0000000000..402b46cfe6 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V12__retained_tenant_association.sql @@ -0,0 +1,105 @@ +CREATE TABLE game_session_retained_tenant_association ( + operation_id UUID PRIMARY KEY, + approval_schema_version INTEGER NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + association_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + approval_operation_id UUID NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + game_session_evidence_digest VARCHAR(71) NOT NULL, + approval_manifest_digest VARCHAR(71) NOT NULL, + approval_signature VARCHAR(88) NOT NULL, + snapshot_canonical_json TEXT NOT NULL, + snapshot_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_retained_tenant_association_request + UNIQUE (target_namespace, association_request_id), + CONSTRAINT uq_gs_retained_tenant_association_canonical + UNIQUE (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_retained_tenant_association_legacy_key + UNIQUE (target_namespace, legacy_game_session_tenant_id), + CONSTRAINT chk_gs_retained_tenant_association_schema + CHECK (approval_schema_version = 1), + CONSTRAINT chk_gs_retained_tenant_association_operation_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND approval_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_retained_tenant_association_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gs_retained_tenant_association_approval_labels CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_retained_tenant_association_signed_at CHECK ( + char_length(signed_at) BETWEEN 1 AND 64 + ), + CONSTRAINT chk_gs_retained_tenant_association_retained_key CHECK ( + legacy_game_session_tenant_id > 0 + ), + CONSTRAINT chk_gs_retained_tenant_association_canonical_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_retained_tenant_association_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gs_retained_tenant_association_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_retained_tenant_association_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ), + CONSTRAINT chk_gs_retained_tenant_association_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND approval_manifest_digest ~ '^sha256:[0-9a-f]{64}$' + AND snapshot_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gs_retained_tenant_association_signature CHECK ( + approval_signature ~ '^[A-Za-z0-9+/]{86}==$' + ), + CONSTRAINT chk_gs_retained_tenant_association_snapshot CHECK ( + octet_length(snapshot_canonical_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_retained_tenant_association_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_retained_tenant_association_immutable +BEFORE UPDATE OR DELETE ON game_session_retained_tenant_association +FOR EACH ROW EXECUTE FUNCTION reject_game_session_retained_tenant_association_mutation(); + +CREATE TRIGGER game_session_retained_tenant_association_no_truncate +BEFORE TRUNCATE ON game_session_retained_tenant_association +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_retained_tenant_association_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..d98cbbd3c7 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -0,0 +1,606 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.InvalidAssociationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionRetainedTenantAssociationRepositoryIntegrationTest { + private static final String NAMESPACE = "retained-tenant-association-test"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final Table ASSOCIATIONS = + DSL.table(DSL.name("game_session_retained_tenant_association")); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactRetryReturnsHistoricalReceiptWithoutRecapturingChangedSource() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-before-association"); + String sourceXminBefore = fixture.instanceXmin(420L); + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(42L); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, snapshot); + + AssociationReceipt original = fixture.register(uuid(301), approval); + String associationXmin = fixture.associationXmin(uuid(301)); + String sourceXminAfter = fixture.instanceXmin(420L); + assertThat(sourceXminAfter).isEqualTo(sourceXminBefore); + + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "runtime-after-association", + 420L); + assertThat(fixture.capture(42L).evidenceDigest()) + .isNotEqualTo(original.snapshot().evidenceDigest()); + + AssociationReceipt historicalRetry = fixture.register(uuid(301), approval); + assertThat(historicalRetry).isEqualTo(original); + assertThat(fixture.associationXmin(uuid(301))).isEqualTo(associationXmin); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat( + fixture.repository.read(original.operationId(), uuid(301), uuid(201), 42L, NAMESPACE)) + .contains(original); + assertThatThrownBy( + () -> fixture.repository.read(uuid(999), uuid(998), uuid(997), 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("contradictory local identity"); + assertThat(fixture.repository.read(uuid(999), uuid(998), uuid(997), 999L, NAMESPACE)).isEmpty(); + assertThatThrownBy( + () -> + fixture.repository.read( + original.operationId(), uuid(301), uuid(202), 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThatThrownBy( + () -> + fixture.repository.read( + original.operationId(), uuid(302), uuid(201), 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThatThrownBy( + () -> + fixture.repository.read( + original.operationId(), uuid(301), uuid(201), 43L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.repository.read( + original.operationId(), uuid(301), uuid(201), 42L, NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + } + + @Test + void committedReadRejectsForeignNamespaceBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionRetainedTenantSnapshotRepository snapshots = + mock(GameSessionRetainedTenantSnapshotRepository.class); + GameSessionRetainedTenantAssociationRepository repository = + new GameSessionRetainedTenantAssociationRepository(dsl, snapshots, NAMESPACE); + + assertThatThrownBy( + () -> repository.read(uuid(901), uuid(902), uuid(903), 42L, "other-namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured Game Session workload namespace"); + + verifyNoInteractions(dsl, snapshots); + } + + @Test + void changedRequestAndOneToOneClaimConflictsLeaveNoPartialRows() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + fixture.seedInstance(43L, 430L, "runtime-43"); + GameSessionRetainedTenantSnapshot snapshot42 = fixture.capture(42L); + GameSessionRetainedTenantSnapshot snapshot43 = fixture.capture(43L); + UUID firstRequest = uuid(401); + LegacyGameSessionTenantAssociationReceipt firstApproval = + fixture.approval(uuid(101), uuid(201), 42L, snapshot42); + AssociationReceipt first = fixture.register(firstRequest, firstApproval); + String originalXmin = fixture.associationXmin(firstRequest); + + LegacyGameSessionTenantAssociationReceipt changedApproval = + fixture.approval(uuid(102), uuid(202), 42L, snapshot42); + assertThatThrownBy(() -> fixture.register(firstRequest, changedApproval)) + .isInstanceOf(AssociationConflictException.class); + + assertThatThrownBy(() -> fixture.register(uuid(402), firstApproval)) + .isInstanceOf(AssociationConflictException.class); + + LegacyGameSessionTenantAssociationReceipt changedCanonicalClaim = + fixture.approval(uuid(103), uuid(201), 43L, snapshot43); + assertThatThrownBy(() -> fixture.register(uuid(403), changedCanonicalClaim)) + .isInstanceOf(AssociationConflictException.class); + + LegacyGameSessionTenantAssociationReceipt changedLegacyClaim = + fixture.approval(uuid(104), uuid(202), 42L, snapshot42); + assertThatThrownBy(() -> fixture.register(uuid(404), changedLegacyClaim)) + .isInstanceOf(AssociationConflictException.class); + + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.associationXmin(firstRequest)).isEqualTo(originalXmin); + assertThat(fixture.storedRequestCount(firstRequest)).isEqualTo(1L); + assertThat(fixture.storedRequestCount(uuid(402))).isZero(); + assertThat(fixture.storedRequestCount(uuid(403))).isZero(); + assertThat(fixture.storedRequestCount(uuid(404))).isZero(); + assertThat( + fixture.repository.read(first.operationId(), firstRequest, uuid(201), 42L, NAMESPACE)) + .contains(first); + } + + @Test + void changedMissingAndExtraRetainedRowsRejectFirstCommit() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-original"); + GameSessionRetainedTenantSnapshot originalSnapshot = fixture.capture(42L); + LegacyGameSessionTenantAssociationReceipt wrongDigestApproval = + fixture.approval(uuid(101), uuid(201), 42L, originalSnapshot, "sha256:" + "0".repeat(64)); + + assertThatThrownBy(() -> fixture.register(uuid(501), wrongDigestApproval)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("does not match the approved owner evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + + LegacyGameSessionTenantAssociationReceipt originalApproval = + fixture.approval(uuid(102), uuid(202), 42L, originalSnapshot); + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", "runtime-changed", 420L); + assertThatThrownBy(() -> fixture.register(uuid(502), originalApproval)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("does not match the approved owner evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + + fixture.seedInstance(42L, 421L, "runtime-extra"); + assertThatThrownBy(() -> fixture.register(uuid(503), originalApproval)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("does not match the approved owner evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + + fixture.dsl.execute("DELETE FROM game_instances WHERE tenant_id = ?", 42L); + assertThatThrownBy(() -> fixture.register(uuid(504), originalApproval)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + } + + @Test + void lostAcknowledgementExactRetryReturnsSameOriginalOperationAndBytesWithoutMutation() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + UUID associationRequestId = uuid(601); + + // Model a committed response lost after the transaction: retain only the database baseline. + fixture.register(associationRequestId, approval); + Record committed = fixture.storedByRequest(associationRequestId); + UUID originalOperation = committed.get("operation_id", UUID.class); + String originalRequestDigest = committed.get("request_digest", String.class); + String originalManifestDigest = committed.get("approval_manifest_digest", String.class); + String originalSignature = committed.get("approval_signature", String.class); + assertThat(committed.get("target_namespace", String.class)).isEqualTo(NAMESPACE); + assertThat(originalManifestDigest).isEqualTo(approval.manifestDigest()); + assertThat(originalSignature).isEqualTo(approval.ed25519Signature()); + assertThat(originalRequestDigest) + .isEqualTo( + independentlyComputedRequestDigest( + NAMESPACE, + associationRequestId, + approval.manifestDigest(), + approval.ed25519Signature())); + String originalSnapshot = committed.get("snapshot_canonical_json", String.class); + String originalSnapshotDigest = committed.get("snapshot_evidence_digest", String.class); + String originalReceiptDigest = committed.get("receipt_digest", String.class); + byte[] originalSnapshotBytes = originalSnapshot.getBytes(StandardCharsets.UTF_8); + String originalXmin = fixture.associationXmin(associationRequestId); + + AssociationReceipt recovered = fixture.register(associationRequestId, approval); + + assertThat(recovered.operationId()).isEqualTo(originalOperation); + assertThat(recovered.requestDigest()).isEqualTo(originalRequestDigest); + assertThat(recovered.approvalManifestDigest()).isEqualTo(originalManifestDigest); + assertThat(recovered.approvalSignature()).isEqualTo(originalSignature); + assertThat(recovered.snapshot().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(originalSnapshotBytes); + assertThat(recovered.snapshot().evidenceDigest()).isEqualTo(originalSnapshotDigest); + assertThat(recovered.receiptDigest()).isEqualTo(originalReceiptDigest); + assertThat(fixture.associationXmin(associationRequestId)).isEqualTo(originalXmin); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void rollbackLeavesNoAssociationClaimAndNewAttemptSucceeds() { + Fixture fixture = fixture(); + fixture.seedInstance(43L, 430L, "runtime-43"); + UUID associationRequestId = uuid(602); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(103), uuid(203), 43L, fixture.capture(43L)); + + AssociationReceipt rolledBack = + fixture.transactions.execute( + status -> { + AssociationReceipt result = + fixture.repository.register(associationRequestId, approval); + status.setRollbackOnly(); + return result; + }); + assertThat(rolledBack).isNotNull(); + assertThat(fixture.storedRequestCount(associationRequestId)).isZero(); + assertThat( + fixture.repository.read( + rolledBack.operationId(), associationRequestId, uuid(203), 43L, NAMESPACE)) + .isEmpty(); + + AssociationReceipt retry = fixture.register(associationRequestId, approval); + assertThat(retry.operationId()).isNotEqualTo(rolledBack.operationId()); + assertThat( + fixture.repository.read( + retry.operationId(), associationRequestId, uuid(203), 43L, NAMESPACE)) + .contains(retry); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void concurrentExactFirstWritersReturnSameImmutableReceipt() throws Exception { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + UUID associationRequestId = uuid(701); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + await(start, "concurrent registration start"); + return fixture.register(associationRequestId, approval); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + await(start, "concurrent registration start"); + return fixture.register(associationRequestId, approval); + }); + await(ready, "concurrent registration workers"); + start.countDown(); + + AssociationReceipt firstReceipt = first.get(15, TimeUnit.SECONDS); + AssociationReceipt secondReceipt = second.get(15, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), associationRequestId, uuid(201), 42L, NAMESPACE)) + .contains(firstReceipt); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void sourceWriterWaitsUntilAssociationCommitReleasesRetainedRowFence() throws Exception { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-fenced"); + UUID associationRequestId = uuid(702); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + CountDownLatch snapshotCaptured = new CountDownLatch(1); + CountDownLatch allowAssociationToContinue = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + GameSessionRetainedTenantSnapshotRepository delayedSnapshots = spy(fixture.snapshotRepository); + doAnswer( + invocation -> { + var snapshot = invocation.callRealMethod(); + snapshotCaptured.countDown(); + await(allowAssociationToContinue, "association commit release"); + return snapshot; + }) + .when(delayedSnapshots) + .capture(eq(NAMESPACE), eq("42")); + GameSessionRetainedTenantAssociationRepository delayedRepository = + new GameSessionRetainedTenantAssociationRepository( + fixture.dsl, delayedSnapshots, NAMESPACE); + Fixture delayedFixture = + new Fixture(fixture.dsl, delayedSnapshots, delayedRepository, fixture.transactions); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future association = + executor.submit(() -> delayedFixture.register(associationRequestId, approval)); + await(snapshotCaptured, "fenced snapshot capture"); + Future sourceWriter = + executor.submit( + () -> { + writerStarted.countDown(); + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "runtime-after-fence", + 420L); + }); + await(writerStarted, "source writer attempt"); + assertThatThrownBy(() -> sourceWriter.get(250, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + + allowAssociationToContinue.countDown(); + AssociationReceipt committed = association.get(10, TimeUnit.SECONDS); + sourceWriter.get(10, TimeUnit.SECONDS); + assertThat(committed.snapshot().evidenceDigest()) + .isNotEqualTo(fixture.capture(42L).evidenceDigest()); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } finally { + allowAssociationToContinue.countDown(); + executor.shutdownNow(); + } + } + + @Test + void persistedRowsRejectUpdateDeleteAndTruncateThroughTheirOwnImmutableTriggers() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + UUID associationRequestId = uuid(801); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + fixture.register(associationRequestId, approval); + UUID operationId = + fixture.storedByRequest(associationRequestId).get("operation_id", UUID.class); + + assertCheckViolation( + () -> + fixture.dsl.execute( + "UPDATE game_session_retained_tenant_association SET approved_by = ? " + + "WHERE operation_id = ?", + "changed", + operationId)); + assertCheckViolation( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_retained_tenant_association WHERE operation_id = ?", + operationId)); + assertCheckViolation( + () -> fixture.dsl.execute("TRUNCATE game_session_retained_tenant_association")); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + private Fixture fixture() { + String schema = "gs_retained_tenant_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionRetainedTenantSnapshotRepository snapshotRepository = + new GameSessionRetainedTenantSnapshotRepository(dsl); + GameSessionRetainedTenantAssociationRepository repository = + new GameSessionRetainedTenantAssociationRepository(dsl, snapshotRepository, NAMESPACE); + return new Fixture(dsl, snapshotRepository, repository, transactions); + } + + private static void assertCheckViolation( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + Throwable failure = catchThrowable(action); + assertThat(failure).isInstanceOf(DataAccessException.class); + SQLException sqlException = findSqlException(failure); + assertThat((Throwable) sqlException).isNotNull(); + assertThat(sqlException.getSQLState()).isEqualTo("23514"); + } + + private static SQLException findSqlException(Throwable failure) { + Throwable current = failure; + while (current != null && !(current instanceof SQLException)) { + current = current.getCause(); + } + return (SQLException) current; + } + + private static void await(CountDownLatch latch, String label) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + label); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + label, exception); + } + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static String independentlyComputedRequestDigest( + String exactNamespace, UUID associationRequestId, String manifestDigest, String signature) { + ByteArrayOutputStream framedPreimage = new ByteArrayOutputStream(); + for (String segment : + new String[] { + "game-session/retained-tenant-association-request/v1", + exactNamespace, + associationRequestId.toString(), + manifestDigest, + signature + }) { + byte[] segmentBytes = segment.getBytes(StandardCharsets.UTF_8); + framedPreimage.writeBytes( + Integer.toString(segmentBytes.length).getBytes(StandardCharsets.US_ASCII)); + framedPreimage.write(':'); + framedPreimage.writeBytes(segmentBytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framedPreimage.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new AssertionError("SHA-256 must be available", exception); + } + } + + private record Fixture( + DSLContext dsl, + GameSessionRetainedTenantSnapshotRepository snapshotRepository, + GameSessionRetainedTenantAssociationRepository repository, + TransactionTemplate transactions) { + void seedInstance(long tenantId, long instanceId, String runtimeVersion) { + dsl.execute( + "INSERT INTO game_instances " + + "(id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (?, ?, ?, ?, ?, ?)", + instanceId, + tenantId, + runtimeVersion, + 9L, + "STOPPED", + 0L); + } + + GameSessionRetainedTenantSnapshot capture(long legacyTenantId) { + return Objects.requireNonNull( + transactions.execute( + status -> snapshotRepository.capture(NAMESPACE, Long.toString(legacyTenantId)))); + } + + LegacyGameSessionTenantAssociationReceipt approval( + UUID approvalOperationId, + UUID canonicalTenantId, + long legacyTenantId, + GameSessionRetainedTenantSnapshot snapshot) { + return approval( + approvalOperationId, + canonicalTenantId, + legacyTenantId, + snapshot, + snapshot.evidenceDigest()); + } + + LegacyGameSessionTenantAssociationReceipt approval( + UUID approvalOperationId, + UUID canonicalTenantId, + long legacyTenantId, + GameSessionRetainedTenantSnapshot snapshot, + String evidenceDigest) { + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + 1, + approvalOperationId, + NAMESPACE, + "fixture-owner-key", + "owner-reviewer", + "approval-" + approvalOperationId, + "2026-01-01T00:00:00Z", + Long.toString(legacyTenantId), + canonicalTenantId, + "501", + "source-game-501", + "RETAINED_GAME_V29", + evidenceDigest); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, evidence.manifestDigest(), signature); + } + + AssociationReceipt register( + UUID associationRequestId, LegacyGameSessionTenantAssociationReceipt approval) { + return Objects.requireNonNull( + transactions.execute(status -> repository.register(associationRequestId, approval))); + } + + Record storedByRequest(UUID associationRequestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND association_request_id = ?", + NAMESPACE, + associationRequestId); + } + + long storedRequestCount(UUID associationRequestId) { + Record row = + dsl.fetchOne( + "SELECT count(*) FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND association_request_id = ?", + NAMESPACE, + associationRequestId); + return Objects.requireNonNull( + Objects.requireNonNull(row, "COUNT query must return a row").get(0, Long.class), + "COUNT query returned null"); + } + + String associationXmin(UUID associationRequestId) { + Record row = + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND association_request_id = ?", + NAMESPACE, + associationRequestId); + return Objects.requireNonNull(row).get("xmin", String.class); + } + + String instanceXmin(long instanceId) { + Record row = + dsl.fetchOne("SELECT xmin::text AS xmin FROM game_instances WHERE id = ?", instanceId); + return Objects.requireNonNull(row).get("xmin", String.class); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java new file mode 100644 index 0000000000..dc06804969 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java @@ -0,0 +1,559 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionRetainedTenantSnapshotRepositoryIntegrationTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String NAMESPACE = "retained-snapshot-test"; + private static final String TENANT_ID = "70123"; + private static final long TENANT = Long.parseLong(TENANT_ID); + private static final long OTHER_TENANT = TENANT + 1; + private static final UUID SHARED_NAMESPACE = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID ISOLATED_NAMESPACE = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID REALM_SHARED = UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID REALM_ISOLATED = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String COMMITTED_INSTANCE_PHANTOM_INSERT = + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (901, " + + TENANT + + ", 'phantom', 90123, 'STOPPED', 0)"; + private static final String COMMITTED_POINTER_PHANTOM_INSERT = + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, realm_slug, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, last_updated_by, " + + "last_update_reason, public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (902, 'phantom-world', 'Phantom', 'phantom-realm', 'Phantom realm', " + + TENANT + + ", 901, 1, false, false, 'ISOLATED', 'DISABLED', 'test', 'fence test', false, " + + "'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', 'ffffffff-ffff-4fff-8fff-ffffffffffff')"; + // The integration runtime includes other services' migration resources; scan this module only. + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerTransaction() + throws Exception { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> fixture.repository.capture(NAMESPACE, Long.toString(OTHER_TENANT)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant evidence"); + fixture.seedProjection(); + + assertThatThrownBy(() -> fixture.repository.capture(NAMESPACE, TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(); + JsonNode root = JSON.readTree(snapshot.canonicalJson()); + assertThat(root.get("schemaVersion").intValue()).isEqualTo(3); + assertThat(root.get("targetNamespace").textValue()).isEqualTo(NAMESPACE); + assertThat(root.get("legacyGameSessionTenantId").textValue()).isEqualTo(TENANT_ID); + assertThat(textValues(root.get("instances"), "id")).containsExactly("2", "10", "20"); + assertThat(root.get("instances").get(1).get("runtime_version").textValue()) + .isEqualTo("Café 🐉"); + assertThat(root.get("instances").get(1).get("row_version").textValue()) + .isEqualTo("9223372036854775807"); + assertThat(root.get("instances").get(1).get("owner_account_id").textValue()).isEqualTo("90010"); + assertThat(root.get("instances").get(1).has("owner_account_uuid")).isFalse(); + assertThat(textValues(root.get("pointers"), "id")).containsExactly("2", "10"); + assertThat(root.get("pointers").get(1).get("catalog_revision").textValue()) + .isEqualTo("9223372036854775807"); + assertThat(root.get("pointerEvents").get(1).get("game_instance_id").textValue()) + .isEqualTo("888888"); + assertThat( + root.get("preparedUpgrades").get(0).get("executed_target_game_instance_id").textValue()) + .isEqualTo("999999"); + assertThat(root.get("backfillIssues").size()).isZero(); + assertThat( + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + .isEqualTo(snapshot); + + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> readOnly.execute(status -> fixture.repository.capture(NAMESPACE, TENANT_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-write owner transaction"); + + TransactionTemplate repeatableRead = new TransactionTemplate(fixture.transactionManager); + repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatableRead.execute(status -> fixture.repository.capture(NAMESPACE, TENANT_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + + GameSessionRetainedTenantSnapshotRepository autocommitRepository = + new GameSessionRetainedTenantSnapshotRepository(fixture.autocommitDsl); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> autocommitRepository.capture(NAMESPACE, TENANT_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("DSL connection to join the owner transaction"); + + fixture.dsl.execute( + "INSERT INTO gameplay_admission_pointer_identity_backfill_issue " + + "(pointer_id, tenant_id, world_slug, realm_slug, prior_state_scope, issue_code) " + + "VALUES (?, ?, ?, ?, ?, ?)", + 400L, + TENANT, + "affected-world", + "affected-realm", + "UNKNOWN", + "TEST_UNRESOLVED"); + assertThatThrownBy(fixture::capture) + .isInstanceOf( + GameSessionRetainedTenantSnapshotRepository.InvalidRetainedTenantSnapshotException + .class) + .hasMessageContaining("backfill issue"); + } + + @Test + void capturesCurrentNumericOwnersAndBindsOwnerChangesToSnapshotDigest() throws Exception { + Fixture fixture = fixture(); + fixture.seedProjection(); + fixture.dsl.execute( + "INSERT INTO game_instances " + + "(id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (?, ?, ?, ?, ?, ?)", + 22L, + TENANT, + "numeric-owner", + 90022L, + "STOPPED", + 0L); + + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(); + JsonNode instances = JSON.readTree(snapshot.canonicalJson()).get("instances"); + JsonNode retainedNumericOwner = instances.get(1); + JsonNode newNumericOwner = instances.get(3); + assertThat(retainedNumericOwner.get("id").textValue()).isEqualTo("10"); + assertThat(retainedNumericOwner.get("owner_account_id").textValue()).isEqualTo("90010"); + assertThat(retainedNumericOwner.has("owner_account_uuid")).isFalse(); + assertThat(newNumericOwner.get("id").textValue()).isEqualTo("22"); + assertThat(newNumericOwner.get("owner_account_id").textValue()).isEqualTo("90022"); + assertThat(newNumericOwner.has("owner_account_uuid")).isFalse(); + assertThat( + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + .isEqualTo(snapshot); + + fixture.dsl.execute("UPDATE game_instances SET owner_account_id = ? WHERE id = ?", 90011L, 10L); + GameSessionRetainedTenantSnapshot changedRawSnapshot = fixture.capture(); + assertThat(changedRawSnapshot.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + JsonNode changedRawOwner = + JSON.readTree(changedRawSnapshot.canonicalJson()).get("instances").get(1); + assertThat(changedRawOwner.get("owner_account_id").textValue()).isEqualTo("90011"); + + fixture.dsl.execute("UPDATE game_instances SET owner_account_id = ? WHERE id = ?", 90023L, 22L); + GameSessionRetainedTenantSnapshot changedSnapshot = fixture.capture(); + assertThat(changedSnapshot.evidenceDigest()).isNotEqualTo(changedRawSnapshot.evidenceDigest()); + JsonNode changedOwner = JSON.readTree(changedSnapshot.canonicalJson()).get("instances").get(3); + assertThat(changedOwner.get("owner_account_id").textValue()).isEqualTo("90023"); + } + + @Test + void captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback() throws Exception { + Fixture fixture = fixture(); + fixture.seedProjection(); + CountDownLatch writerReady = new CountDownLatch(1); + CountDownLatch finishWriter = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future writer = + executor.submit( + () -> + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "uncommitted-writer", + 10L); + writerReady.countDown(); + await(finishWriter); + status.setRollbackOnly(); + return null; + })); + assertThat(writerReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(fixture::capture).isInstanceOf(DataAccessException.class); + finishWriter.countDown(); + writer.get(10, TimeUnit.SECONDS); + assertThat(fixture.capture().canonicalJson()).contains("Café 🐉"); + } finally { + finishWriter.countDown(); + executor.shutdownNow(); + } + } + + @Test + void + shareFenceBlocksConcurrentInsertUpdateDeleteAcrossEverySourceFamilyAndReleasesAfterCommitOrRollback() + throws Exception { + Fixture fixture = fixture(); + fixture.seedProjection(); + GameSessionRetainedTenantSnapshot originalSnapshot = fixture.capture(); + + fixture.transactions.execute( + status -> { + fixture.repository.capture(NAMESPACE, TENANT_ID); + for (MutationCase mutation : mutationCases()) { + fixture.assertMutationBlocked(mutation.insertSql()); + fixture.assertMutationBlocked(mutation.updateSql()); + fixture.assertMutationBlocked(mutation.deleteSql()); + } + return null; + }); + + fixture.assertMutationMatrixSucceedsThenRollsBack(); + assertThat(fixture.capture().evidenceDigest()).isEqualTo(originalSnapshot.evidenceDigest()); + fixture.executeMutation(COMMITTED_INSTANCE_PHANTOM_INSERT); + Long instancePhantomCount = + java.util.Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT count(*) FROM game_instances WHERE id = 901 AND tenant_id = ?", TENANT)) + .get(0, Long.class); + assertThat(instancePhantomCount).isEqualTo(1L); + GameSessionRetainedTenantSnapshot afterInstanceInsert = fixture.capture(); + assertThat(afterInstanceInsert.evidenceDigest()) + .isNotEqualTo(originalSnapshot.evidenceDigest()); + + fixture.transactions.execute( + status -> { + fixture.repository.capture(NAMESPACE, TENANT_ID); + status.setRollbackOnly(); + return null; + }); + fixture.assertMutationMatrixSucceedsThenRollsBack(); + assertThat(fixture.capture().evidenceDigest()).isEqualTo(afterInstanceInsert.evidenceDigest()); + fixture.executeMutation(COMMITTED_POINTER_PHANTOM_INSERT); + Long pointerPhantomCount = + java.util.Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT count(*) FROM gameplay_admission_pointer WHERE id = 902 AND tenant_id = ? " + + "AND game_instance_id = 901", + TENANT)) + .get(0, Long.class); + assertThat(pointerPhantomCount).isEqualTo(1L); + GameSessionRetainedTenantSnapshot afterPointerInsert = fixture.capture(); + assertThat(afterPointerInsert.evidenceDigest()) + .isNotEqualTo(afterInstanceInsert.evidenceDigest()); + } + + private Fixture fixture() { + String schema = "gs_retained_snapshot_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext autocommitDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new Fixture( + dataSource, + transactionManager, + transactions, + dsl, + autocommitDsl, + new GameSessionRetainedTenantSnapshotRepository(dsl)); + } + + private static List textValues(JsonNode rows, String field) { + java.util.ArrayList values = new java.util.ArrayList<>(); + for (JsonNode row : rows) { + values.add(row.get(field).textValue()); + } + return values; + } + + private static List mutationCases() { + return List.of( + new MutationCase( + "game_instances", + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (911, " + + TENANT + + ", 'matrix-phantom', 90123, 'STOPPED', 0)", + "UPDATE game_instances SET runtime_version = 'matrix-updated' WHERE id = 10 AND tenant_id = " + + TENANT, + "DELETE FROM game_instances WHERE id = 10 AND tenant_id = " + TENANT), + new MutationCase( + "gameplay_admission_pointer", + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, realm_slug, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, " + + "last_updated_by, last_update_reason, public_production_realm, realm_id, " + + "playable_state_namespace_id) VALUES (912, 'matrix-world', 'Matrix', " + + "'matrix-realm', 'Matrix realm', " + + TENANT + + ", 20, 1, false, false, " + + "'ISOLATED', 'DISABLED', 'test', 'fence test', false, " + + "'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', " + + "'ffffffff-ffff-4fff-8fff-ffffffffffff')", + "UPDATE gameplay_admission_pointer SET last_update_reason = 'matrix-updated' " + + "WHERE id = 10 AND tenant_id = " + + TENANT, + "DELETE FROM gameplay_admission_pointer WHERE id = 10 AND tenant_id = " + TENANT), + new MutationCase( + "gameplay_tenant_shared_playable_state_namespace", + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (" + + OTHER_TENANT + + ", '11111111-2222-4333-8444-555555555555')", + "UPDATE gameplay_tenant_shared_playable_state_namespace SET " + + "playable_state_namespace_id = '22222222-3333-4444-8555-666666666666' " + + "WHERE tenant_id = " + + TENANT, + "DELETE FROM gameplay_tenant_shared_playable_state_namespace WHERE tenant_id = " + + TENANT), + new MutationCase( + "gameplay_admission_pointer_identity_backfill_issue", + "INSERT INTO gameplay_admission_pointer_identity_backfill_issue " + + "(pointer_id, tenant_id, world_slug, realm_slug, prior_state_scope, issue_code) " + + "VALUES (903, " + + OTHER_TENANT + + ", 'phantom-world', 'phantom-realm', 'UNKNOWN', 'TEST')", + "UPDATE gameplay_admission_pointer_identity_backfill_issue SET issue_code = 'MATRIX_UPDATED' " + + "WHERE pointer_id = 399 AND tenant_id = " + + OTHER_TENANT, + "DELETE FROM gameplay_admission_pointer_identity_backfill_issue WHERE pointer_id = 399 " + + "AND tenant_id = " + + OTHER_TENANT), + new MutationCase( + "gameplay_admission_pointer_event", + "INSERT INTO gameplay_admission_pointer_event (id, world_slug, realm_slug, " + + "world_display_name, realm_display_name, tenant_id, game_instance_id, pointer_version, " + + "visible, requires_character_selection, state_scope, character_creation_policy, " + + "actor_principal, reason, control_plane_request_id, public_production_realm) " + + "VALUES (904, 'phantom-world', 'phantom-realm', 'Phantom', 'Phantom realm', " + + OTHER_TENANT + + ", 21, 1, false, false, 'ISOLATED', 'DISABLED', 'test', " + + "'fence test', 'request-phantom-event', false)", + "UPDATE gameplay_admission_pointer_event SET reason = 'matrix-updated' " + + "WHERE id = 10 AND tenant_id = " + + TENANT, + "DELETE FROM gameplay_admission_pointer_event WHERE id = 10 AND tenant_id = " + TENANT), + new MutationCase( + "prepared_version_upgrade", + "INSERT INTO prepared_version_upgrade (id, preparation_id, control_plane_request_id, " + + "tenant_id, source_game_instance_id, source_version_id, target_version_id, " + + "target_launch_descriptor_id, result, reasons_json, checked_participants_json, " + + "participant_results_json, checked_at) VALUES (905, 'phantom-preparation', " + + "'phantom-request', " + + OTHER_TENANT + + ", 21, 1, 2, 'phantom-launch', 'CHECKED', " + + "'[]', '[]', '[]', CURRENT_TIMESTAMP)", + "UPDATE prepared_version_upgrade SET result = 'MATRIX_UPDATED' WHERE id = 3 AND tenant_id = " + + TENANT, + "DELETE FROM prepared_version_upgrade WHERE id = 3 AND tenant_id = " + TENANT)); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for retained-tenant writer"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for retained-tenant writer", exception); + } + } + + private record MutationCase(String table, String insertSql, String updateSql, String deleteSql) {} + + private record Fixture( + DriverManagerDataSource dataSource, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + DSLContext dsl, + DSLContext autocommitDsl, + GameSessionRetainedTenantSnapshotRepository repository) { + GameSessionRetainedTenantSnapshot capture() { + GameSessionRetainedTenantSnapshot snapshot = + transactions.execute(status -> repository.capture(NAMESPACE, TENANT_ID)); + return java.util.Objects.requireNonNull(snapshot); + } + + void seedProjection() { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (10, ?, 'Café 🐉', 90010, 'STOPPED', ?), " + + "(2, ?, 'runtime-two', 90002, 'STOPPED', 0)", + TENANT, + Long.MAX_VALUE, + TENANT); + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (20, ?, 'matrix-pointer-target', 90020, 'STOPPED', 0), " + + "(21, ?, 'other-tenant-history-target', 90021, 'STOPPED', 0)", + TENANT, + OTHER_TENANT); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + TENANT, + SHARED_NAMESPACE); + dsl.execute( + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, realm_slug, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, last_updated_by, " + + "last_update_reason, public_production_realm, realm_id, playable_state_namespace_id, " + + "catalog_revision) VALUES (10, 'north-star', 'Café World', 'quiet-bay', 'Quiet Bay', " + + "?, 10, ?, true, true, 'ISOLATED', 'DISABLED', 'seed', 'projection fixture', false, " + + "?, ?, ?), (2, 'north-star', 'Café World', 'shared-square', 'Shared Square', ?, 2, 1, " + + "true, false, 'SHARED', 'DISABLED', 'seed', 'projection fixture', true, ?, ?, 1)", + TENANT, + Long.MAX_VALUE, + REALM_ISOLATED, + ISOLATED_NAMESPACE, + Long.MAX_VALUE, + TENANT, + REALM_SHARED, + SHARED_NAMESPACE); + dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (id, world_slug, realm_slug, world_display_name, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, actor_principal, " + + "reason, control_plane_request_id, prepared_version_upgrade_id, public_production_realm) " + + "VALUES (10, 'old-world', 'old-realm', 'Old world', 'Old realm', ?, 888888, ?, false, " + + "false, 'ISOLATED', 'DISABLED', 'historical-operator', 'retained history', 'event-ten', " + + "'missing-upgrade', false), (2, 'old-world', 'old-realm-two', 'Old world', 'Old realm', " + + "?, 777777, 1, true, false, 'SHARED', 'DISABLED', 'historical-operator', " + + "'retained history', 'event-two', null, true)", + TENANT, + Long.MAX_VALUE, + TENANT); + dsl.execute( + "INSERT INTO prepared_version_upgrade (id, preparation_id, control_plane_request_id, tenant_id, " + + "source_game_instance_id, source_version_id, target_version_id, target_launch_descriptor_id, " + + "remap_set_id, result, reasons_json, checked_participants_json, participant_results_json, " + + "checked_at, executed_target_game_instance_id, executed_pointer_version, " + + "execution_control_plane_request_id) VALUES (3, 'preparation-three', 'upgrade-request-three', " + + "?, 888888, 99, 100, 'launch-descriptor', null, 'CHECKED', '[]', '[]', '[]', " + + "CURRENT_TIMESTAMP, 999999, ?, 'execution-request-three')", + TENANT, + Long.MAX_VALUE); + dsl.execute( + "INSERT INTO gameplay_admission_pointer_identity_backfill_issue " + + "(pointer_id, tenant_id, world_slug, realm_slug, prior_state_scope, issue_code) " + + "VALUES (399, ?, 'other-tenant-world', 'other-tenant-realm', 'UNKNOWN', 'TEST_FIXTURE')", + OTHER_TENANT); + } + + void assertMutationBlocked(String sql) { + try (Connection connection = dataSource.getConnection()) { + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '200ms'"); + statement.execute(sql); + connection.commit(); + throw new AssertionError( + "Mutation unexpectedly passed the retained-tenant fence: " + sql); + } catch (SQLException exception) { + connection.rollback(); + assertThat(exception.getSQLState()) + .as("mutation should time out on its relation lock: %s", sql) + .isEqualTo("55P03"); + } + } catch (SQLException exception) { + throw new IllegalStateException("Unable to test retained-tenant relation fence", exception); + } + } + + void assertMutationMatrixSucceedsThenRollsBack() { + for (MutationCase mutation : mutationCases()) { + assertMutationSucceedsThenRollsBack(mutation.insertSql()); + assertMutationSucceedsThenRollsBack(mutation.updateSql()); + assertMutationSucceedsThenRollsBack(mutation.deleteSql()); + } + } + + private void assertMutationSucceedsThenRollsBack(String sql) { + try (Connection connection = dataSource.getConnection()) { + connection.setAutoCommit(false); + try { + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '200ms'"); + int affectedRows = statement.executeUpdate(sql); + assertThat(affectedRows) + .as("mutation must change an existing or newly inserted row: %s", sql) + .isPositive(); + } + } finally { + connection.rollback(); + } + } catch (SQLException exception) { + throw new IllegalStateException( + "Mutation did not affect a row after retained-tenant transaction", exception); + } + } + + void executeMutation(String sql) { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement()) { + connection.setAutoCommit(false); + statement.execute("SET LOCAL lock_timeout = '200ms'"); + statement.execute(sql); + connection.commit(); + } catch (SQLException exception) { + throw new IllegalStateException( + "Mutation remained blocked after retained-tenant transaction", exception); + } + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java index 1487459b39..b93793181e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -17,6 +17,7 @@ import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Base64; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -24,7 +25,11 @@ 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.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.GameSessionTenantAssociationManifestEvidence; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -36,8 +41,13 @@ class GameDesignRuntimeTenantIdentityClientTest { private static final String NAMESPACE = "test"; private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final String SOURCE_KEY = "game-design-tenant-91"; private static final long SOURCE_ROW_ID = 91L; + private static final String LEGACY_GAME_SESSION_TENANT_ID = "23"; + private static final String ASSOCIATION_SOURCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String SIGNATURE_SHAPE_FIXTURE = + Base64.getEncoder().encodeToString(new byte[64]); @Test void exactOwnerResponseIsTypedAndStableOnRetryForBothProvenanceKinds() throws Exception { @@ -214,6 +224,311 @@ void rejectsPlaintextIncompleteClasspathTlsAndInvalidNamespaceBeforeChannelCreat verifyNoInteractions(channelFactory); } + @Test + void retainedAssociationReadReturnsCompleteImmutableReceiptAndRetriesExactly() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + ResolveLegacyGameSessionTenantAssociationResponse response = associationResponse(); + when(stub.resolveLegacyGameSessionTenantAssociation(any())) + .thenReturn(response) + .thenReturn(response); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + var first = + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString()); + var retry = + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString()); + + assertThat(first).isEqualTo(retry); + assertThat(first.evidence()).isEqualTo(associationEvidence()); + assertThat(first.manifestDigest()).isEqualTo(associationEvidence().manifestDigest()); + assertThat(first.ed25519Signature()).isEqualTo(SIGNATURE_SHAPE_FIXTURE); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ResolveLegacyGameSessionTenantAssociationRequest.class); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub, times(2)).resolveLegacyGameSessionTenantAssociation(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .allSatisfy( + request -> { + assertThat(request.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(request.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(request.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(request.getLegacyGameSessionTenantId()) + .isEqualTo(LEGACY_GAME_SESSION_TENANT_ID); + }); + } + + @Test + void retainedAssociationRejectsAliasesNilAndBigintOverflowBeforeRpc() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignRuntimeTenantIdentityClient client = newClientWithoutStub(channelFactory); + List invalidRequests = + List.of( + new String[] { + "AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", + OPERATION_ID.toString(), + "9", + REQUEST_ID.toString() + }, + new String[] { + "00000000-0000-0000-0000-000000000000", + OPERATION_ID.toString(), + "9", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + "33333333-3333-4333-8333-33333333333", + "9", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + "00000000-0000-0000-0000-000000000000", + "9", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), OPERATION_ID.toString(), "0", REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), OPERATION_ID.toString(), "09", REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), OPERATION_ID.toString(), "+9", REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + OPERATION_ID.toString(), + "9223372036854775808", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + OPERATION_ID.toString(), + "9", + "22222222-2222-4222-8222-22222222222" + }, + new String[] { + TENANT_ID.toString(), + OPERATION_ID.toString(), + "9", + "00000000-0000-0000-0000-000000000000" + }); + + for (String[] invalid : invalidRequests) { + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + invalid[0], invalid[1], invalid[2], invalid[3])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + + @Test + void retainedAssociationRejectsMissingManifestAndUnknownEnvelopeFields() throws Exception { + assertAssociationRejected( + ResolveLegacyGameSessionTenantAssociationResponse.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .build(), + "has no manifest"); + assertAssociationRejected( + associationResponse().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + "unsupported fields"); + GameSessionTenantAssociationManifestEvidence manifestWithUnknownField = + associationResponse().getManifest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertAssociationRejected( + associationResponse().toBuilder().setManifest(manifestWithUnknownField).build(), + "manifest contains unsupported fields"); + } + + @Test + void retainedAssociationRejectsEveryChangedManifestFieldAgainstOriginalDigest() throws Exception { + ResolveLegacyGameSessionTenantAssociationResponse valid = associationResponse(); + GameSessionTenantAssociationManifestEvidence manifest = valid.getManifest(); + List changedManifests = + List.of( + manifest.toBuilder().setOperationId(REQUEST_ID.toString()).build(), + manifest.toBuilder().setTargetNamespace("other").build(), + manifest.toBuilder().setSignerKeyId("other-signer").build(), + manifest.toBuilder().setApprovedBy("other-approver").build(), + manifest.toBuilder().setApprovalReference("other-reference").build(), + manifest.toBuilder().setSignedAt("2026-09-30T12:01:00Z").build(), + manifest.toBuilder().setLegacyGameSessionTenantId("24").build(), + manifest.toBuilder().setCanonicalTenantId(REQUEST_ID.toString()).build(), + manifest.toBuilder().setSourceGameRowId("92").build(), + manifest.toBuilder().setSourceGameTenantKey("game-design-tenant-92").build(), + manifest.toBuilder().setProvenanceKind("NEW_GAME_ROW").build(), + manifest.toBuilder().setGameSessionEvidenceDigest("sha256:" + "b".repeat(64)).build()); + + for (GameSessionTenantAssociationManifestEvidence changed : changedManifests) { + assertAssociationRejected(valid.toBuilder().setManifest(changed).build(), "manifest digest"); + } + assertAssociationRejected( + valid.toBuilder().setManifest(manifest.toBuilder().setSchemaVersion(2).build()).build(), + "manifest is invalid"); + } + + @Test + void retainedAssociationRejectsChangedEchoAndRecomputedForeignRequestBindings() throws Exception { + ResolveLegacyGameSessionTenantAssociationResponse valid = associationResponse(); + assertAssociationRejected( + valid.toBuilder().setRequestId(OPERATION_ID.toString()).build(), "exact request echo"); + + List foreignEvidence = + List.of( + associationEvidenceWith( + REQUEST_ID, NAMESPACE, LEGACY_GAME_SESSION_TENANT_ID, TENANT_ID), + associationEvidenceWith( + OPERATION_ID, "other", LEGACY_GAME_SESSION_TENANT_ID, TENANT_ID), + associationEvidenceWith(OPERATION_ID, NAMESPACE, "24", TENANT_ID), + associationEvidenceWith( + OPERATION_ID, NAMESPACE, LEGACY_GAME_SESSION_TENANT_ID, REQUEST_ID)); + for (GameSessionTenantAssociationEvidence evidence : foreignEvidence) { + assertAssociationRejected(associationResponse(evidence), "exact request"); + } + } + + @Test + void retainedAssociationRejectsInvalidSignatureAndDigestAndPropagatesUnavailable() + throws Exception { + ResolveLegacyGameSessionTenantAssociationResponse valid = associationResponse(); + assertAssociationRejected( + valid.toBuilder().setEd25519Signature("not-base64").build(), "signature is invalid"); + assertAssociationRejected( + valid.toBuilder() + .setEd25519Signature( + SIGNATURE_SHAPE_FIXTURE.substring(0, SIGNATURE_SHAPE_FIXTURE.length() - 2)) + .build(), + "signature is not canonical"); + assertAssociationRejected( + valid.toBuilder() + .setEd25519Signature(Base64.getEncoder().encodeToString(new byte[63])) + .build(), + "signature is not canonical"); + assertAssociationRejected( + valid.toBuilder().setManifestDigest("sha256:" + "0".repeat(64)).build(), "manifest digest"); + + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + Status.UNAVAILABLE.withDescription("Game Design owner unavailable").asRuntimeException(); + when(stub.resolveLegacyGameSessionTenantAssociation(any())).thenThrow(unavailable); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString())) + .isSameAs(unavailable); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void retainedAssociationRejectsUseBeforeClientInitialization() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignRuntimeTenantIdentityClient client = newClientWithoutStub(channelFactory); + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + } + + private static GameSessionTenantAssociationEvidence associationEvidence() { + return associationEvidenceWith( + OPERATION_ID, NAMESPACE, LEGACY_GAME_SESSION_TENANT_ID, TENANT_ID); + } + + private static GameSessionTenantAssociationEvidence associationEvidenceWith( + UUID operationId, String namespace, String retainedTenantKey, UUID canonicalTenantId) { + return new GameSessionTenantAssociationEvidence( + 1, + operationId, + namespace, + "owner-key-1", + "owner@example.test", + "approval-2026-09", + "2026-09-30T12:00:00Z", + retainedTenantKey, + canonicalTenantId, + "91", + SOURCE_KEY, + "RETAINED_GAME_V29", + ASSOCIATION_SOURCE_DIGEST); + } + + private static ResolveLegacyGameSessionTenantAssociationResponse associationResponse() { + return associationResponse(associationEvidence()); + } + + private static ResolveLegacyGameSessionTenantAssociationResponse associationResponse( + GameSessionTenantAssociationEvidence evidence) { + GameSessionTenantAssociationManifestEvidence manifest = + GameSessionTenantAssociationManifestEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setOperationId(evidence.operationId().toString()) + .setTargetNamespace(evidence.targetNamespace()) + .setSignerKeyId(evidence.signerKeyId()) + .setApprovedBy(evidence.approvedBy()) + .setApprovalReference(evidence.approvalReference()) + .setSignedAt(evidence.signedAt()) + .setLegacyGameSessionTenantId(evidence.legacyGameSessionTenantId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setGameSessionEvidenceDigest(evidence.gameSessionEvidenceDigest()) + .build(); + return ResolveLegacyGameSessionTenantAssociationResponse.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setManifest(manifest) + .setManifestDigest(evidence.manifestDigest()) + .setEd25519Signature(SIGNATURE_SHAPE_FIXTURE) + .build(); + } + + private static void assertAssociationRejected( + ResolveLegacyGameSessionTenantAssociationResponse response, String message) throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveLegacyGameSessionTenantAssociation(any())).thenReturn(response); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(message); + } + @Test void initUsesConfiguredGameDesignTargetAndFileBackedTls(@TempDir Path directory) throws Exception { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java new file mode 100644 index 0000000000..0d00eac1cb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java @@ -0,0 +1,290 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; +import org.junit.jupiter.api.Test; + +class GameSessionRetainedTenantSnapshotTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String NAMESPACE = "retained-snapshot-test"; + private static final String TENANT_ID = "7"; + private static final String SNAPSHOT_DIGEST_DOMAIN = + "game-session/retained-tenant-identity-snapshot/v3"; + private static final String SNAPSHOT_DIGEST = + "sha256:79d78d5af138e7261f63696a2ccc2b8f5ceadc4f0e139c348238873e74bda5c4"; + private static final String IRRELEVANT_DIGEST = "sha256:" + "0".repeat(64); + + @Test + void emitsCanonicalOrderedUnicodeAndLargeCounterVectorAndBindsChangedFields() { + String canonicalJson = snapshotJson("Café 🐉"); + GameSessionRetainedTenantSnapshot snapshot = + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, canonicalJson, expectedDigest(canonicalJson)); + + assertThat(snapshot.canonicalJson()) + .startsWith("{\"backfillIssues\":[],\"instances\":[") + .contains("\"runtime_version\":\"Café 🐉\"") + .contains("\"row_version\":\"9223372036854775807\""); + assertThat(snapshot.canonicalJson().indexOf("\"id\":\"2\"")) + .isLessThan(snapshot.canonicalJson().indexOf("\"id\":\"10\"")); + assertThat(snapshot.evidenceDigest()).isEqualTo(SNAPSHOT_DIGEST); + assertThat(snapshot.evidenceDigest()).isEqualTo(expectedDigest(canonicalJson)); + assertThat( + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + .isEqualTo(snapshot); + + GameSessionRetainedTenantSnapshot changed = + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshotJson("Café 🐲"), expectedDigest(snapshotJson("Café 🐲"))); + assertThat(changed.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + } + + @Test + void retainsRequiredCurrentNumericOwnerIdentityAndBindsItToTheDigest() { + ObjectNode projection = envelopeWithInstances("runtime"); + ArrayNode instances = projection.withArray("instances"); + ObjectNode owner = (ObjectNode) instances.get(0); + owner.put("owner_account_id", "10"); + instances.add(instance("20", "legacy-owner", "20")); + + GameSessionRetainedTenantSnapshot snapshot = snapshot(projection); + JsonNode rows; + try { + rows = JSON.readTree(snapshot.canonicalJson()).get("instances"); + } catch (IOException exception) { + throw new AssertionError("Unable to read canonical snapshot test vector", exception); + } + assertThat(rows.get(0).get("owner_account_id").textValue()).isEqualTo("10"); + assertThat(rows.get(0).has("owner_account_uuid")).isFalse(); + assertThat(rows.get(1).get("owner_account_id").textValue()).isEqualTo("9"); + assertThat(rows.get(2).get("owner_account_id").textValue()).isEqualTo("9"); + assertThat(rows.get(2).has("owner_account_uuid")).isFalse(); + + ObjectNode changedOwner = projection.deepCopy(); + ((ObjectNode) changedOwner.withArray("instances").get(0)).put("owner_account_id", "11"); + GameSessionRetainedTenantSnapshot changedSnapshot = snapshot(changedOwner); + assertThat(changedSnapshot.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + } + + @Test + void rejectsMissingOwnerFieldAndIncompatibleV2SnapshotReceipts() { + ObjectNode missingSlot = envelopeWithInstances("runtime"); + ((ObjectNode) missingSlot.withArray("instances").get(0)).remove("owner_account_id"); + assertThatThrownBy(() -> revalidate(missingSlot)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or undeclared fields"); + + ObjectNode oldSchema = envelopeWithInstances("runtime"); + oldSchema.put("schemaVersion", 2); + assertThatThrownBy(() -> revalidate(oldSchema)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schemaVersion must be integer 3"); + + ObjectNode nullOwner = envelopeWithInstances("runtime"); + ((ObjectNode) nullOwner.withArray("instances").get(0)).putNull("owner_account_id"); + assertThatThrownBy(() -> revalidate(nullOwner)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner_account_id may not be null"); + } + + @Test + void rejectsEmptyUnknownMalformedAndDuplicateMemberEvidence() { + ObjectNode empty = envelope(); + assertThatThrownBy(() -> revalidate(empty)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant evidence"); + + ObjectNode unknown = envelopeWithInstances("Café 🐉"); + unknown.put("unexpected", "evidence"); + assertThatThrownBy(() -> revalidate(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("undeclared"); + + ObjectNode malformedNumeric = envelopeWithInstances("Café 🐉"); + ((ObjectNode) malformedNumeric.withArray("instances").get(0)).put("id", "01"); + assertThatThrownBy(() -> revalidate(malformedNumeric)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + + ObjectNode malformedUuid = envelopeWithInstances("Café 🐉"); + ObjectNode pointer = pointer("2", "not-a-uuid"); + malformedUuid.withArray("pointers").add(pointer); + assertThatThrownBy(() -> revalidate(malformedUuid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase canonical UUID"); + + ObjectNode missingInstance = envelopeWithInstances("Café 🐉"); + missingInstance + .withArray("pointers") + .add(pointer("999", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + assertThatThrownBy(() -> revalidate(missingInstance)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant instance"); + + ObjectNode unresolvedBackfill = envelopeWithInstances("Café 🐉"); + unresolvedBackfill.withArray("backfillIssues").add(JSON.createObjectNode()); + assertThatThrownBy(() -> revalidate(unresolvedBackfill)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("backfillIssues must be empty"); + + String valid = snapshotJson("Café 🐉"); + String duplicateMemberJson = + valid.replace( + "\"targetNamespace\":\"" + NAMESPACE + "\"", + "\"targetNamespace\":\"" + NAMESPACE + "\",\"targetNamespace\":\"" + NAMESPACE + "\""); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, duplicateMemberJson, SNAPSHOT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("malformed"); + } + + @Test + void rejectsNonCanonicalNamespaceAndLegacyTenantKeys() { + String valid = snapshotJson("runtime"); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + "Invalid-Namespace", TENANT_ID, valid, IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, "07", valid, IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, "9223372036854775808", valid, IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive BIGINT"); + } + + private static GameSessionRetainedTenantSnapshot revalidate(ObjectNode projection) { + return GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, canonicalJson(projection), IRRELEVANT_DIGEST); + } + + private static String snapshotJson(String runtimeVersion) { + return canonicalJson(envelopeWithInstances(runtimeVersion)); + } + + private static ObjectNode envelopeWithInstances(String runtimeVersion) { + ObjectNode envelope = envelope(); + ArrayNode instances = JSON.createArrayNode(); + instances.add(instance("2", "old-runtime", "0")); + instances.add(instance("10", runtimeVersion, "9223372036854775807")); + envelope.set("instances", instances); + return envelope; + } + + private static ObjectNode envelope() { + ObjectNode envelope = JSON.createObjectNode(); + envelope.put("targetNamespace", NAMESPACE); + envelope.put("schemaVersion", 3); + envelope.put("legacyGameSessionTenantId", TENANT_ID); + envelope.set("instances", JSON.createArrayNode()); + envelope.set("pointers", JSON.createArrayNode()); + envelope.set("sharedNamespaces", JSON.createArrayNode()); + envelope.set("backfillIssues", JSON.createArrayNode()); + envelope.set("pointerEvents", JSON.createArrayNode()); + envelope.set("preparedUpgrades", JSON.createArrayNode()); + return envelope; + } + + private static ObjectNode instance(String id, String runtimeVersion, String rowVersion) { + ObjectNode instance = JSON.createObjectNode(); + instance.put("id", id); + instance.put("tenant_id", TENANT_ID); + instance.put("runtime_version", runtimeVersion); + instance.putNull("script_patch_version"); + instance.put("owner_account_id", "9"); + instance.put("status", "STOPPED"); + instance.put("row_version", rowVersion); + instance.putNull("game_template_id"); + instance.putNull("launch_descriptor_id"); + instance.putNull("version_id"); + instance.putNull("release_bundle_id"); + instance.putNull("version_state_epoch"); + instance.putNull("generation_config_revision"); + instance.putNull("remap_set_id"); + instance.putNull("script_patch_pinned_control_plane_request_id"); + instance.putNull("script_pin_epoch"); + return instance; + } + + private static ObjectNode pointer(String instanceId, String realmId) { + ObjectNode pointer = JSON.createObjectNode(); + pointer.put("id", "1"); + pointer.put("tenant_id", TENANT_ID); + pointer.put("game_instance_id", instanceId); + pointer.put("world_slug", "north-star"); + pointer.put("realm_slug", "one-realm"); + pointer.put("pointer_version", "1"); + pointer.put("catalog_revision", "1"); + pointer.put("visible", true); + pointer.put("requires_character_selection", false); + pointer.put("state_scope", "ISOLATED"); + pointer.put("character_creation_policy", "DISABLED"); + pointer.put("public_production_realm", false); + pointer.put("realm_id", realmId); + pointer.put("playable_state_namespace_id", "11111111-2222-4333-8444-555555555555"); + return pointer; + } + + private static String canonicalJson(ObjectNode projection) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new AssertionError("Unable to build canonical snapshot test vector", exception); + } + } + + private static GameSessionRetainedTenantSnapshot snapshot(ObjectNode projection) { + String canonicalJson = canonicalJson(projection); + return GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, canonicalJson, expectedDigest(canonicalJson)); + } + + private static String expectedDigest(String canonicalJson) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + updateFrame(hash, SNAPSHOT_DIGEST_DOMAIN); + updateFrame(hash, canonicalJson); + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new AssertionError("SHA-256 unavailable for snapshot test vector", exception); + } + } + + private static void updateFrame(MessageDigest hash, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java new file mode 100644 index 0000000000..ba4014b3fa --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java @@ -0,0 +1,260 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamesession.service.GameSessionRetainedTenantAssociationService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionRetainedTenantAssociationServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID REQUEST = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID APPROVAL_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OTHER_TENANT = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String LEGACY_KEY = "42"; + + private final GameDesignRuntimeTenantIdentityClient client = + mock(GameDesignRuntimeTenantIdentityClient.class); + private final GameSessionRetainedTenantAssociationRepository repository = + mock(GameSessionRetainedTenantAssociationRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final GameSessionRetainedTenantAssociationService service = + new GameSessionRetainedTenantAssociationService( + client, repository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesOwnerReceiptBeforeStartingReadCommittedRequiresNewTransaction() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + AssociationReceipt localReceipt = mock(AssociationReceipt.class); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(localReceipt); + + assertThat( + service.associate( + REQUEST.toString(), TENANT.toString(), APPROVAL_OPERATION.toString(), LEGACY_KEY)) + .isSameAs(localReceipt); + + InOrder ordered = inOrder(client, transactionManager, repository); + ordered + .verify(client) + .resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString()); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + ordered.verify(transactionManager).getTransaction(definition.capture()); + ordered.verify(repository).register(REQUEST, ownerReceipt); + ordered.verify(transactionManager).commit(any(TransactionStatus.class)); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + + ArgumentCaptor readRequest = ArgumentCaptor.forClass(String.class); + verify(client) + .resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), + eq(APPROVAL_OPERATION.toString()), + eq(LEGACY_KEY), + readRequest.capture()); + UUID readRequestId = UUID.fromString(readRequest.getValue()); + assertThat(readRequestId.toString()).isEqualTo(readRequest.getValue()); + assertThat(readRequestId).isNotEqualTo(REQUEST).isNotEqualTo(APPROVAL_OPERATION); + } + + @Test + void rejectsMalformedCallerBindingBeforeOwnerReadOrTransaction() { + List malformed = + List.of( + new String[] {null, TENANT.toString(), APPROVAL_OPERATION.toString(), LEGACY_KEY}, + new String[] { + new UUID(0L, 0L).toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY + }, + new String[] { + "abcdefab-cdef-4abc-8def-abcdefabcdef".toUpperCase(Locale.ROOT), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY + }, + new String[] { + REQUEST.toString(), "not-a-uuid", APPROVAL_OPERATION.toString(), LEGACY_KEY + }, + new String[] { + REQUEST.toString(), + new UUID(0L, 0L).toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY + }, + new String[] { + REQUEST.toString(), + TENANT.toString(), + "00000000-0000-0000-0000-000000000000", + LEGACY_KEY + }, + new String[] { + REQUEST.toString(), TENANT.toString(), APPROVAL_OPERATION.toString(), "0" + }, + new String[] { + REQUEST.toString(), TENANT.toString(), APPROVAL_OPERATION.toString(), "042" + }, + new String[] { + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + "9223372036854775808" + }); + + for (String[] arguments : malformed) { + assertThatThrownBy( + () -> service.associate(arguments[0], arguments[1], arguments[2], arguments[3])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(client, transactionManager, repository); + } + + @Test + void rejectsDirectInvocationInsideActualTransactionBeforeSourceRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an owner transaction"); + + verifyNoInteractions(client, transactionManager, repository); + } + + @Test + void rejectsContradictoryOwnerReceiptBeforeTransactionStart() { + when(client.resolveLegacyGameSessionTenantAssociation( + anyString(), anyString(), anyString(), anyString())) + .thenReturn(receipt("other-namespace", TENANT, 42L)) + .thenReturn(receipt(NAMESPACE, OTHER_TENANT, 42L)) + .thenReturn( + receipt( + NAMESPACE, UUID.fromString("66666666-6666-4666-8666-666666666666"), TENANT, 42L)) + .thenReturn(receipt(NAMESPACE, TENANT, 43L)); + + for (int attempt = 0; attempt < 4; attempt++) { + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the exact association"); + } + + verify(client, times(4)) + .resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString()); + verifyNoInteractions(transactionManager, repository); + } + + @Test + void sourceFailureDoesNotStartTransactionOrCreateLocalState() { + when(client.resolveLegacyGameSessionTenantAssociation( + anyString(), anyString(), anyString(), anyString())) + .thenThrow(new IllegalStateException("owner unavailable")); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("owner unavailable"); + + verifyNoInteractions(transactionManager, repository); + } + + @Test + void associationCandidateIsNotRegisteredAsSpringComponent() { + assertThat( + AnnotatedElementUtils.hasAnnotation( + GameSessionRetainedTenantAssociationService.class, Component.class)) + .isFalse(); + assertThat( + AnnotatedElementUtils.hasAnnotation( + GameSessionRetainedTenantAssociationRepository.class, Component.class)) + .isFalse(); + } + + private static LegacyGameSessionTenantAssociationReceipt receipt( + String namespace, UUID canonicalTenantId, long legacyKey) { + return receipt(namespace, APPROVAL_OPERATION, canonicalTenantId, legacyKey); + } + + private static LegacyGameSessionTenantAssociationReceipt receipt( + String namespace, UUID operationId, UUID canonicalTenantId, long legacyKey) { + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + 1, + operationId, + namespace, + "fixture-key", + "approved-by-test", + "approval-reference-1", + "2026-01-01T00:00:00Z", + Long.toString(legacyKey), + canonicalTenantId, + "501", + "source-game-501", + "RETAINED_GAME_V29", + "sha256:" + "a".repeat(64)); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, evidence.manifestDigest(), signature); + } +} From b0bfbdb7e9bc85256baec85c29f696d255b1fca9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 16:55:26 +1300 Subject: [PATCH 057/105] Converge UUID receiving paths and preserve tenant foundation in child --- .../account-service/api-contracts.md | 6 +- .../api-contracts.md | 2 + .../game-design-service/README.md | 4 +- .../game-design-service/api-contracts.md | 17 - .../logging-admin-service/api-contracts.md | 2 +- .../social-groups-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 3 - .../player-access-and-session.md | 4 +- protos/account/v1/account_service.proto | 7 +- .../v1/tenant_identity_service.proto | 27 -- .../service/impl/AccountGrpcService.java | 99 +++- .../RuntimeAccountIdentityGrpcService.java | 5 + .../src/main/resources/application-prod.yml | 1 + .../src/main/resources/application.yml | 1 + ...timeAccountIdentityGrpcAuthWiringTest.java | 159 ++++++ .../service/impl/AccountGrpcServiceTest.java | 453 ++++++++++++++---- .../impl/ScriptEventIngressServiceImpl.java | 6 +- .../ScriptEventIngressServiceImplTest.java | 11 +- .../tenant/RuntimeTenantIdentityEvidence.java | 53 -- .../RuntimeTenantIdentityEvidenceTest.java | 121 ----- .../common/security/SessionContext.java | 8 +- .../SessionContextTenantAccessTest.java | 24 +- .../firemud/gamedesign/entity/Game.java | 2 - .../firemud/gamedesign/mapper/GameMapper.java | 2 - .../gamedesign/repository/GameRepository.java | 148 +----- .../repository/GameTenantIdentity.java | 15 - .../impl/TenantIdentityGrpcService.java | 168 ------- .../src/main/resources/application.yml | 4 - .../V29__canonical_game_tenant_identity.sql | 68 --- ...nantIdentityRepositoryIntegrationTest.java | 177 ------- .../TenantIdentityGrpcAuthWiringTest.java | 244 ---------- .../impl/TenantIdentityGrpcServiceTest.java | 206 -------- ...GameDesignRuntimeTenantIdentityClient.java | 164 ------- .../client/ModerationPolicyClient.java | 5 +- .../command/text/PlayCommandHandler.java | 15 +- .../service/impl/GameSessionGrpcService.java | 7 - .../GameSessionLoginIntegrationTest.java | 12 +- ...essionWebSocketHandlerIntegrationTest.java | 46 +- ...DesignRuntimeTenantIdentityClientTest.java | 316 ------------ .../command/text/PlayCommandHandlerTest.java | 319 +++++++----- .../text/SessionResumptionFlowTest.java | 11 +- .../text/TextCommandInterpreterTest.java | 15 +- .../gamesession/CrossServiceAppHarness.java | 2 +- .../service/impl/SessionActorReaders.java | 8 +- .../impl/AdmissionPointerServiceImplTest.java | 16 +- 45 files changed, 962 insertions(+), 2023 deletions(-) delete mode 100644 protos/game-design/v1/tenant_identity_service.proto delete mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java delete mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java delete mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java delete mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java delete mode 100644 services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql delete mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java delete mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java delete mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index e7eca2a03b..ceef4ecd94 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +Current profile gRPC reads and writes reject requests without the exact authenticated Account UUID subject; `GetProfile` and `UpdateProfile` are not cross-account Social APIs. `ListPresenceVisibilityPolicies` now requires the exact same-namespace Social & Groups mTLS identity, validates the complete batch of at most 100 canonical non-nil Account UUIDs before storage access, resolves subjects only through Account's provenance-checked local resolver, and returns policies keyed only by requested UUIDs. Unknown or unproven subjects are omitted for complete `PRIVATE` redaction; ambiguous resolver aliases and unexpected policy-row keys fail closed. Social's durable relationship subjects still have no trusted Account UUID mapping, so Social's safe consumer migration remains outstanding; numeric relationship row IDs must not be forwarded as cross-owner identity. + Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). `ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. Its focused service test passed 7/7 cases, and its shared auth-interceptor wiring test passed 3/3 cases, including the base and production configuration paths. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. @@ -93,7 +95,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. - `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails and permits account holders to select `PUBLIC`, `FRIENDS_ONLY`, or `PRIVATE`, while `HIDDEN_STAFF` remains reserved for the staff-visibility owner. The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. -- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 account IDs. Social projections consume this authority at read time; unknown or unavailable entries are intentionally omitted so callers apply complete `PRIVATE` redaction. +- `ListPresenceVisibilityPolicies` – implemented bounded workload-only bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. The exact same-namespace Social & Groups mTLS identity is enforced by the handler; the method bypasses bearer validation only to permit this workload-only call. Account privately resolves each requested UUID through its provenance-checked resolver, queries the existing tenant-local policy shape, and returns only UUID-correlated results. Unknown or unproven subjects are omitted for complete `PRIVATE` redaction; ambiguous storage-row aliases or unexpected rows fail closed. Social projections may consume this read after Social's still-missing trusted mapping from durable relationship subjects to canonical Account UUIDs is supplied. `GetProfile` and `UpdateProfile` remain exact self-subject operations. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current implementation behind this method remains the local legacy export described above. - `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. @@ -113,7 +115,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – exact Game Session workload-only membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. `accountId` is the canonical non-nil Account UUID on the wire; Account alone resolves it through its provenance-checked UUID-to-private-row resolver, verifies the returned private membership DTO still identifies that resolved Account row and requested tenant, and echoes the requested canonical UUID. `tenantId` remains a positive numeric tenant identifier, and `requestId` is forwarded unchanged. The proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. - `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, UUID provenance, and persisted source numeric row identity. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 6839cc3dc8..226b86179d 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -14,6 +14,8 @@ For `ListScriptHandoffEvents`, the target command identity is the complete Comma This section records the current implementation boundary only. The API sections below remain normative target contracts; a current implementation note does not relax those contracts, and a target-only surface must not be inferred as shipped. +The current legacy `TriggerScriptEvent(isDryRun=true)` principal quota key uses the canonical Account UUID claim when the authenticated caller has an account subject; service and operator branches retain their separate principal forms. Account subjects are not converted to numeric Account storage IDs. + The unsupported NPC formation REST family has been removed from the runtime and authoritative OpenAPI. Formation operations remain available only through the authenticated internal gRPC control-plane path; no REST caller can supply a tenant or NPC identifier to reach the formation service. The gRPC path retains its existing global admin guard, which is neither tenant-bound `tenantAdmin` authorization nor Entity-owned NPC namespace/ownership proof; formation behavior remains partial until those target checks are implemented and proven. Target formation control-plane behavior eliminates unauthenticated service-local reachability and retains the family only as an exact authenticated internal `tenantAdmin` operation. The caller must be bound to the requested tenant; request tenant selectors are not authority, and neither a global `platformAdmin` nor any other global-role override is permitted. Automation must verify formation ownership before every read or mutation, including member listing, and must verify through Entity Management's NPC owner contract that the leader and every referenced member belong to the same tenant and applicable gameplay namespace before create, membership mutation, or returning the formation. Missing auth/context, tenant mismatch, formation mismatch, and cross-tenant NPC references fail closed; focused negative proof must cover unauthenticated calls, tenant A selecting tenant B, and tenant A adding/listing tenant B NPCs. diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 2c88de1b49..598505a693 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -4,7 +4,7 @@ Offers tools for building worlds, items, actions, and events that make up each game. Used by creators to design content without touching the underlying code. It maintains version metadata, configuration manifests, and templates so new game instances can be created with predefined rules. Template creation does not provision administrator accounts; any future bootstrap flow must use Account-owned account, membership, and grant operations. -Creator authoring and publication are design-time operations. Game Design also exposes an authenticated, internal owner-local tenant-identity metadata read for Game Session; that narrow read does not make Game Design a gameplay or actor-entry authority. Runtime clients never request logos, favicons, or themes from it. **Target state:** published assets are served from object storage via manifest files; the current private object-store URLs are not public client delivery, so approved public delivery remains deferred. +This service is used only at design time. Runtime clients never request logos, favicons, or themes from it. **Target state:** published assets are served from object storage via manifest files; the current private object-store URLs are not public client delivery, so approved public delivery remains deferred. Authoritative read surfaces worth wiring into creator/operator tooling: @@ -16,8 +16,6 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved, because `GameAssetServiceImpl` uses `MultipartFile.getBytes()` without matching limits in `AssetStoreProperties`; upload admission and resource-safety readiness remain blocked. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. Publish/export later writes version-prefix objects and a manifest through the private object-store endpoint; target private-candidate/content-addressed publication and approved public `/assets/**` delivery remain unimplemented. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). -The owner-local tenant UUID read is implemented, but published realm-entry policy/descriptor/template production and Game Session/Entity admission composition remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused proof passed for the service (6/6), auth wiring (3/3), and shared evidence (2/2); the PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. See the exact API boundary and current proof record in [API Contracts](./api-contracts.md#runtime-tenant-identity-owner-read) and the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). - ## 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 5c8b76dd0a..6f2adfb281 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -35,8 +35,6 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. Full-version publish has a Temporal `publish` workflow path when Temporal is enabled. Its four owner-to-owner digest reads now use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; the authorization seam no longer depends on an empty-role JWT or an Automation admin-role fallback. End-to-end full-version publication remains blocked: the Game Logic owner digest fails closed because owner-local manifest and provenance for the version's rule inputs are absent, Automation's full-version content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see the explicit status below and [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). When the Temporal beans are disabled or absent, the synchronous `PublishVersion` path returns success only after its local terminal publish gates, release-attestation commit, Version finalization, and artifact publication complete; ordinary validation/export failures are surfaced explicitly. After a downstream exception, exact readback determines the outcome: if it proves that no release bundle or artifact exists and the candidate Version remains `DRAFT`, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row; best-effort object-store cleanup can still be uncertain. Complete release evidence is reconciled to success, while partial evidence remains pending for reconciliation. Restart-independent workflow durability and workflow runtime metadata are target/conditional properties of the Temporal path when its authorization, worker, and readback proofs are live; they are not properties of this synchronous fallback. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. -Game Design now issues a canonical tenant UUID on its owner `game` row and serves the authenticated owner-local `ResolveRuntimeTenantIdentity` read. Migration V29 records exact source-row/key provenance for valid retained keys and leaves blank or out-of-bounds retained keys quarantined without a canonical identity; row identity and provenance are immutable after issuance. This evidence is only a tenant-owner read: it does not publish realm-entry policy or resolve a realm descriptor/template, current realm pointer, playable-state namespace/scope, or actor admission. Reported focused proof: compilation and `generateJooq` succeeded, `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2; the PostgreSQL integration test compiled, but PostgreSQL execution remains unproved because Docker was unavailable. - The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. @@ -71,7 +69,6 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e ## gRPC APIs - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. -- `ResolveRuntimeTenantIdentity` – returns Game Design's persisted canonical tenant UUID and exact source-row/key provenance to Game Session; this owner-local metadata read does not resolve realm policy, realm routing, playable-state namespace/scope, or actor entry. - `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. @@ -98,20 +95,6 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `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. - `FinalizePurgeVersionAssets` – **Target state:** CAS-guarded purge completion that transitions purge-in-progress artifacts to `PURGED` after byte-deletion confirmation. The current implementation has no database CAS or shared idempotency ledger. -### Runtime tenant identity owner read - -`TenantIdentityService/ResolveRuntimeTenantIdentity` is an internal authenticated read of the canonical tenant identity persisted by Game Design for its own `game` row. The protobuf in [`tenant_identity_service.proto`](../../../../protos/game-design/v1/tenant_identity_service.proto) is the wire authority. The scoped durable-identity boundary remains [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) and [Multi-tenancy](../../system-architecture-multi-tenancy.md); this read does not derive or reassign another owner's identifiers. - -The only permitted peer is the verified Game Session workload identity `spiffe://firemud/ns/{namespace}/sa/game-session-service`, where `{namespace}` must exactly match Game Design's configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. An empty or invalid configured namespace, absent verified peer identity, another service identity, or a peer from another namespace returns `PERMISSION_DENIED`. JWT claims and request metadata are not peer identity; workload authentication follows [Authentication and Authorization](../../system-architecture-authentication.md). - -The shared `AuthTokenInterceptor` configuration exempts exactly this full RPC method name from bearer-token validation because this is a workload-only method under [ADR 0038](../../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). This is not public transport exposure: the gRPC listener still requires mTLS, and the handler requires the exact verified workload identity above. No other Game Design RPC is exempted. - -The request contains exactly two fields: `canonical_tenant_id` and `request_id`, each a canonical lower-case, nonnil UUID string. Unknown protobuf fields, noncanonical/nil IDs, or a missing ID return `INVALID_ARGUMENT`. The tenant UUID is only a selector: Game Design returns it only after an exact canonical-UUID lookup and owner-row provenance validation. - -The response fields are `schema_version` (currently `1`), `target_namespace` (the configured workload namespace, not a playable-state namespace), the exact echoed `request_id`, `canonical_tenant_id`, positive internal `source_game_row_id`, exact retained `source_game_tenant_key`, and `provenance_kind` (`RETAINED_GAME_V29` or `NEW_GAME_ROW`). The tenant UUID and source provenance are issued/read from the same Game Design owner row; callers must not translate the legacy key or row ID into another identity. - -Bounded transport outcomes are: `NOT_FOUND` when no owner row exists for the exact UUID; `FAILED_PRECONDITION` for missing, ambiguous, malformed, or inconsistent persisted provenance; `UNAVAILABLE` for unavailable storage/connection failures; and `INTERNAL` for other read failures. No partial evidence is returned on error. This method does not return a version-bound realm-entry policy, descriptor/template identity, current Game Session pointer, or playable-state namespace/scope; those owner compositions and [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md) actor-entry behavior remain separate, incomplete work. - These gRPC entries are the discoverability index for the control-plane contracts described in [Game Templates and Configuration Tools](game-templates.md) and related architecture docs. When request/response schemas evolve, the proto contract and those architecture sections must be updated in the same change so launch-resolution and template-phase semantics do not drift. ## REST & gRPC Endpoints diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 7ca506ddb7..c9d672311e 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -33,7 +33,7 @@ Routine rollback is expected to leave ordinary gameplay available while scoped A - Current `POST /logs/query` and `QueryLogs` read only the service-owned PostgreSQL `log_events` table. They require an exact tenant and apply case-insensitive containment to the stored message, returning the matching messages. They do not query deployed structured logs, mirror data to Elasticsearch, prove the ADR 0162 emitter-to-query path, implement a compatible indexed or console/journal profile, or expose Kibana/Grafana embedding. - The current moderation proto's `scope` and `action` fields are unrestricted strings, which is drift from ADR 0141's closed typed target rather than permission to accept arbitrary categories. Converged moderation ingress must validate the closed-category, typed-scope vocabulary and reject unknown values, `account_security_lock`, and its aliases before persistence. Only Account-owned security policy and recovery may create, extend, expire, remove, or clear `account_security_lock`; the moderation action route cannot create or clear it. `EvaluateModerationPolicy` remains a live read and carries no mutation authorization reference. - Admission-pointer reads, audit, and prepared-upgrade proof reads are part of the core operator/control-plane availability model and must not depend on observability backends. `GET /admission-pointers` returns unavailable when a current pointer lacks matching latest audit identity/catalog evidence; historical audit remains a raw read that preserves unknown legacy identity. Admission-pointer mutation and preparation handlers are absent from public HTTP ingress and OpenAPI; their internal service/control-plane implementation must not be described as current live operator mutation support. -- The internal `SetAdmissionPointerRequest` DTO omits `actorPrincipal`. `AdmissionPointerServiceImpl` derives the actor from the authenticated internal caller context and writes that derived value to the control-plane request; `actorPrincipal` is response/audit data, not client-supplied write authority. +- The internal `SetAdmissionPointerRequest` DTO omits `actorPrincipal`. `AdmissionPointerServiceImpl` derives the actor from the authenticated internal caller context and writes the canonical Account UUID for an account caller (or `internal-service` when no account subject is present) to the control-plane request; `actorPrincipal` is response/audit data, not client-supplied write authority. - Public administrative report persistence is currently unavailable. The unsafe controller that formerly occupied `POST /reports` and its `/api/admin/reports/**` Gateway exposure have been removed because the canonical role- and purpose-scoped authorization and live reference-validation checks are not implemented. Any restored administrative surface uses the distinct `POST /admin/reports` service path. `POST /reports` is reserved for the separate player-bootstrap submission contract and must bind the `player-bootstrap` subject and live tenant membership; it must not be inferred from or share the unavailable administrative route. The internal `CreateReport` gRPC contract is not public HTTP or player ingress, but its target exact workload/method authorization is unproved: current transport mTLS alone does not establish an allowlisted receiver identity. The interim receiver requires an internal-service JWT naming `social-groups-service`, while certificate-derived exact workload/method authorization remains unproved. Caller-supplied tenant, reporter, and optional target identities are data references only. - `ApplyModerationAction` has an implementation path, but `/moderation/actions` plus the gRPC action now hard fail closed after narrow tenant/admin checks. HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported/nonconformant drift, not available mutation support. The target gate requires the action-family schema, shared cross-language `mutationDigest/v1` vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption. Separate fixed-category policy/audit evidence and owner enforcement are absent, and no forwarding occurs. Target behavior is Logging & Admin intent/case/audit persistence followed by exactly-once redemption of its local Account reference; that reference is never forwarded. A separate future owner-enforcement command has its own Account reference and receiving-owner redemption. The separate live `EvaluateModerationPolicy` contract supplies synchronous decisions consumed by Game Session at `GAMEPLAY_ADMISSION` and Social & Groups at `CHAT_SEND`; that compatibility read is a legacy, deny-only lookup over generic action rows ordered by recency, is nonconformant with ADR 0141's broadest-effect response precedence (`platform_access_ban` over `account_security_lock`, `chat_ban` over `chat_mute`), and does not implement or prove all five fixed categories or their independent lifecycles. It is not operator mutation support. Fixed-category owner-local enforcement, bounded appeals, and broader coverage remain target work under [Moderation Policies](./moderation-policies.md). - Quota-override ingress is a hypothetical target family until Account exposes the canonical owner-side override mutation contract; no executable route exists today. diff --git a/design/architecture/microservices/social-groups-service/api-contracts.md b/design/architecture/microservices/social-groups-service/api-contracts.md index 5894635e65..b51dbabc22 100644 --- a/design/architecture/microservices/social-groups-service/api-contracts.md +++ b/design/architecture/microservices/social-groups-service/api-contracts.md @@ -16,6 +16,8 @@ The target chat write contract derives `senderAccountId` from authenticated call The friend-presence slice currently implements non-pageable friend-roster and presence reads over tenant-scoped mutually accepted reciprocal links whose two directed rows are both `active`; that is implementation status, not the target relationship authority. The player-facing Gateway `/api/social/friends` route is removed/unavailable because the current endpoint path has no directional block-state model or block revalidation. The direct service-local implementation remains available for direct-service and future non-edge use and retains reciprocal-active filtering, but it does not claim the target player-facing safety boundary. The target distinguishes tenant-free account-pair relationships from separate tenant-local records and binds each group to one declared membership subject type. One-way links, inactive reciprocal links, and links stored under another tenant are not endpoint-visible; focused integration proof covers those boundaries in [SocialGroupsApplicationIntegrationTest.java](../../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java). It does not create snapshots, continuations, or paginated bulk pages. Snapshot-bound continuation, continuation-time relationship and block revalidation, bounded paginated bulk reads, and the failure-precedence contract below remain target behavior; this document does not claim that the current implementation or existing tests prove those target obligations. +Account-owned identity now uses canonical UUID account IDs, but the live Social relationship rows and DTOs still persist numeric Account row IDs and carry no trusted UUID/provenance mapping. Consequently, the existing Account profile calls cannot safely become canonical cross-account reads, and presence-policy batching cannot yet send canonical Account IDs. Account `GetProfile` and `UpdateProfile` remain exact self-subject operations; cross-account friend-presence policy must use the minimized `ListPresenceVisibilityPolicies` workload read after Social has a trusted mapping. Account-local UUID-to-row resolution remains private to Account. Do not infer UUIDs from Social's numeric values or forward those private row IDs as canonical cross-owner identity. + The current chat writer paths remain internal/non-player-safe: the Gateway `/api/social/chat` edge route is removed/unavailable, while service-local `/chat` and gRPC `SendMessage` still use the request-body `senderAccountId` with the Social access guard. The synchronous `EvaluateModerationPolicy` read at `CHAT_SEND` remains the current Logging & Admin hot-path compatibility seam and is consumed only after a cache/replay miss. Replay storage and lookup remain tenant/effect-only and occur before that policy check, with no authenticated-caller or full request-digest binding. The duplicate-effect catch also queries after a unique violation in the same outer transaction, so PostgreSQL transaction-abort/rollback-only behavior is not a reliable replay result; conflict-safe insert or isolated transaction handling and real concurrent proof remain required. Owner-local restriction state, essential notices, independent stacking, expiry/reordering, appeal handling, and the target gate are not yet implemented or proved; these writers therefore remain nonconformant to the target contract above. Guild membership is account-only in the current implementation: the live `guild_members` schema, DTOs, and controllers persist and authorize `accountId` and have no character subject or declared subject-type field. The `ACCOUNT`/`CHARACTER` choice below is target behavior and remains unimplemented for `CHARACTER`; the current account route must not be read as proof of the richer target model. 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 ca4a4faa4d..62c98d61e5 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,8 +8,6 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. -Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; the issuance and source provenance are immutable. Reported compilation and `generateJooq` succeeded; focused `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2. The PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. This does not prove a Game Design-published version-bound realm-entry policy, descriptor/template identity, Game Session pointer/namespace/scope composition, Entity actor admission, or actor creation/activation. The method contract and status boundary are owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#runtime-tenant-identity-owner-read); actor-entry target behavior remains [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). - 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. @@ -180,7 +178,6 @@ Game Design owns revision history, commits, version state, and publish orchestra - Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the current participant observations and first World mutation handoff do not yet establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. The current implementation lacks the version-scoped asset mapping/authoring path and corresponding publication/export guard; purge and publication recovery also lack complete durable operation, CAS, and exact readback proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. -- Realm-authored controllable actor entry remains incomplete: no explicit published per-version `PLAYER_CREATED` / `PRESEEDED_ONLY` / `AUTO_PROVISIONED` policy with its required descriptor/template identity and version is resolved, and Game Session's current owner pointer/namespace/scope is not yet composed with Entity's fail-closed admission/creation path. The canonical tenant UUID read above supplies owner-row provenance only and is not entry-policy or actor-creation proof. - Normalized-template cutover phase is target-only: no tenant-scoped `GetTemplateReferencePhase` RPC, durable phase authority, or `BACKFILLING`/`VALIDATED`/`ENFORCED` consumer contract exists in the current slice; live launch checks only the per-template `ENFORCED`/`LEGACY` field. The target API and fail-before-launch behavior remain unimplemented and unproved. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. - World design authoring currently has the first typed revision-to-World handoff, including the transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. Broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain outside the current seam. 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 df035f12fb..2ea2d50b26 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,11 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Account's persisted UUID backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. The current candidate extends UUID identity through Account authentication, bootstrap, and profile producers and through the carrier paths described below; tenant identity fields and unrelated numeric-only consumers remain incomplete. Numeric Account-claim consumers still outside this cohort include common-security `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, Social & Groups current-account authorization, and Game Session's numeric control-plane owner authorization. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no deployed/fresh-runtime or global downstream migration proof. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). +Account's persisted UUID backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. The current candidate extends UUID identity through Account authentication, bootstrap, and profile producers and through the carrier paths described below; tenant identity fields and unrelated numeric-only consumers remain incomplete. `GrpcClientAuth` already canonicalizes UUID identity; the shared direct Account-claim reader is `SessionContext.currentAccountUuidOrNull`, now used by Logging & Admin actor attribution and Automation Scripting dry-run principal keys. Social & Groups current-account authorization and Game Session's numeric control-plane owner authorization still compare numeric identifiers. Social's persisted relationship subjects currently have no trusted Account UUID mapping, so cross-account Account profile/presence calls remain a separate unresolved boundary. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no deployed/fresh-runtime or global downstream migration proof. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). This candidate now carries Account UUID through Account authentication, bootstrap, and profile producers; Common Security subject/account matching; Gateway gameplay-handshake validation; and Game Session and Game Logic carriers. Reported focused unit and formatting tasks passed for Account, Common Security, Gateway, Game Logic, and Game Design; the focused Game Session suite passed 262/262. This is candidate source/test proof, not deployed or fresh-runtime proof, and it does not establish global convergence of numeric Account consumers or backfill historical command UUIDs. Canonical identity and namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Account's `ResolveRuntimeAccountIdentity` owner read has focused service proof (7/7) and auth-wiring proof (3/3); Entity Management's Account identity receiver test passed 7/7. Those reads carry persisted UUID and source-row/provenance evidence but do not create membership, grants, actor ownership, a namespace, or admission authority; Game Session caller wiring remains unclaimed. Focused Game Session proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. Game Session now rejects unreadable or wrong-type registry evidence before persisted-context fallback and preserves numeric/opaque account evidence without mutation. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. `PLAYER`/`PLAY`, actor association/namespace roster, and full-stack fresh-smoke proof remain incomplete. #2898 remains unresolved. -Game Design now exposes an authenticated owner-local canonical tenant UUID/provenance read intended for Game Session; this slice claims no Game Session caller wiring. The producer is independent of Account UUID authentication and does not establish the current Game Session pointer, playable-state namespace/scope, published actor-entry policy, Entity selection, or actor creation. Its contract and focused proof status are recorded in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#runtime-tenant-identity-owner-read) and the [Game authoring, publishing, and activation tracker](./game-authoring-publishing-and-activation.md). `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +The Game Design canonical tenant UUID/provenance producer and its Game Session receiver are prepared in a separate retained-tenant association prerequisite, not this Account UUID carrier slice. That prerequisite must prove source identity and exact retained-row association without establishing the current Game Session pointer, playable-state namespace/scope, published actor-entry policy, Entity selection, or actor creation. `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index ff20d2c324..0c80fda31e 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -14,6 +14,9 @@ service AccountService { rpc Authenticate(AuthenticateRequest) returns (AuthenticateResponse); rpc RequestEmailLoginOtp(RequestEmailLoginOtpRequest) returns (RequestEmailLoginOtpResponse); rpc VerifyEmailLoginOtp(VerifyEmailLoginOtpRequest) returns (AuthenticateResponse); + // Exact Game Session workload only. account_id is the canonical non-nil Account UUID; Account + // resolves its private storage row internally and echoes the requested UUID in the response. + // tenant_id remains a positive numeric tenant identifier and request_id is passed unchanged. rpc GetTenantMembershipForRuntime(GetTenantMembershipForRuntimeRequest) returns (GetTenantMembershipForRuntimeResponse); rpc GetRealmAccessGrantForRuntime(GetRealmAccessGrantForRuntimeRequest) returns (GetRealmAccessGrantForRuntimeResponse); rpc GetTenantEntitlementsForRuntime(GetTenantEntitlementsForRuntimeRequest) returns (GetTenantEntitlementsForRuntimeResponse); @@ -198,7 +201,9 @@ message GetProfileResponse { shared.v1.ErrorDetail error = 2; } -// Internal bounded bulk read used by Social Groups when projecting friend presence. +// Exact same-namespace Social & Groups mTLS workload only. Accepts at most 100 canonical non-nil +// Account UUIDs; Account resolves private storage rows internally and returns UUID-keyed policies. +// Unknown or unproven subjects are omitted so the caller applies complete PRIVATE redaction. message ListPresenceVisibilityPoliciesRequest { string tenant_id = 1; repeated string account_ids = 2; diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto deleted file mode 100644 index 9d88ce123e..0000000000 --- a/protos/game-design/v1/tenant_identity_service.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; - -package gamedesign.v1; - -option java_package = "net.firedevops.firemud.gamedesign.v1"; -option java_multiple_files = true; - -// Authenticated owner-local read of Game Design's persisted tenant identity. -service TenantIdentityService { - rpc ResolveRuntimeTenantIdentity(ResolveRuntimeTenantIdentityRequest) - returns (ResolveRuntimeTenantIdentityResponse); -} - -message ResolveRuntimeTenantIdentityRequest { - string canonical_tenant_id = 1; - string request_id = 2; -} - -message ResolveRuntimeTenantIdentityResponse { - int32 schema_version = 1; - string target_namespace = 2; - string request_id = 3; - string canonical_tenant_id = 4; - int64 source_game_row_id = 5; - string source_game_tenant_key = 6; - string provenance_kind = 7; -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 44728f45bd..5ce1b5d35e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -435,14 +435,22 @@ public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + long accountStorageId = accountService.resolveAccountStorageId(accountUuid); var dto = accountService.getTenantMembershipForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getRequestId()); + accountStorageId, tenantId, request.getRequestId()); + if (dto == null + || !Long.valueOf(accountStorageId).equals(dto.accountId()) + || !Long.valueOf(tenantId).equals(dto.tenantId())) { + throw new IllegalStateException( + "Account membership authority returned an inconsistent identity"); + } GetTenantMembershipForRuntimeResponse response = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) + .setAccountId(accountUuid.toString()) .setTenantId(String.valueOf(dto.tenantId())) .setMembershipExists(dto.membershipExists()) .setGameplayAdmissionAllowed(dto.gameplayAdmissionAllowed()) @@ -453,6 +461,13 @@ public void getTenantMembershipForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + appError("GetTenantMembershipForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetTenantMembershipForRuntimeResponse response = GetTenantMembershipForRuntimeResponse.newBuilder() @@ -468,6 +483,16 @@ public void getTenantMembershipForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onNext( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + appError( + "GetTenantMembershipForRuntime", + "AUTH_UNAVAILABLE", + AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } @@ -606,29 +631,67 @@ public void listPresenceVisibilityPolicies( StreamObserver responseObserver) { try { + requireSocialGroupsPeer(); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); if (request.getAccountIdsCount() > MAX_ACCOUNT_IDS_PER_REQUEST) { throw new InvalidRequestException( "accountIds must contain at most " + MAX_ACCOUNT_IDS_PER_REQUEST + " entries", null); } - java.util.List accountIds = + java.util.List accountUuids = request.getAccountIdsList().stream() - .map(accountId -> requirePositiveRequestId(accountId, "accountId")) + .map(AccountGrpcService::requireCanonicalAccountUuid) .distinct() .toList(); + java.util.Map storageIdsByAccountUuid = new java.util.LinkedHashMap<>(); + java.util.Map accountUuidsByStorageId = new java.util.HashMap<>(); + for (UUID accountUuid : accountUuids) { + Long storageId; + try { + storageId = accountService.resolveAccountStorageId(accountUuid); + } catch (IllegalArgumentException | IllegalStateException ex) { + // Unknown or unproven local subjects are omitted so Social applies complete PRIVATE + // redaction rather than receiving a guessed identity or a private storage key. + continue; + } + if (storageId == null || storageId <= 0L) { + continue; + } + UUID previousAccountUuid = accountUuidsByStorageId.putIfAbsent(storageId, accountUuid); + if (previousAccountUuid != null && !previousAccountUuid.equals(accountUuid)) { + throw new IllegalStateException("Account UUID resolution returned an ambiguous row"); + } + storageIdsByAccountUuid.put(accountUuid, storageId); + } + java.util.List storageIds = java.util.List.copyOf(storageIdsByAccountUuid.values()); + java.util.Map policies = + storageIds.isEmpty() + ? java.util.Map.of() + : accountService.listPresenceVisibilityPolicies(tenantId, storageIds); + for (java.util.Map.Entry policy : + policies.entrySet()) { + if (!accountUuidsByStorageId.containsKey(policy.getKey()) || policy.getValue() == null) { + throw new IllegalStateException( + "Presence visibility policy read returned an unexpected Account row"); + } + } var builder = net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder(); - accountService - .listPresenceVisibilityPolicies(tenantId, accountIds) - .forEach( - (accountId, policy) -> - builder.addPolicies( - net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry.newBuilder() - .setAccountId(Long.toString(accountId)) - .setPolicy(policy.name()) - .build())); + policies.forEach( + (storageId, policy) -> + builder.addPolicies( + net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(accountUuidsByStorageId.get(storageId).toString()) + .setPolicy(policy.name()) + .build())); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() + .setError( + appError("ListPresenceVisibilityPolicies", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { responseObserver.onNext( net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() @@ -645,7 +708,11 @@ public void listPresenceVisibilityPolicies( } catch (RuntimeException ex) { responseObserver.onNext( net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() - .setError(appError("ListPresenceVisibilityPolicies", "INTERNAL", ex.getMessage())) + .setError( + appError( + "ListPresenceVisibilityPolicies", + "INTERNAL", + "Presence visibility policy lookup failed")) .build()); responseObserver.onCompleted(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java index a109fe7288..5e9dc7270a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.sql.SQLException; @@ -27,6 +28,10 @@ public class RuntimeAccountIdentityGrpcService private final AccountRepository accountRepository; private final String workloadNamespace; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "AccountRepository is an injected internal owner collaborator, not exposed state.") public RuntimeAccountIdentityGrpcService( AccountRepository accountRepository, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 130c82c21d..d37794baa1 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -72,6 +72,7 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping + - account.v1.AccountService/ListPresenceVisibilityPolicies - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 027fc23c34..bc0123d633 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -99,6 +99,7 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping + - account.v1.AccountService/ListPresenceVisibilityPolicies - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java index d6293c0d54..fde3feb614 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -23,11 +23,17 @@ import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesRequest; +import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse; import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.PingService; +import net.firedevops.firemud.accountservice.service.impl.AccountGrpcService; import net.firedevops.firemud.accountservice.service.impl.RuntimeAccountIdentityGrpcService; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -50,9 +56,13 @@ class RuntimeAccountIdentityGrpcAuthWiringTest { "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; private static final String NONPUBLIC_METHOD = "account.v1.AccountService/GetRealmAccessGrantForRuntime"; + private static final String PRESENCE_METHOD = + "account.v1.AccountService/ListPresenceVisibilityPolicies"; private static final String ACCOUNT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String SOCIAL_GROUPS_URI = + "spiffe://firemud/ns/test/sa/social-groups-service"; private static final String ENTITY_MANAGEMENT_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; private static final MethodDescriptor< @@ -69,6 +79,13 @@ class RuntimeAccountIdentityGrpcAuthWiringTest { NONPUBLIC_METHOD, GetRealmAccessGrantForRuntimeRequest.getDefaultInstance(), GetRealmAccessGrantForRuntimeResponse.getDefaultInstance()); + private static final MethodDescriptor< + ListPresenceVisibilityPoliciesRequest, ListPresenceVisibilityPoliciesResponse> + PRESENCE_METHOD_DESCRIPTOR = + unaryMethod( + PRESENCE_METHOD, + ListPresenceVisibilityPoliciesRequest.getDefaultInstance(), + ListPresenceVisibilityPoliciesResponse.getDefaultInstance()); @Test void exactSameNamespaceRuntimePeersReachReadOnlyHandlerUnderBaseAndProdYaml() { @@ -176,6 +193,67 @@ void unrelatedAccountMethodRemainsBearerProtectedUnderBothYamlLayers() { } } + @Test + void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + AccountService accountService = mock(AccountService.class); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + when(accountService.listPresenceVisibilityPolicies(1L, List.of(42L))) + .thenReturn(Map.of(42L, ProfilePresenceVisibilityPolicy.PRIVATE)); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), accountService, null, "test"); + + PresenceDispatchResult result = + dispatchPresenceMethod(interceptor, service, SOCIAL_GROUPS_URI, null); + + assertThat(result.handlerDispatched()).isTrue(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getPoliciesCount()).isEqualTo(1); + assertThat(result.observer().response.getPolicies(0).getAccountId()) + .isEqualTo(ACCOUNT_UUID); + assertThat(result.observer().response.getPolicies(0).getPolicy()).isEqualTo("PRIVATE"); + verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + verify(accountService).listPresenceVisibilityPolicies(1L, List.of(42L)); + }); + } + } + + @Test + void bearerOnlyPresenceRequestReachesHandlerButIsDeniedWithoutSocialPeerUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, jwtUtil) -> { + AccountService accountService = mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), accountService, null, "test"); + String bearer = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of( + "accountId", + ACCOUNT_UUID, + "globalRoles", + List.of("platformAdmin"), + "scopedRoles", + Map.of())); + + PresenceDispatchResult result = + dispatchPresenceMethod(interceptor, service, null, bearer); + + assertThat(result.handlerDispatched()).isTrue(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + verifyNoInteractions(accountService); + }); + } + } + private static Account persistedAccount() { Account account = new Account(); account.setId(42L); @@ -242,6 +320,63 @@ public void onMessage(ResolveRuntimeAccountIdentityRequest request) { return new DispatchResult(observer, handlerDispatched.get()); } + private static PresenceDispatchResult dispatchPresenceMethod( + AuthTokenInterceptor interceptor, + AccountGrpcService service, + String peerUri, + String bearerToken) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(PRESENCE_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + PresenceTestObserver observer = new PresenceTestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ListPresenceVisibilityPoliciesRequest, + ListPresenceVisibilityPoliciesResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ListPresenceVisibilityPoliciesRequest request) { + service.listPresenceVisibilityPolicies(request, observer); + } + }; + } + }; + ListPresenceVisibilityPoliciesRequest request = + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds(ACCOUNT_UUID) + .build(); + Metadata headers = new Metadata(); + if (bearerToken != null) { + headers.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + bearerToken); + } + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new PresenceDispatchResult(observer, handlerDispatched.get()); + } + private static void withConfiguredInterceptor( boolean productionLayer, java.util.function.BiConsumer action) { @@ -281,6 +416,7 @@ private static void withConfiguredInterceptor( assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) .contains(IDENTITY_METHOD) + .contains(PRESENCE_METHOD) .doesNotContain(NONPUBLIC_METHOD); action.accept( context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); @@ -301,6 +437,8 @@ MethodDescriptor unaryMethod( private record DispatchResult(TestObserver observer, boolean handlerDispatched) {} + private record PresenceDispatchResult(PresenceTestObserver observer, boolean handlerDispatched) {} + private static final class TestObserver implements StreamObserver { private ResolveRuntimeAccountIdentityResponse response; @@ -324,4 +462,25 @@ public void onCompleted() { completed = true; } } + + private static final class PresenceTestObserver + implements StreamObserver { + private ListPresenceVisibilityPoliciesResponse response; + private boolean completed; + + @Override + public void onNext(ListPresenceVisibilityPoliciesResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + throw new AssertionError("Expected Account application response", throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 4ef94020b4..d594df2858 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -893,97 +893,261 @@ void getProfileRejectsMismatchedCallerSubjectBeforeStorageResolution() { Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); } + private static ListPresenceVisibilityPoliciesRequest presencePolicyRequest( + String... accountUuids) { + ListPresenceVisibilityPoliciesRequest.Builder builder = + ListPresenceVisibilityPoliciesRequest.newBuilder().setTenantId("1"); + for (String accountUuid : accountUuids) { + builder.addAccountIds(accountUuid); + } + return builder.build(); + } + @Test - void listPresenceVisibilityPoliciesMapsPersistedPolicies() { + void listPresenceVisibilityPoliciesResolvesAndReturnsCanonicalUuidKeysForSocialPeer() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) + .thenReturn(3L); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L, 3L))) .thenReturn( Map.of( 2L, ProfilePresenceVisibilityPolicy.PRIVATE, 3L, ProfilePresenceVisibilityPolicy.HIDDEN_STAFF)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .addAccountIds("3") - .addAccountIds("2") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, OTHER_ACCOUNT_UUID, ACCOUNT_UUID), observer)); assertNotNull(observer.response()); assertEquals(2, observer.response().getPoliciesCount()); + assertEquals( + java.util.Set.of(ACCOUNT_UUID, OTHER_ACCOUNT_UUID), + observer.response().getPoliciesList().stream() + .map(entry -> entry.getAccountId()) + .collect(java.util.stream.Collectors.toSet())); assertTrue( observer.response().getPoliciesList().stream() .anyMatch( - entry -> entry.getAccountId().equals("2") && entry.getPolicy().equals("PRIVATE"))); + entry -> + entry.getAccountId().equals(ACCOUNT_UUID) + && entry.getPolicy().equals("PRIVATE"))); assertTrue( observer.response().getPoliciesList().stream() .anyMatch( entry -> - entry.getAccountId().equals("3") && entry.getPolicy().equals("HIDDEN_STAFF"))); + entry.getAccountId().equals(OTHER_ACCOUNT_UUID) + && entry.getPolicy().equals("HIDDEN_STAFF"))); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID)); Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); } - @Test - void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { + @ParameterizedTest + @ValueSource( + strings = { + "2", + "0", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B" + }) + void listPresenceVisibilityPoliciesRejectsNonCanonicalAccountUuidBeforeResolution( + String accountId) { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("0") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, accountId), observer)); - assertNotNull(observer.response()); assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); - assertEquals("accountId must be positive", observer.response().getError().getMessage()); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); Mockito.verifyNoInteractions(accountService); } @Test - void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { + void listPresenceVisibilityPoliciesRejectsOverLimitBeforeResolution() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + String[] accountUuids = + java.util.stream.LongStream.rangeClosed(1L, 101L) + .mapToObj(value -> new UUID(0L, value).toString()) + .toArray(String[]::new); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies(presencePolicyRequest(accountUuids), observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void listPresenceVisibilityPoliciesRequiresExactSocialWorkloadPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List deniedPeers = + List.of( + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/account-service", "test", "account-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service"), + GAME_SESSION_PEER); + RecordingObserver noPeerObserver = + new RecordingObserver<>(); + + service.listPresenceVisibilityPolicies(presencePolicyRequest(ACCOUNT_UUID), noPeerObserver); + for (GrpcPeerIdentity peer : deniedPeers) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer( + peer, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID), observer)); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + + assertEquals("PERMISSION_DENIED", noPeerObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void listPresenceVisibilityPoliciesOmitsUnknownAndUnprovenSubjects() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + String unprovenAccountUuid = "00000000-0000-4000-8000-000000000003"; + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) + .thenThrow(new IllegalArgumentException("Account not found")); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(unprovenAccountUuid))) + .thenThrow(new IllegalStateException("Account identity provenance is unavailable")); + Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) + .thenReturn(Map.of(2L, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, OTHER_ACCOUNT_UUID, unprovenAccountUuid), + observer)); + + assertEquals(1, observer.response().getPoliciesCount()); + assertEquals(ACCOUNT_UUID, observer.response().getPolicies(0).getAccountId()); + assertEquals("FRIENDS_ONLY", observer.response().getPolicies(0).getPolicy()); + Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L)); + } + + @Test + void listPresenceVisibilityPoliciesRejectsAliasedResolverRowsWithoutPolicyRead() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) + .thenReturn(2L); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, OTHER_ACCOUNT_UUID), observer)); + assertEquals("INTERNAL", observer.response().getError().getCode()); + assertEquals(0, observer.response().getPoliciesCount()); + Mockito.verify(accountService, Mockito.never()) + .listPresenceVisibilityPolicies(Mockito.anyLong(), Mockito.anyList()); + } + + @Test + void listPresenceVisibilityPoliciesRejectsUnexpectedStorageRowsWithoutPolicyResults() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) + .thenReturn(Map.of(3L, ProfilePresenceVisibilityPolicy.PRIVATE)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies(presencePolicyRequest(ACCOUNT_UUID), observer)); + + assertEquals("INTERNAL", observer.response().getError().getCode()); + assertEquals(0, observer.response().getPoliciesCount()); + } + + @Test + void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenThrow(new IllegalArgumentException("Tenant not found")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver notFoundObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - notFoundObserver); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID), notFoundObserver)); assertEquals("NOT_FOUND", notFoundObserver.response().getError().getCode()); assertTrue(notFoundObserver.completed()); assertFalse(notFoundObserver.receivedTransportError()); Mockito.reset(accountService); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenThrow(new IllegalStateException("Policy lookup unavailable")); RecordingObserver internalObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - internalObserver); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID), internalObserver)); assertEquals("INTERNAL", internalObserver.response().getError().getCode()); assertTrue(internalObserver.completed()); @@ -994,59 +1158,74 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors void getTenantMembershipForRuntimeReturnsResponse() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( 2L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantMembershipForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); - assertEquals("2", ref.get().getAccountId()); + assertEquals(ACCOUNT_UUID, ref.get().getAccountId()); assertTrue(ref.get().getMembershipExists()); assertTrue(ref.get().getGameplayAdmissionAllowed()); assertEquals(44L, ref.get().getMembershipVersion()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService).getTenantMembershipForRuntime(2L, 1L, "req-1"); } @Test void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); assertNotNull(observer.response()); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertFalse(observer.response().getMembershipExists()); assertTrue(observer.response().getGameplayAdmissionAllowed()); assertTrue(observer.completed()); @@ -1057,27 +1236,31 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( void getTenantMembershipForRuntimeRejectsZeroTenantIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("0") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("0") + .setRequestId("req-1") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantMembershipForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1085,6 +1268,116 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource( + strings = { + "2", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAe05e8-7a6b-4b14-9d44-665e3eec450b" + }) + void getTenantMembershipForRuntimeRejectsNonCanonicalAccountId(String accountId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(accountId) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void getTenantMembershipForRuntimeRejectsMissingGameSessionPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void getTenantMembershipForRuntimeFailsClosedWhenPrivateAccountDoesNotCorrelate() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( + 3L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + + @Test + void getTenantMembershipForRuntimeFailsClosedWhenPrivateTenantDoesNotCorrelate() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( + 2L, 3L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + @Test void getRealmAccessGrantForRuntimeRejectsZeroAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java index 31b1d7f0d0..1eead61106 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java @@ -1611,9 +1611,9 @@ private static String resolveSourceService() { } private static String dryRunPrincipalKey() { - Long accountId = SessionContext.currentAccountIdOrNull(); - if (accountId != null) { - return "account:" + accountId; + String accountUuid = SessionContext.currentAccountUuidOrNull(); + if (accountUuid != null) { + return "account:" + accountUuid; } String serviceName = SessionContext.getServiceName(); if (serviceName != null && !serviceName.isBlank()) { diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java index 7ba9937a36..fe90ccfe14 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java @@ -3182,7 +3182,12 @@ void quotaDeniedHandlerWritesAuditWithoutWorkItem() { @Test void dryRunBudgetDenialStopsBeforeHandlerResolution() { SessionContext.setContext( - "41", List.of("platformAdmin"), Map.of(), true, "game-session-service", "gs-1"); + "11111111-1111-1111-1111-111111111111", + List.of("platformAdmin"), + Map.of(), + true, + "game-session-service", + "gs-1"); ScriptEventIngressAuditRepository repository = Mockito.mock(ScriptEventIngressAuditRepository.class); stubClaimRepository(repository); @@ -3202,7 +3207,9 @@ void dryRunBudgetDenialStopsBeforeHandlerResolution() { .setScriptPatchPinnedControlPlaneRequestId("pin-request-1") .build()) .build()); - when(dryRunQuotaService.tryAcquire("1", "script-1", "account:41")).thenReturn(false); + when(dryRunQuotaService.tryAcquire( + "1", "script-1", "account:11111111-1111-1111-1111-111111111111")) + .thenReturn(false); ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); ScriptEventIngressService service = diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java deleted file mode 100644 index 06366df88b..0000000000 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.firedevops.firemud.common.tenant; - -import java.nio.charset.StandardCharsets; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; - -/** Immutable Game Design owner evidence for one persisted runtime tenant identity. */ -public record RuntimeTenantIdentityEvidence( - int schemaVersion, - String targetNamespace, - UUID requestId, - UUID canonicalTenantId, - long sourceGameRowId, - String sourceGameTenantKey, - String provenanceKind) { - private static final int SCHEMA_VERSION = 1; - private static final UUID NIL_UUID = new UUID(0L, 0L); - private static final int MAX_SOURCE_KEY_CODE_POINTS = 36; - private static final int MAX_SOURCE_KEY_UTF16_LENGTH = 72; - - public RuntimeTenantIdentityEvidence { - if (schemaVersion != SCHEMA_VERSION) { - throw new IllegalArgumentException("Unsupported runtime tenant identity schema version"); - } - if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { - throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); - } - requireNonNil(requestId, "requestId"); - requireNonNil(canonicalTenantId, "canonicalTenantId"); - if (sourceGameRowId <= 0) { - throw new IllegalArgumentException("sourceGameRowId must be positive"); - } - Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); - if (sourceGameTenantKey.isBlank() - || sourceGameTenantKey.length() > MAX_SOURCE_KEY_UTF16_LENGTH - || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) - > MAX_SOURCE_KEY_CODE_POINTS - || !StandardCharsets.UTF_8.newEncoder().canEncode(sourceGameTenantKey)) { - throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); - } - if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { - throw new IllegalArgumentException("Runtime tenant provenance kind is not recognized"); - } - } - - private static void requireNonNil(UUID value, String label) { - Objects.requireNonNull(value, label); - if (NIL_UUID.equals(value)) { - throw new IllegalArgumentException(label + " must not be nil"); - } - } -} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java deleted file mode 100644 index 0be76125d2..0000000000 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package net.firedevops.firemud.common.tenant; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.UUID; -import org.junit.jupiter.api.Test; - -class RuntimeTenantIdentityEvidenceTest { - private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); - - @Test - void acceptsNewAndRetainedOwnerEvidence() { - assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); - assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); - } - - @Test - void rejectsUnsupportedOrIncompleteOwnerEvidence() { - RuntimeTenantIdentityEvidence valid = evidence("NEW_GAME_ROW"); - assertInvalid( - 2, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalTenantId(), - valid.sourceGameRowId(), - valid.sourceGameTenantKey(), - valid.provenanceKind()); - assertInvalid( - 1, - "test.invalid", - valid.requestId(), - valid.canonicalTenantId(), - valid.sourceGameRowId(), - valid.sourceGameTenantKey(), - valid.provenanceKind()); - assertInvalid( - 1, - valid.targetNamespace(), - new UUID(0L, 0L), - valid.canonicalTenantId(), - valid.sourceGameRowId(), - valid.sourceGameTenantKey(), - valid.provenanceKind()); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - new UUID(0L, 0L), - valid.sourceGameRowId(), - valid.sourceGameTenantKey(), - valid.provenanceKind()); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalTenantId(), - 0, - valid.sourceGameTenantKey(), - valid.provenanceKind()); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalTenantId(), - valid.sourceGameRowId(), - " ", - valid.provenanceKind()); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalTenantId(), - valid.sourceGameRowId(), - "x".repeat(37), - valid.provenanceKind()); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalTenantId(), - valid.sourceGameRowId(), - "invalid-" + (char) 0xd800, - valid.provenanceKind()); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalTenantId(), - valid.sourceGameRowId(), - valid.sourceGameTenantKey(), - "UNKNOWN"); - } - - private static RuntimeTenantIdentityEvidence evidence(String provenanceKind) { - return new RuntimeTenantIdentityEvidence( - 1, "test", REQUEST_ID, TENANT_ID, 42L, "source-game-key-42", provenanceKind); - } - - private static void assertInvalid( - int schemaVersion, - String targetNamespace, - UUID requestId, - UUID canonicalTenantId, - long sourceGameRowId, - String sourceGameTenantKey, - String provenanceKind) { - assertThatThrownBy( - () -> - new RuntimeTenantIdentityEvidence( - schemaVersion, - targetNamespace, - requestId, - canonicalTenantId, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java index 5383df3e6f..6a5168858d 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java @@ -107,16 +107,16 @@ public static boolean hasAuthenticatedCallerContext() { } /** - * Returns the current account id when present. + * Returns the current canonical Account UUID when present. * - *

Blank or missing claims return {@code null}. Malformed or non-positive claims fail closed. + *

Blank or missing claims return {@code null}. Malformed, nil, or non-UUID claims fail closed. */ - public static Long currentAccountIdOrNull() { + public static String currentAccountUuidOrNull() { ClaimsData data = currentData(); if (data == null || data.accountId == null || data.accountId.isBlank()) { return null; } - return JwtClaims.requireLong(data.accountId, "accountId", false); + return JwtClaims.requireCanonicalAccountUuid(data.accountId, "accountId"); } /** Throws 403 when the current caller cannot act on the provided tenant. */ diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java index 9ae1889a51..0b2d2f7ab8 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java @@ -68,28 +68,32 @@ void currentAccountAccessRejectsNonPositiveCurrentAccountClaim() { } @Test - void currentAccountIdOrNullReturnsParsedAccountId() { - SessionContext.setContext("42", List.of(), Map.of()); + void currentAccountUuidOrNullReturnsCanonicalAccountUuid() { + String accountUuid = "11111111-1111-1111-1111-111111111111"; + SessionContext.setContext(accountUuid, List.of(), Map.of()); - assertTrue(SessionContext.currentAccountIdOrNull() == 42L); + assertTrue(accountUuid.equals(SessionContext.currentAccountUuidOrNull())); } @Test - void currentAccountIdOrNullReturnsNullWhenClaimMissing() { + void currentAccountUuidOrNullReturnsNullWhenClaimMissing() { SessionContext.clear(); - assertNull(SessionContext.currentAccountIdOrNull()); + assertNull(SessionContext.currentAccountUuidOrNull()); SessionContext.setContext(" ", List.of(), Map.of()); - assertNull(SessionContext.currentAccountIdOrNull()); + assertNull(SessionContext.currentAccountUuidOrNull()); } @Test - void currentAccountIdOrNullRejectsMalformedOrNonPositiveClaim() { + void currentAccountUuidOrNullRejectsMalformedNumericAndNilClaims() { SessionContext.setContext("not-a-long", List.of(), Map.of()); - assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountUuidOrNull); - SessionContext.setContext("0", List.of(), Map.of()); - assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); + SessionContext.setContext("42", List.of(), Map.of()); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountUuidOrNull); + + SessionContext.setContext("00000000-0000-0000-0000-000000000000", List.of(), Map.of()); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountUuidOrNull); } @Test diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java index 204de77695..83572c7198 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Game.java @@ -1,13 +1,11 @@ package net.firedevops.firemud.gamedesign.entity; -import java.util.UUID; import lombok.Data; @Data public class Game { private Long id; private String tenantId; - private UUID canonicalTenantId; private String name; private String description; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java index 2d3c2c6c40..f9a4d6c07c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/mapper/GameMapper.java @@ -3,12 +3,10 @@ import net.firedevops.firemud.gamedesign.dto.GameDto; import net.firedevops.firemud.gamedesign.entity.Game; import org.mapstruct.Mapper; -import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface GameMapper { GameDto toDto(Game entity); - @Mapping(target = "canonicalTenantId", ignore = true) Game toEntity(GameDto dto); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java index 638f33c93d..57bce6b96d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java @@ -2,10 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; -import java.util.Optional; -import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Game; -import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -21,14 +18,6 @@ public class GameRepository { private static final Table GAME_TABLE = DSL.table(DSL.name("game")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); - private static final Field CANONICAL_TENANT_ID = - DSL.field(DSL.name("canonical_tenant_id"), UUID.class); - private static final Field TENANT_IDENTITY_PROVENANCE_KIND = - DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); - private static final Field TENANT_IDENTITY_SOURCE_GAME_ID = - DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); - private static final Field TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID = - DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); private static final Field NAME = DSL.field(DSL.name("name"), String.class); private static final Field DESCRIPTION = DSL.field(DSL.name("description"), String.class); @@ -44,66 +33,22 @@ public List findAll() { public Game save(Game game) { if (game.getId() == null) { - if (game.getCanonicalTenantId() != null) { - throw new IllegalArgumentException("Canonical tenant identity is issued by Game Design"); - } Record record = dsl.insertInto(GAME_TABLE) .set(TENANT_ID, game.getTenantId()) .set(NAME, game.getName()) .set(DESCRIPTION, game.getDescription()) - .returning( - ID, - TENANT_ID, - CANONICAL_TENANT_ID, - TENANT_IDENTITY_PROVENANCE_KIND, - TENANT_IDENTITY_SOURCE_GAME_ID, - TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, - NAME, - DESCRIPTION) + .returning(ID, TENANT_ID, NAME, DESCRIPTION) .fetchOne(); - if (record == null) { - throw new IllegalStateException("Game insert did not return its persisted row"); - } - Game saved = toEntity(record); - GameTenantIdentity identity = toTenantIdentity(record); - if (saved == null - || saved.getId() == null - || !saved.getId().equals(identity.sourceGameId()) - || !saved.getTenantId().equals(identity.sourceLegacyTenantId()) - || identity.provenanceKind() != GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW) { - throw new IllegalStateException( - "Persisted game tenant identity did not match its owner row"); - } - return saved; + return toEntity(record); } - Condition identityCondition = ID.eq(game.getId()); - if (game.getTenantId() != null) { - identityCondition = identityCondition.and(TENANT_ID.eq(game.getTenantId())); - } - if (game.getCanonicalTenantId() != null) { - identityCondition = - identityCondition.and(CANONICAL_TENANT_ID.eq(game.getCanonicalTenantId())); - } - Record record = - dsl.update(GAME_TABLE) - .set(NAME, game.getName()) - .set(DESCRIPTION, game.getDescription()) - .where(identityCondition) - .returning( - ID, - TENANT_ID, - CANONICAL_TENANT_ID, - TENANT_IDENTITY_PROVENANCE_KIND, - TENANT_IDENTITY_SOURCE_GAME_ID, - TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID, - NAME, - DESCRIPTION) - .fetchOne(); - if (record == null) { - throw new IllegalStateException("Game update identity does not match a persisted game row"); - } - return toEntity(record); + dsl.update(GAME_TABLE) + .set(TENANT_ID, game.getTenantId()) + .set(NAME, game.getName()) + .set(DESCRIPTION, game.getDescription()) + .where(ID.eq(game.getId())) + .execute(); + return findByTenantId(game.getTenantId()); } public Game findByTenantId(String tenantId) { @@ -120,24 +65,6 @@ public Game findByTenantIdForUpdate(String tenantId) { .fetchOne(this::toEntity); } - /** Reads one persisted tenant UUID and validates its provenance against the actual owner row. */ - public Optional findRuntimeTenantIdentityByCanonicalTenantId( - UUID canonicalTenantId) { - if (canonicalTenantId == null) { - throw new IllegalArgumentException("Canonical tenant UUID is required"); - } - return dsl.select( - ID, - TENANT_ID, - CANONICAL_TENANT_ID, - TENANT_IDENTITY_PROVENANCE_KIND, - TENANT_IDENTITY_SOURCE_GAME_ID, - TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) - .from(GAME_TABLE) - .where(CANONICAL_TENANT_ID.eq(canonicalTenantId)) - .fetchOptional(this::toRuntimeTenantIdentity); - } - private Game toEntity(Record record) { if (record == null) { return null; @@ -145,65 +72,8 @@ private Game toEntity(Record record) { Game game = new Game(); game.setId(record.get(ID)); game.setTenantId(record.get(TENANT_ID)); - game.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); game.setName(record.get(NAME)); game.setDescription(record.get(DESCRIPTION)); return game; } - - private GameTenantIdentity toTenantIdentity(Record record) { - UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); - String provenanceKindValue = record.get(TENANT_IDENTITY_PROVENANCE_KIND); - Long sourceGameId = record.get(TENANT_IDENTITY_SOURCE_GAME_ID); - String sourceLegacyTenantId = record.get(TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID); - if (canonicalTenantId == null - || provenanceKindValue == null - || sourceGameId == null - || sourceGameId <= 0 - || sourceLegacyTenantId == null - || sourceLegacyTenantId.isBlank()) { - throw new IllegalStateException("Persisted game tenant identity provenance is incomplete"); - } - GameTenantIdentity.ProvenanceKind provenanceKind; - try { - provenanceKind = GameTenantIdentity.ProvenanceKind.valueOf(provenanceKindValue); - } catch (IllegalArgumentException exception) { - throw new IllegalStateException( - "Persisted game tenant identity provenance kind is unknown", exception); - } - return new GameTenantIdentity( - canonicalTenantId, provenanceKind, sourceGameId, sourceLegacyTenantId); - } - - private GameTenantIdentity toRuntimeTenantIdentity(Record record) { - Long actualGameId = record.get(ID); - String actualTenantKey = record.get(TENANT_ID); - UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID); - String provenanceKindValue = record.get(TENANT_IDENTITY_PROVENANCE_KIND); - Long sourceGameId = record.get(TENANT_IDENTITY_SOURCE_GAME_ID); - String sourceTenantKey = record.get(TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID); - if (actualGameId == null - || actualGameId <= 0 - || actualTenantKey == null - || actualTenantKey.isBlank() - || canonicalTenantId == null - || provenanceKindValue == null - || sourceGameId == null - || sourceGameId <= 0 - || sourceTenantKey == null - || !actualGameId.equals(sourceGameId) - || !actualTenantKey.equals(sourceTenantKey)) { - throw new IllegalStateException( - "Persisted runtime tenant identity provenance does not match its game row"); - } - - GameTenantIdentity.ProvenanceKind provenanceKind; - try { - provenanceKind = GameTenantIdentity.ProvenanceKind.valueOf(provenanceKindValue); - } catch (IllegalArgumentException exception) { - throw new IllegalStateException( - "Persisted runtime tenant identity provenance kind is unknown", exception); - } - return new GameTenantIdentity(canonicalTenantId, provenanceKind, actualGameId, actualTenantKey); - } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java deleted file mode 100644 index 10e7f0aae2..0000000000 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantIdentity.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.firedevops.firemud.gamedesign.repository; - -import java.util.UUID; - -/** Game Design's canonical tenant identity and exact provenance in its owning game row. */ -public record GameTenantIdentity( - UUID canonicalTenantId, - ProvenanceKind provenanceKind, - Long sourceGameId, - String sourceLegacyTenantId) { - public enum ProvenanceKind { - RETAINED_GAME_V29, - NEW_GAME_ROW - } -} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java deleted file mode 100644 index 15a26369a6..0000000000 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ /dev/null @@ -1,168 +0,0 @@ -package net.firedevops.firemud.gamedesign.service.impl; - -import io.grpc.Status; -import io.grpc.stub.StreamObserver; -import java.sql.SQLException; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; -import net.firedevops.firemud.gamedesign.repository.GameRepository; -import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; -import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; -import org.jooq.exception.DataAccessException; -import org.jooq.exception.TooManyRowsException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.dao.DataAccessResourceFailureException; -import org.springframework.grpc.server.service.GrpcService; - -/** Authenticated read of Game Design's own retained tenant identity provenance. */ -@GrpcService -public class TenantIdentityGrpcService - extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { - private final GameRepository gameRepository; - private final String workloadNamespace; - - public TenantIdentityGrpcService( - GameRepository gameRepository, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { - this.gameRepository = gameRepository; - this.workloadNamespace = workloadNamespace; - } - - @Override - public void resolveRuntimeTenantIdentity( - ResolveRuntimeTenantIdentityRequest request, - StreamObserver responseObserver) { - if (!isGameSessionPeer()) { - responseObserver.onError( - Status.PERMISSION_DENIED - .withDescription("Verified Game Session workload identity is required") - .asRuntimeException()); - return; - } - - UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); - UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); - if (canonicalTenantId == null - || requestId == null - || !request.getUnknownFields().asMap().isEmpty()) { - responseObserver.onError( - Status.INVALID_ARGUMENT - .withDescription( - "Canonical nonnil IDs and the exact metadata request schema are required") - .asRuntimeException()); - return; - } - - Optional resolved; - try { - resolved = gameRepository.findRuntimeTenantIdentityByCanonicalTenantId(canonicalTenantId); - } catch (IllegalStateException | TooManyRowsException ex) { - responseObserver.onError( - Status.FAILED_PRECONDITION - .withDescription("Game Design tenant identity provenance is ambiguous or invalid") - .asRuntimeException()); - return; - } catch (DataAccessResourceFailureException ex) { - responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Game Design tenant identity is temporarily unavailable") - .asRuntimeException()); - return; - } catch (DataAccessException ex) { - Status.Code code = - hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; - responseObserver.onError( - Status.fromCode(code) - .withDescription( - code == Status.Code.UNAVAILABLE - ? "Game Design tenant identity is temporarily unavailable" - : "Game Design tenant identity could not be read") - .asRuntimeException()); - return; - } catch (RuntimeException ex) { - responseObserver.onError( - Status.INTERNAL - .withDescription("Game Design tenant identity could not be read") - .asRuntimeException()); - return; - } - if (resolved.isEmpty()) { - responseObserver.onError( - Status.NOT_FOUND - .withDescription("No Game Design tenant identity for exact canonical tenant ID") - .asRuntimeException()); - return; - } - - GameTenantIdentity identity = resolved.orElseThrow(); - RuntimeTenantIdentityEvidence evidence; - try { - if (!canonicalTenantId.equals(identity.canonicalTenantId())) { - throw new IllegalArgumentException("Resolved tenant UUID does not match the request"); - } - evidence = - new RuntimeTenantIdentityEvidence( - 1, - workloadNamespace, - requestId, - identity.canonicalTenantId(), - identity.sourceGameId() == null ? 0L : identity.sourceGameId(), - identity.sourceLegacyTenantId(), - identity.provenanceKind() == null ? null : identity.provenanceKind().name()); - } catch (RuntimeException ex) { - responseObserver.onError( - Status.FAILED_PRECONDITION - .withDescription("Game Design tenant identity readback is incomplete or inconsistent") - .asRuntimeException()); - return; - } - - responseObserver.onNext( - ResolveRuntimeTenantIdentityResponse.newBuilder() - .setSchemaVersion(evidence.schemaVersion()) - .setTargetNamespace(evidence.targetNamespace()) - .setRequestId(evidence.requestId().toString()) - .setCanonicalTenantId(evidence.canonicalTenantId().toString()) - .setSourceGameRowId(evidence.sourceGameRowId()) - .setSourceGameTenantKey(evidence.sourceGameTenantKey()) - .setProvenanceKind(evidence.provenanceKind()) - .build()); - responseObserver.onCompleted(); - } - - private boolean isGameSessionPeer() { - GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - return peer != null - && GrpcPeerIdentity.isValidNamespace(workloadNamespace) - && peer.uri() - .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"); - } - - private static UUID parseCanonicalNonNilUuid(String value) { - if (value == null) { - return null; - } - try { - UUID parsed = UUID.fromString(value); - return !new UUID(0L, 0L).equals(parsed) && parsed.toString().equals(value) ? parsed : null; - } catch (IllegalArgumentException ex) { - return null; - } - } - - private static boolean hasConnectionFailureSqlState(Throwable failure) { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException exception) { - String sqlState = exception.getSQLState(); - if (sqlState != null && sqlState.startsWith("08")) { - return true; - } - } - } - return false; - } -} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index d1bce34ed8..4de4297c8d 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -59,9 +59,6 @@ server: firemud: auth: - grpc: - public-methods: - - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity http: enabled: true role-requirement: PRIVILEGED @@ -75,7 +72,6 @@ firemud: - method: GET path-pattern: /.well-known/** grpc: - workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} diff --git a/services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql b/services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql deleted file mode 100644 index a6758bc557..0000000000 --- a/services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql +++ /dev/null @@ -1,68 +0,0 @@ -ALTER TABLE game - ADD COLUMN canonical_tenant_id UUID, - ADD COLUMN tenant_identity_provenance_kind VARCHAR(32), - ADD COLUMN tenant_identity_source_game_id BIGINT, - ADD COLUMN tenant_identity_source_legacy_tenant_id VARCHAR(36); - --- A UUID is issued only for an exact, nonblank, bounded owner key. Rows outside --- that shape remain unproven and cannot be resolved by the runtime read. -UPDATE game -SET canonical_tenant_id = gen_random_uuid(), - tenant_identity_provenance_kind = 'RETAINED_GAME_V29', - tenant_identity_source_game_id = id, - tenant_identity_source_legacy_tenant_id = tenant_id -WHERE char_length(tenant_id) BETWEEN 1 AND 36 - AND tenant_id ~ '[^[:space:]]'; - -ALTER TABLE game - ADD CONSTRAINT uq_game_canonical_tenant_id UNIQUE (canonical_tenant_id), - ADD CONSTRAINT chk_game_tenant_identity_provenance CHECK ( - (canonical_tenant_id IS NULL - AND tenant_identity_provenance_kind IS NULL - AND tenant_identity_source_game_id IS NULL - AND tenant_identity_source_legacy_tenant_id IS NULL) - OR - (canonical_tenant_id IS NOT NULL - AND tenant_identity_provenance_kind IS NOT NULL - AND tenant_identity_provenance_kind IN ('RETAINED_GAME_V29', 'NEW_GAME_ROW') - AND tenant_identity_source_game_id IS NOT NULL - AND tenant_identity_source_game_id = id - AND tenant_identity_source_legacy_tenant_id IS NOT NULL - AND tenant_identity_source_legacy_tenant_id = tenant_id - AND char_length(tenant_identity_source_legacy_tenant_id) BETWEEN 1 AND 36 - AND tenant_identity_source_legacy_tenant_id ~ '[^[:space:]]') - ); - --- [jooq ignore start] -CREATE FUNCTION enforce_game_tenant_identity() RETURNS trigger AS $$ -BEGIN - IF TG_OP = 'INSERT' THEN - NEW.canonical_tenant_id := gen_random_uuid(); - NEW.tenant_identity_provenance_kind := 'NEW_GAME_ROW'; - NEW.tenant_identity_source_game_id := NEW.id; - NEW.tenant_identity_source_legacy_tenant_id := NEW.tenant_id; - RETURN NEW; - END IF; - - IF NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN - RAISE EXCEPTION 'game legacy tenant_id is immutable after canonical tenant identity issuance' - USING ERRCODE = 'check_violation'; - END IF; - - IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id - OR NEW.tenant_identity_provenance_kind IS DISTINCT FROM OLD.tenant_identity_provenance_kind - OR NEW.tenant_identity_source_game_id IS DISTINCT FROM OLD.tenant_identity_source_game_id - OR NEW.tenant_identity_source_legacy_tenant_id IS DISTINCT FROM OLD.tenant_identity_source_legacy_tenant_id THEN - RAISE EXCEPTION 'game canonical tenant identity and provenance are immutable' - USING ERRCODE = 'check_violation'; - END IF; - - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - -CREATE TRIGGER trg_game_tenant_identity_immutable - BEFORE INSERT OR UPDATE ON game - FOR EACH ROW - EXECUTE FUNCTION enforce_game_tenant_identity(); --- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java deleted file mode 100644 index ef2dab2ea3..0000000000 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package integration.net.firedevops.firemud.gamedesign.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.sql.Connection; -import java.sql.Statement; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.gamedesign.entity.Game; -import net.firedevops.firemud.gamedesign.repository.GameRepository; -import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; -import org.flywaydb.core.api.configuration.FluentConfiguration; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.Table; -import org.jooq.exception.DataAccessException; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -@Testcontainers(disabledWithoutDocker = true) -class GameTenantIdentityRepositoryIntegrationTest { - private static final String SERVICE_SCHEMA = "game_design_service"; - private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; - private static final Table GAME = DSL.table(DSL.name("game")); - private static final org.jooq.Field ID = DSL.field(DSL.name("id"), Long.class); - private static final org.jooq.Field TENANT_ID = - DSL.field(DSL.name("tenant_id"), String.class); - private static final org.jooq.Field NAME = DSL.field(DSL.name("name"), String.class); - private static final org.jooq.Field CANONICAL_TENANT_ID = - DSL.field(DSL.name("canonical_tenant_id"), UUID.class); - private static final org.jooq.Field PROVENANCE_KIND = - DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); - private static final org.jooq.Field SOURCE_GAME_ID = - DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); - private static final org.jooq.Field SOURCE_LEGACY_TENANT_ID = - DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); - - @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); - - @Test - void migratesOnlyExactOwnerKeysAndReadsImmutableGameRowProvenance() throws Exception { - DriverManagerDataSource dataSource = dataSource(); - migrate(dataSource, MigrationVersion.fromVersion("28")); - - long retainedGameId; - long quarantinedGameId; - try (Connection connection = dataSource.getConnection()) { - setSearchPath(connection); - DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); - retainedGameId = insertLegacyGame(dsl, "legacy-owner-alpha", "Alpha"); - quarantinedGameId = insertLegacyGame(dsl, " ", "Unproven"); - } - - migrate(dataSource, null); - - try (Connection connection = dataSource.getConnection()) { - setSearchPath(connection); - DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); - GameRepository repository = new GameRepository(dsl); - UUID retainedTenantId = - dsl.select(CANONICAL_TENANT_ID) - .from(GAME) - .where(ID.eq(retainedGameId)) - .fetchOne(CANONICAL_TENANT_ID); - - assertThat(retainedTenantId).isNotNull(); - assertThat(repository.findRuntimeTenantIdentityByCanonicalTenantId(retainedTenantId)) - .contains( - new GameTenantIdentity( - retainedTenantId, - GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V29, - retainedGameId, - "legacy-owner-alpha")); - assertThat( - dsl.select( - CANONICAL_TENANT_ID, PROVENANCE_KIND, SOURCE_GAME_ID, SOURCE_LEGACY_TENANT_ID) - .from(GAME) - .where(ID.eq(quarantinedGameId)) - .fetchOne()) - .satisfies( - row -> { - assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); - assertThat(row.get(PROVENANCE_KIND)).isNull(); - assertThat(row.get(SOURCE_GAME_ID)).isNull(); - assertThat(row.get(SOURCE_LEGACY_TENANT_ID)).isNull(); - }); - assertThat(repository.findRuntimeTenantIdentityByCanonicalTenantId(UUID.randomUUID())) - .isEmpty(); - - Game newGame = new Game(); - newGame.setTenantId("new-owner-key"); - newGame.setName("New"); - Game saved = repository.save(newGame); - assertThat(saved.getCanonicalTenantId()).isNotNull(); - assertThat(saved.getId()).isPositive(); - assertThat( - repository.findRuntimeTenantIdentityByCanonicalTenantId(saved.getCanonicalTenantId())) - .contains( - new GameTenantIdentity( - saved.getCanonicalTenantId(), - GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, - saved.getId(), - "new-owner-key")); - - Game forgedGame = new Game(); - forgedGame.setTenantId("forged-owner-key"); - forgedGame.setName("Forged"); - forgedGame.setCanonicalTenantId(UUID.randomUUID()); - assertThatThrownBy(() -> repository.save(forgedGame)) - .isInstanceOf(IllegalArgumentException.class); - - assertThatThrownBy( - () -> - dsl.update(GAME) - .set(TENANT_ID, "renamed-owner-key") - .where(ID.eq(retainedGameId)) - .execute()) - .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.update(GAME) - .set(SOURCE_GAME_ID, SOURCE_GAME_ID.plus(1L)) - .where(ID.eq(retainedGameId)) - .execute()) - .isInstanceOf(DataAccessException.class); - assertThat(dsl.fetchCount(GAME)).isEqualTo(3); - } - } - - private DriverManagerDataSource dataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setUrl(postgres.getJdbcUrl()); - dataSource.setUsername(postgres.getUsername()); - dataSource.setPassword(postgres.getPassword()); - return dataSource; - } - - private void migrate(DriverManagerDataSource dataSource, MigrationVersion target) { - FluentConfiguration configuration = - Flyway.configure() - .dataSource(dataSource) - .schemas(SERVICE_SCHEMA) - .defaultSchema(SERVICE_SCHEMA) - .table(FLYWAY_TABLE) - .placeholders(Map.of("serviceSchema", SERVICE_SCHEMA)) - .locations("classpath:db/migration"); - if (target != null) { - configuration.target(target); - } - configuration.load().migrate(); - } - - private void setSearchPath(Connection connection) throws Exception { - try (Statement statement = connection.createStatement()) { - statement.execute("SET search_path TO game_design_service"); - } - } - - private long insertLegacyGame(DSLContext dsl, String tenantId, String name) { - return Objects.requireNonNull( - dsl.insertInto(GAME) - .set(TENANT_ID, tenantId) - .set(NAME, name) - .returning(ID) - .fetchOne(ID)) - .longValue(); - } -} 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 deleted file mode 100644 index 91007bb76b..0000000000 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ /dev/null @@ -1,244 +0,0 @@ -package unit.net.firedevops.firemud.gamedesign.security; - -import static org.assertj.core.api.Assertions.assertThat; -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.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 java.io.IOException; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.AuthTokenInterceptor; -import net.firedevops.firemud.common.security.GrpcAuthProperties; -import net.firedevops.firemud.gamedesign.repository.GameRepository; -import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; -import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; -import net.firedevops.firemud.gamedesign.v1.PingRequest; -import net.firedevops.firemud.gamedesign.v1.PingResponse; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; -import org.springframework.boot.env.YamlPropertySourceLoader; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.core.env.PropertySource; -import org.springframework.core.io.FileSystemResource; - -class TenantIdentityGrpcAuthWiringTest { - private static final String TENANT_METHOD = - "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity"; - private static final String PING_METHOD = "gamedesign.v1.GameDesignService/Ping"; - private static final String TENANT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; - private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; - private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; - private static final MethodDescriptor< - ResolveRuntimeTenantIdentityRequest, ResolveRuntimeTenantIdentityResponse> - TENANT_METHOD_DESCRIPTOR = - unaryMethod( - TENANT_METHOD, - ResolveRuntimeTenantIdentityRequest.getDefaultInstance(), - ResolveRuntimeTenantIdentityResponse.getDefaultInstance()); - private static final MethodDescriptor PING_METHOD_DESCRIPTOR = - unaryMethod(PING_METHOD, PingRequest.getDefaultInstance(), PingResponse.getDefaultInstance()); - - @Test - void noTokenWithValidSameNamespacePeerReachesTenantIdentityService() { - withConfiguredInterceptor( - interceptor -> { - GameRepository repository = mock(GameRepository.class); - UUID tenantId = UUID.fromString(TENANT_UUID); - when(repository.findRuntimeTenantIdentityByCanonicalTenantId(tenantId)) - .thenReturn( - Optional.of( - new GameTenantIdentity( - tenantId, - GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, - 42L, - "legacy-owner-key-42"))); - TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); - - DispatchResult result = dispatchTenantMethod(interceptor, service, GAME_SESSION_URI); - - assertThat(result.observer().failure).isFalse(); - assertThat(result.observer().completed).isTrue(); - assertThat(result.observer().response.getCanonicalTenantId()).isEqualTo(TENANT_UUID); - assertThat(result.handlerDispatched()).isTrue(); - verify(repository).findRuntimeTenantIdentityByCanonicalTenantId(tenantId); - }); - } - - @Test - void noTokenWithAbsentOrWrongPeerIsDeniedBeforeOwnerRead() { - withConfiguredInterceptor( - interceptor -> { - GameRepository repository = mock(GameRepository.class); - TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); - - DispatchResult absent = dispatchTenantMethod(interceptor, service, null); - DispatchResult wrong = - dispatchTenantMethod( - interceptor, service, "spiffe://firemud/ns/test/sa/account-service"); - - assertThat(absent.observer().failure).isTrue(); - assertThat(absent.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat(wrong.observer().failure).isTrue(); - assertThat(wrong.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat(absent.handlerDispatched()).isTrue(); - assertThat(wrong.handlerDispatched()).isTrue(); - org.mockito.Mockito.verifyNoInteractions(repository); - }); - } - - @Test - void unrelatedGameDesignMethodRemainsBearerProtected() { - withConfiguredInterceptor( - interceptor -> { - @SuppressWarnings({"rawtypes", "unchecked"}) - ServerCall call = mock(ServerCall.class); - when(call.getMethodDescriptor()).thenReturn(PING_METHOD_DESCRIPTOR); - @SuppressWarnings({"rawtypes", "unchecked"}) - ServerCallHandler next = mock(ServerCallHandler.class); - - interceptor.interceptCall(call, new Metadata(), next); - - ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); - verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any(Metadata.class)); - assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); - verify(next, never()) - .startCall( - org.mockito.ArgumentMatchers.eq(call), - org.mockito.ArgumentMatchers.any(Metadata.class)); - }); - } - - private static DispatchResult dispatchTenantMethod( - AuthTokenInterceptor interceptor, TenantIdentityGrpcService service, String peerUri) { - @SuppressWarnings({"rawtypes", "unchecked"}) - ServerCall call = - mock(ServerCall.class); - when(call.getMethodDescriptor()).thenReturn(TENANT_METHOD_DESCRIPTOR); - AtomicBoolean handlerDispatched = new AtomicBoolean(); - TestObserver observer = new TestObserver(); - ServerCallHandler - next = - new ServerCallHandler<>() { - @Override - public ServerCall.Listener startCall( - ServerCall< - ResolveRuntimeTenantIdentityRequest, ResolveRuntimeTenantIdentityResponse> - serverCall, - Metadata headers) { - handlerDispatched.set(true); - return new ServerCall.Listener<>() { - @Override - public void onMessage(ResolveRuntimeTenantIdentityRequest request) { - service.resolveRuntimeTenantIdentity(request, observer); - } - }; - } - }; - ResolveRuntimeTenantIdentityRequest request = - ResolveRuntimeTenantIdentityRequest.newBuilder() - .setCanonicalTenantId(TENANT_UUID) - .setRequestId(REQUEST_UUID) - .build(); - Runnable dispatch = - () -> { - ServerCall.Listener listener = - interceptor.interceptCall(call, new Metadata(), next); - listener.onMessage(request); - }; - - if (peerUri == null) { - Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); - } else { - GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); - Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); - } - return new DispatchResult(observer, handlerDispatched.get()); - } - - private static void withConfiguredInterceptor( - java.util.function.Consumer action) { - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - ConfigurationPropertiesAutoConfiguration.class, - CommonSecurityAutoConfiguration.class)) - .withInitializer( - context -> { - try { - PropertySource gameDesignApplication = - new YamlPropertySourceLoader() - .load( - "game-design-application", - new FileSystemResource("src/main/resources/application.yml")) - .get(0); - context.getEnvironment().getPropertySources().addLast(gameDesignApplication); - } catch (IOException exception) { - throw new IllegalStateException( - "Could not load Game Design application config", exception); - } - }) - .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") - .run( - context -> { - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(TENANT_METHOD); - action.accept(context.getBean(AuthTokenInterceptor.class)); - }); - } - - private static - MethodDescriptor unaryMethod( - String fullMethodName, ReqT requestDefault, RespT responseDefault) { - return MethodDescriptor.newBuilder() - .setType(MethodDescriptor.MethodType.UNARY) - .setFullMethodName(fullMethodName) - .setRequestMarshaller(ProtoUtils.marshaller(requestDefault)) - .setResponseMarshaller(ProtoUtils.marshaller(responseDefault)) - .build(); - } - - private record DispatchResult(TestObserver observer, boolean handlerDispatched) {} - - private static final class TestObserver - implements StreamObserver { - private ResolveRuntimeTenantIdentityResponse response; - private Status.Code statusCode; - private boolean failure; - private boolean completed; - - @Override - public void onNext(ResolveRuntimeTenantIdentityResponse value) { - response = value; - } - - @Override - public void onError(Throwable throwable) { - failure = true; - statusCode = Status.fromThrowable(throwable).getCode(); - } - - @Override - public void onCompleted() { - completed = true; - } - } -} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java deleted file mode 100644 index 79336c6cce..0000000000 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package net.firedevops.firemud.gamedesign.service.impl; - -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 com.google.protobuf.UnknownFieldSet; -import io.grpc.Context; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import io.grpc.stub.StreamObserver; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.gamedesign.repository.GameRepository; -import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; -import org.jooq.exception.TooManyRowsException; -import org.junit.jupiter.api.Test; -import org.springframework.dao.DataAccessResourceFailureException; - -class TenantIdentityGrpcServiceTest { - private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; - private static final UUID TENANT_ID = UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); - private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); - - private final GameRepository repository = mock(GameRepository.class); - private final TenantIdentityGrpcService service = - new TenantIdentityGrpcService(repository, "test"); - - @Test - void resolvesExactOwnerIdentityForAuthenticatedGameSessionPeer() { - when(repository.findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID)) - .thenReturn( - Optional.of( - new GameTenantIdentity( - TENANT_ID, - GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V29, - 42L, - "legacy-owner-key-42"))); - - TestObserver observer = - call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); - - assertThat(observer.failure).isNull(); - assertThat(observer.completed).isTrue(); - assertThat(observer.value.getSchemaVersion()).isEqualTo(1); - assertThat(observer.value.getTargetNamespace()).isEqualTo("test"); - assertThat(observer.value.getRequestId()).isEqualTo(REQUEST_ID.toString()); - assertThat(observer.value.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); - assertThat(observer.value.getSourceGameRowId()).isEqualTo(42L); - assertThat(observer.value.getSourceGameTenantKey()).isEqualTo("legacy-owner-key-42"); - assertThat(observer.value.getProvenanceKind()).isEqualTo("RETAINED_GAME_V29"); - verify(repository).findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID); - } - - @Test - void rejectsUnauthenticatedWrongNamespaceAndWrongServiceBeforeOwnerRead() { - assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), null))) - .isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat( - status( - call( - request(TENANT_ID.toString(), REQUEST_ID.toString()), - "spiffe://firemud/ns/other/sa/game-session-service"))) - .isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat( - status( - call( - request(TENANT_ID.toString(), REQUEST_ID.toString()), - "spiffe://firemud/ns/test/sa/account-service"))) - .isEqualTo(Status.Code.PERMISSION_DENIED); - verifyNoInteractions(repository); - } - - @Test - void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { - TenantIdentityGrpcService inactiveService = new TenantIdentityGrpcService(repository, ""); - TestObserver observer = new TestObserver(); - GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); - - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - inactiveService.resolveRuntimeTenantIdentity( - request(TENANT_ID.toString(), REQUEST_ID.toString()), observer)); - - assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); - verifyNoInteractions(repository); - } - - @Test - void rejectsNoncanonicalNilAndOpenMetadataRequestsBeforeOwnerRead() { - assertThat( - status( - call( - request(TENANT_ID.toString().toUpperCase(), REQUEST_ID.toString()), - GAME_SESSION_URI))) - .isEqualTo(Status.Code.INVALID_ARGUMENT); - assertThat( - status( - call( - request("00000000-0000-0000-0000-000000000000", REQUEST_ID.toString()), - GAME_SESSION_URI))) - .isEqualTo(Status.Code.INVALID_ARGUMENT); - assertThat( - status( - call( - request(TENANT_ID.toString(), "00000000-0000-0000-0000-000000000000"), - GAME_SESSION_URI))) - .isEqualTo(Status.Code.INVALID_ARGUMENT); - ResolveRuntimeTenantIdentityRequest openRequest = - request(TENANT_ID.toString(), REQUEST_ID.toString()).toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build(); - assertThat(status(call(openRequest, GAME_SESSION_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); - verifyNoInteractions(repository); - } - - @Test - void returnsNotFoundAndFailsClosedForInvalidOrAmbiguousOwnerEvidence() { - when(repository.findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID)) - .thenReturn(Optional.empty()) - .thenReturn( - Optional.of( - new GameTenantIdentity( - TENANT_ID, GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, 42L, " "))) - .thenThrow(new TooManyRowsException("duplicate owner identity")); - - assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) - .isEqualTo(Status.Code.NOT_FOUND); - assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status(call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - } - - @Test - void mapsUnavailableOwnerReadWithoutReturningPartialEvidence() { - when(repository.findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID)) - .thenThrow(new DataAccessResourceFailureException("unavailable")); - - TestObserver observer = - call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); - - assertThat(status(observer)).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(observer.value).isNull(); - assertThat(observer.completed).isFalse(); - } - - private static ResolveRuntimeTenantIdentityRequest request(String tenantId, String requestId) { - return ResolveRuntimeTenantIdentityRequest.newBuilder() - .setCanonicalTenantId(tenantId) - .setRequestId(requestId) - .build(); - } - - private TestObserver call(ResolveRuntimeTenantIdentityRequest request, String peerUri) { - TestObserver observer = new TestObserver(); - Runnable invocation = () -> service.resolveRuntimeTenantIdentity(request, observer); - if (peerUri == null) { - Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); - } else { - GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); - Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); - } - return observer; - } - - private static Status.Code status(TestObserver observer) { - assertThat(observer.grpcFailure).isTrue(); - assertThat(observer.failure).isNotNull(); - return observer.failure; - } - - private static final class TestObserver - implements StreamObserver { - private ResolveRuntimeTenantIdentityResponse value; - private Status.Code failure; - private boolean grpcFailure; - private boolean completed; - - @Override - public void onNext(ResolveRuntimeTenantIdentityResponse response) { - value = response; - } - - @Override - public void onError(Throwable throwable) { - grpcFailure = throwable instanceof StatusRuntimeException; - failure = Status.fromThrowable(throwable).getCode(); - } - - @Override - public void onCompleted() { - completed = true; - } - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java deleted file mode 100644 index 2eb99d9bcf..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java +++ /dev/null @@ -1,164 +0,0 @@ -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.tenant.RuntimeTenantIdentityEvidence; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; -import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; - -/** Unwired Game Session candidate for exact owner-local runtime tenant identity reads. */ -public final class GameDesignRuntimeTenantIdentityClient - extends AbstractReloadingBlockingGrpcClient< - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { - private static final long CALL_DEADLINE_SECONDS = 5L; - - private final String workloadNamespace; - - public GameDesignRuntimeTenantIdentityClient( - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProps, - GrpcChannelFactory channelFactory, - String workloadNamespace) { - super( - endpoints, - requireGameSessionMtls(tlsProps), - channelFactory, - GameDesignRuntimeTenantIdentityClient.class); - if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { - throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); - } - this.workloadNamespace = workloadNamespace; - } - - /** Initializes the client only when an explicit caller owns activation of 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 TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( - ManagedChannel channel) { - return TenantIdentityServiceGrpc.newBlockingStub(channel) - .withInterceptors( - new GrpcServerPeerIdentityClientInterceptor( - "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) - .withCompression("gzip"); - } - - /** Reads persisted Game Design identity and validates every returned owner field. */ - public RuntimeTenantIdentityEvidence resolveRuntimeTenantIdentity( - String canonicalTenantId, String requestId) { - UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); - UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); - if (currentStub == null) { - throw new IllegalStateException( - "Game Design runtime tenant identity client is not initialized"); - } - - ResolveRuntimeTenantIdentityResponse response = - currentStub - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .resolveRuntimeTenantIdentity( - ResolveRuntimeTenantIdentityRequest.newBuilder() - .setCanonicalTenantId(tenantUuid.toString()) - .setRequestId(requestUuid.toString()) - .build()); - if (response == null) { - throw new IllegalStateException("Game Design runtime tenant identity response is absent"); - } - if (!response.getUnknownFields().asMap().isEmpty()) { - throw new IllegalStateException( - "Game Design runtime tenant identity response contains unsupported fields"); - } - - RuntimeTenantIdentityEvidence evidence; - try { - evidence = - new RuntimeTenantIdentityEvidence( - response.getSchemaVersion(), - response.getTargetNamespace(), - parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"), - parseCanonicalNonNilUuid( - response.getCanonicalTenantId(), "response canonical tenant ID"), - response.getSourceGameRowId(), - response.getSourceGameTenantKey(), - response.getProvenanceKind()); - } catch (IllegalArgumentException exception) { - throw new IllegalStateException( - "Game Design runtime tenant identity response is invalid", exception); - } - - if (!workloadNamespace.equals(evidence.targetNamespace()) - || !requestUuid.equals(evidence.requestId()) - || !tenantUuid.equals(evidence.canonicalTenantId())) { - throw new IllegalStateException( - "Game Design runtime tenant identity response does not match the exact request"); - } - return evidence; - } - - private static UUID parseCanonicalNonNilUuid(String value, String label) { - if (value == null) { - throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); - } - UUID parsed; - try { - parsed = UUID.fromString(value); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); - } - if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { - throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); - } - return parsed; - } - - 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( - "Runtime tenant identity reads require Game Session workload mTLS"); - } - if (!hasText(tlsProps.getCertChain()) - || !hasText(tlsProps.getPrivateKey()) - || !hasText(tlsProps.getCaCert())) { - throw new IllegalArgumentException( - "Runtime tenant identity 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( - "Runtime tenant identity 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/client/ModerationPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java index 3ad6c4b534..71ad8a65c5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java @@ -50,11 +50,12 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( LoggingAdminServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public EvaluateModerationPolicyResponse evaluateGameplayAdmission(long tenantId, long accountId) { + public EvaluateModerationPolicyResponse evaluateGameplayAdmission( + long tenantId, String accountId) { EvaluateModerationPolicyRequest request = EvaluateModerationPolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setScope(SCOPE_GAMEPLAY_ADMISSION) .build(); return stub().evaluateModerationPolicy(request); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 775c145547..5cee6ebf15 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; @@ -338,11 +339,14 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { private Optional validateModerationPolicy( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, String tenantTag) { + if (!AccountIds.isCanonicalNonNilUuid(context.accountId())) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), context.characterId())); + } var decision = moderationPolicyClient.evaluateGameplayAdmission( - selectedRealm.tenantId(), - PositiveLongParsing.requireOptionalText(context.accountId(), "accountId") - .orElseThrow(() -> new IllegalArgumentException("accountId must be positive"))); + selectedRealm.tenantId(), context.accountId()); if (decision.hasError() && decision.getError().getCode() != null && !decision.getError().getCode().isBlank()) { @@ -912,8 +916,9 @@ private boolean isSafeMembershipAuthorityResponse( } try { Instant.parse(response.getEvaluatedAt()); - if (!PositiveLongParsing.requireOptionalText(response.getAccountId(), "accountId") - .equals(PositiveLongParsing.requireOptionalText(context.accountId(), "accountId")) + if (!AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + || !AccountIds.isCanonicalNonNilUuid(context.accountId()) + || !response.getAccountId().equals(context.accountId()) || Long.parseLong(response.getTenantId()) != selectedRealm.tenantId()) { return false; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 5624d14ef9..b838171ddd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -797,13 +797,6 @@ private void requireTenantAccess(long tenantId) { throw new AuthorizationException("Tenant access required"); } - private void requireTenantOrCurrentAccountAccess(long tenantId, long accountId) { - if (SessionContext.hasTenantAccess(tenantId) || isCurrentAccount(accountId)) { - return; - } - throw new AuthorizationException("Account access required"); - } - private void requireTenantOrCurrentAccountAccess(long tenantId, String accountId) { String currentAccountId = SessionContext.getAccountId(); if (SessionContext.hasTenantAccess(tenantId) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index d3299aa316..359780473a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -52,6 +52,8 @@ }) @Import({NoGrpcServerTestConfiguration.class, InMemorySessionContextTestConfiguration.class}) class GameSessionLoginIntegrationTest { + private static final String ACCOUNT_UUID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; + @LocalServerPort private int port; @MockitoBean private AccountClient accountClient; @@ -101,7 +103,10 @@ void setUp() { stubTransactionExecution(redisTemplate); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("stub-token").setAccountId("7").build()); + AuthenticateResponse.newBuilder() + .setAuthToken("stub-token") + .setAccountId(ACCOUNT_UUID) + .build()); when(sharedSettingsAuthorityReader.readOverrides(anyLong(), org.mockito.ArgumentMatchers.any())) .thenReturn(ScopedSettingsSnapshot.empty()); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) @@ -142,8 +147,9 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { } assertThat(payloads).anyMatch(s -> s.startsWith("OK LOGIN")); - assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)).isPresent(); - assertThat(redisValueStore).containsKey("accountrecentpresence:42:7"); + assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)) + .hasValueSatisfying(context -> assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID)); + assertThat(redisValueStore).containsKey("accountrecentpresence:42:" + ACCOUNT_UUID); verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 66f1849c1e..d8258fc8b0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -119,6 +119,7 @@ @ActiveProfiles("test") @Import({NoGrpcServerTestConfiguration.class, InMemorySessionContextTestConfiguration.class}) class GameSessionWebSocketHandlerIntegrationTest { + private static final String ACCOUNT_UUID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; // Runtime target 2 belongs to the sandbox route in this fixture. private static final long CUTOVER_GAME_INSTANCE_ID = 3L; @@ -244,7 +245,7 @@ void setUp() { return members == null ? java.util.Set.of() : new java.util.LinkedHashSet<>(members); }); when(moderationPolicyClient.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -261,11 +262,11 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("stub-token") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .build()); org.mockito.Mockito.doReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -295,7 +296,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("123") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setName("Emberline") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(12) @@ -304,7 +305,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("456") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setName("Sora") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(7) @@ -312,7 +313,10 @@ void setUp() { .build()) .when(entityManagementClient) .listCharactersByAccount( - eq("22"), eq("123"), eq("1"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + eq("22"), + eq(ACCOUNT_UUID), + eq("1"), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(commandService.enqueue( org.mockito.ArgumentMatchers.anyString(), eq("PLAY demo Emberline"), eq(false))) .thenReturn(CommandEnqueueResult.success()); @@ -656,8 +660,8 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isPresent(); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of("123"))) - .containsKey("123"); + assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(ACCOUNT_UUID))) + .containsKey(ACCOUNT_UUID); List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { @@ -822,7 +826,7 @@ void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { assertThat(payloads).anyMatch(payload -> json(payload).path("outputs").isArray()); verify(accountClient) .getTenantMembershipForRuntime( - eq("123"), eq("22"), org.mockito.ArgumentMatchers.anyString()); + eq(ACCOUNT_UUID), eq("22"), org.mockito.ArgumentMatchers.anyString()); verify(accountClient) .getTenantEntitlementsForRuntime(eq("22"), org.mockito.ArgumentMatchers.anyString()); assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)) @@ -866,7 +870,8 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_UUID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -957,7 +962,8 @@ void websocketFirstPartyStructuredLobbyBrowseIncludesRealmAndCharacterViews() th .isEqualTo("ALLOW_NEW"); assertThat(charsResult.path("outputs").get(0).path("payload").path("characters")).hasSize(2); verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_UUID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -1108,8 +1114,8 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep verify(screenBufferService, never()).clear(22L, 1L, 123L); GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of("123"))) - .containsKey("123"); + assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(ACCOUNT_UUID))) + .containsKey(ACCOUNT_UUID); java.util.List secondPayloads; try (GameplayWebSocketDriver client = @@ -1204,7 +1210,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("789") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setName("CutoverArrival") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(1) @@ -1214,7 +1220,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() .when(entityManagementClient) .listCharactersByAccount( "22", - "123", + ACCOUNT_UUID, Long.toString(CUTOVER_GAME_INSTANCE_ID), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -1247,7 +1253,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() org.mockito.Mockito.verify(entityManagementClient) .listCharactersByAccount( "22", - "123", + ACCOUNT_UUID, Long.toString(CUTOVER_GAME_INSTANCE_ID), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @@ -1306,7 +1312,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo("123"); + assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); @@ -1474,7 +1480,7 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo("123"); + assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); @@ -1567,7 +1573,7 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo("123"); + assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); @@ -1626,7 +1632,7 @@ private java.util.Map firstPartyClaims( String suffix) { return java.util.Map.of( "accountId", - "123", + ACCOUNT_UUID, "tenantId", "22", "worldSlug", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java deleted file mode 100644 index 1487459b39..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java +++ /dev/null @@ -1,316 +0,0 @@ -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.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -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.ManagedChannel; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import java.lang.reflect.Field; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; -import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; -import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.mockito.ArgumentCaptor; - -class GameDesignRuntimeTenantIdentityClientTest { - private static final String NAMESPACE = "test"; - private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); - private static final String SOURCE_KEY = "game-design-tenant-91"; - private static final long SOURCE_ROW_ID = 91L; - - @Test - void exactOwnerResponseIsTypedAndStableOnRetryForBothProvenanceKinds() throws Exception { - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); - when(stub.resolveRuntimeTenantIdentity(any())) - .thenReturn(validResponse("NEW_GAME_ROW")) - .thenReturn(validResponse("NEW_GAME_ROW")) - .thenReturn(validResponse("RETAINED_GAME_V29")) - .thenReturn(validResponse("RETAINED_GAME_V29")); - GameDesignRuntimeTenantIdentityClient client = newClient(stub); - - RuntimeTenantIdentityEvidence first = - client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); - RuntimeTenantIdentityEvidence retry = - client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); - - assertThat(first).isEqualTo(retry); - assertThat(first.schemaVersion()).isEqualTo(1); - assertThat(first.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(first.requestId()).isEqualTo(REQUEST_ID); - assertThat(first.canonicalTenantId()).isEqualTo(TENANT_ID); - assertThat(first.sourceGameRowId()).isEqualTo(SOURCE_ROW_ID); - assertThat(first.sourceGameTenantKey()).isEqualTo(SOURCE_KEY); - assertThat(first.provenanceKind()).isEqualTo("NEW_GAME_ROW"); - - ArgumentCaptor requestCaptor = - ArgumentCaptor.forClass(ResolveRuntimeTenantIdentityRequest.class); - verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); - verify(stub, times(2)).resolveRuntimeTenantIdentity(requestCaptor.capture()); - assertThat(requestCaptor.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); - assertThat(request.getRequestId()).isEqualTo(REQUEST_ID.toString()); - }); - - RuntimeTenantIdentityEvidence retained = - client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); - RuntimeTenantIdentityEvidence retainedRetry = - client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString()); - assertThat(retained).isEqualTo(retainedRetry); - assertThat(retained.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); - assertThat(retained.sourceGameRowId()).isEqualTo(SOURCE_ROW_ID); - assertThat(retained.sourceGameTenantKey()).isEqualTo(SOURCE_KEY); - } - - @Test - void rejectsMalformedRequestsBeforeAnyStubOrChannelUse() { - GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); - GameDesignRuntimeTenantIdentityClient client = newClientWithoutStub(channelFactory); - List invalidRequests = - List.of( - new String[] {null, REQUEST_ID.toString()}, - new String[] {"", REQUEST_ID.toString()}, - new String[] {"AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", REQUEST_ID.toString()}, - new String[] {"11111111-1111-4111-8111-11111111111", REQUEST_ID.toString()}, - new String[] {TENANT_ID.toString(), ""}, - new String[] {TENANT_ID.toString(), "22222222-2222-4222-8222-22222222222"}, - new String[] {TENANT_ID.toString(), "00000000-0000-0000-0000-000000000000"}); - - for (String[] invalid : invalidRequests) { - assertThatThrownBy(() -> client.resolveRuntimeTenantIdentity(invalid[0], invalid[1])) - .isInstanceOf(IllegalArgumentException.class); - } - verifyNoInteractions(channelFactory); - } - - @Test - void rejectsUninitializedClientAndAbsentOwnerResponse() throws Exception { - GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); - GameDesignRuntimeTenantIdentityClient uninitialized = newClientWithoutStub(channelFactory); - assertThatThrownBy( - () -> - uninitialized.resolveRuntimeTenantIdentity( - TENANT_ID.toString(), REQUEST_ID.toString())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("not initialized"); - verifyNoInteractions(channelFactory); - - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); - when(stub.resolveRuntimeTenantIdentity(any())).thenReturn(null); - GameDesignRuntimeTenantIdentityClient client = newClient(stub); - assertThatThrownBy( - () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("absent"); - } - - @Test - void rejectsEveryResponseFieldThatDoesNotMatchTheExactRequestOrClosedSchema() throws Exception { - ResolveRuntimeTenantIdentityResponse valid = validResponse("NEW_GAME_ROW"); - assertRejected(valid.toBuilder().setSchemaVersion(2).build()); - assertRejected(valid.toBuilder().setTargetNamespace("other").build()); - assertRejected(valid.toBuilder().setTargetNamespace("").build()); - assertRejected( - valid.toBuilder().setCanonicalTenantId("AB426BB3-A733-43F0-9C8E-2E379CBDF7EC").build()); - assertRejected(valid.toBuilder().setRequestId("33333333-3333-4333-8333-333333333333").build()); - assertRejected( - valid.toBuilder().setCanonicalTenantId("33333333-3333-4333-8333-333333333333").build()); - assertRejected(valid.toBuilder().setSourceGameRowId(0L).build()); - assertRejected(valid.toBuilder().setSourceGameTenantKey("").build()); - assertRejected(valid.toBuilder().setProvenanceKind("ACCOUNT_ASSOCIATION").build()); - assertRejected(valid.toBuilder().setRequestId("22222222-2222-4222-8222-22222222222").build()); - assertRejected( - valid.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build()); - } - - @Test - void propagatesTransportFailureWithBoundedDeadline() throws Exception { - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); - StatusRuntimeException unavailable = - new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Game Design unavailable")); - when(stub.resolveRuntimeTenantIdentity(any())).thenThrow(unavailable); - GameDesignRuntimeTenantIdentityClient client = newClient(stub); - - assertThatThrownBy( - () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) - .isSameAs(unavailable); - - verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); - } - - @Test - void rejectsPlaintextIncompleteClasspathTlsAndInvalidNamespaceBeforeChannelCreation() { - GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); - CommonGrpcClientProperties plaintext = mtlsProperties(); - plaintext.setPlaintext(true); - - assertThatThrownBy( - () -> - new GameDesignRuntimeTenantIdentityClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new GameDesignRuntimeTenantIdentityClient( - new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("TLS configuration is required"); - - for (CommonGrpcClientProperties incomplete : - List.of( - incompleteMtlsProperties(null, "client.key", "server-ca.crt"), - incompleteMtlsProperties("client.crt", null, "server-ca.crt"), - incompleteMtlsProperties("client.crt", "client.key", null))) { - assertThatThrownBy( - () -> - new GameDesignRuntimeTenantIdentityClient( - new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("certificate, key, and CA"); - } - - CommonGrpcClientProperties classpath = mtlsProperties(); - classpath.setCaCert("classpath:certs/ca.crt"); - assertThatThrownBy( - () -> - new GameDesignRuntimeTenantIdentityClient( - new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("file-backed"); - assertThatThrownBy( - () -> - new GameDesignRuntimeTenantIdentityClient( - new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("one DNS label"); - verifyNoInteractions(channelFactory); - } - - @Test - void initUsesConfiguredGameDesignTargetAndFileBackedTls(@TempDir Path directory) - throws Exception { - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - endpoints.setGameDesignService("game-design.internal:6565"); - CommonGrpcClientProperties tls = mtlsProperties(directory); - GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); - ManagedChannel channel = mock(ManagedChannel.class); - when(channelFactory.buildChannel( - eq("game-design.internal:6565"), - eq(6565), - any(CommonGrpcClientProperties.class), - eq(true))) - .thenReturn(channel); - GameDesignRuntimeTenantIdentityClient client = - new GameDesignRuntimeTenantIdentityClient(endpoints, tls, channelFactory, NAMESPACE); - try { - client.init(); - verify(channelFactory) - .buildChannel( - eq("game-design.internal:6565"), - eq(6565), - any(CommonGrpcClientProperties.class), - eq(true)); - } finally { - client.close(); - } - } - - private static void assertRejected(ResolveRuntimeTenantIdentityResponse response) - throws Exception { - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); - when(stub.resolveRuntimeTenantIdentity(any())).thenReturn(response); - GameDesignRuntimeTenantIdentityClient client = newClient(stub); - - assertThatThrownBy( - () -> client.resolveRuntimeTenantIdentity(TENANT_ID.toString(), REQUEST_ID.toString())) - .isInstanceOf(IllegalStateException.class); - } - - private static GameDesignRuntimeTenantIdentityClient newClient( - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) throws Exception { - GameDesignRuntimeTenantIdentityClient client = - newClientWithoutStub(mock(GrpcChannelFactory.class)); - Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - stubField.setAccessible(true); - stubField.set(client, stub); - return client; - } - - private static GameDesignRuntimeTenantIdentityClient newClientWithoutStub( - GrpcChannelFactory channelFactory) { - return new GameDesignRuntimeTenantIdentityClient( - new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); - } - - private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub mockStub() { - TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = - mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); - when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); - return stub; - } - - private static ResolveRuntimeTenantIdentityResponse validResponse(String provenanceKind) { - return ResolveRuntimeTenantIdentityResponse.newBuilder() - .setSchemaVersion(1) - .setTargetNamespace(NAMESPACE) - .setRequestId(REQUEST_ID.toString()) - .setCanonicalTenantId(TENANT_ID.toString()) - .setSourceGameRowId(SOURCE_ROW_ID) - .setSourceGameTenantKey(SOURCE_KEY) - .setProvenanceKind(provenanceKind) - .build(); - } - - private static CommonGrpcClientProperties mtlsProperties() { - CommonGrpcClientProperties 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; - } - - private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setCertChain(Files.createFile(directory.resolve("game-session-client.crt")).toString()); - tls.setPrivateKey(Files.createFile(directory.resolve("game-session-client.key")).toString()); - tls.setCaCert(Files.createFile(directory.resolve("game-design-ca.crt")).toString()); - return tls; - } - - private static CommonGrpcClientProperties incompleteMtlsProperties( - String certificate, String privateKey, String caCertificate) { - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setCertChain(certificate); - tls.setPrivateKey(privateKey); - tls.setCaCert(caCertificate); - return tls; - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 87959b400f..ac9a8627bb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -42,6 +43,7 @@ import org.mockito.Mockito; class PlayCommandHandlerTest { + private static final String ACCOUNT_ID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final String PLAY_COMMAND_NAME = "PLAY"; private final SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); @@ -98,7 +100,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -107,7 +109,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -161,7 +163,7 @@ void setUp() { @Test void playPromotesSessionIntoGameplay() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -176,7 +178,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -194,7 +196,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -212,7 +214,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -231,7 +233,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -249,13 +251,15 @@ void playPromotesSessionIntoGameplay() { var admissionOrder = Mockito.inOrder(accountClient, entityManagementClient); admissionOrder .verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.anyString()); admissionOrder .verify(accountClient) .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); admissionOrder .verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(entityManagementClient, never()) .findCharacterByName( Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); @@ -270,7 +274,7 @@ void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { .getFirst() .setPublicProductionRealm(true); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult ambiguousDefaultResult = @@ -301,7 +305,7 @@ void playFailsClosedWhenTenantHasNoPublicProductionRealm() { .getFirst() .setPublicProductionRealm(false); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -353,7 +357,7 @@ void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm( "Maintenance World", List.of(realm("maintenance", "Maintenance Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -366,9 +370,11 @@ void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm( assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.anyString()); Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -388,7 +394,7 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { "Other Public World", List.of(realm("production", "Live Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -406,9 +412,9 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(moderationPolicyClient.evaluateGameplayAdmission(22L, 123L)) + when(moderationPolicyClient.evaluateGameplayAdmission(22L, ACCOUNT_ID)) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(false) @@ -420,6 +426,7 @@ void playRejectsModerationPolicyDeniedAdmission() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("MODERATION_POLICY_DENIED"); + verify(moderationPolicyClient).evaluateGameplayAdmission(22L, ACCOUNT_ID); Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); Mockito.verify(gameplayPresenceLifecycleService, Mockito.never()) .registerConnected(Mockito.any()); @@ -428,7 +435,7 @@ void playRejectsModerationPolicyDeniedAdmission() { @Test void playUsesPersistedAccountRosterCharacterForSelectedTarget() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) .thenReturn(Optional.empty()); @@ -447,7 +454,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -465,7 +472,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -485,7 +492,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -505,15 +512,19 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { @Test void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -525,15 +536,19 @@ void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -548,13 +563,17 @@ void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playRejectsMalformedPersistedRosterCharacterId() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "abc", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "abc", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -580,10 +599,10 @@ void playRejectsMalformedPersistedRosterCharacterId() { @Test void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); @@ -599,13 +618,13 @@ void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { @Test void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "8008", "demo", "23", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "8008", "demo", "23", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -618,22 +637,23 @@ void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { @Test void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", "demo", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8008") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("other") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -647,22 +667,23 @@ void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { @Test void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", "demo", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8009") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("Demo") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -675,10 +696,10 @@ void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { @Test void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); PlayCommandHandlingResult result = @@ -691,22 +712,23 @@ void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { @Test void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", "demo", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8009") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("Emberline") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -719,7 +741,7 @@ void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() @Test void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -734,10 +756,10 @@ void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { @Test void playRejectsUnavailableCharacterRosterBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( ListCharactersByAccountResponse.newBuilder() .setError( @@ -760,7 +782,7 @@ void playResumeDoesNotPublishSpawnEvent() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -775,10 +797,14 @@ void playResumeDoesNotPublishSpawnEvent() { "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -798,9 +824,10 @@ void playResumeDoesNotPublishSpawnEvent() { @Test void playIgnoresStaleExistingBindingAfterNormalization() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext clearedExisting = - new SessionContext(9L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); + new SessionContext( + 9L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(clearedExisting)); @@ -815,7 +842,7 @@ void playIgnoresStaleExistingBindingAfterNormalization() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -837,12 +864,12 @@ void playIgnoresStaleExistingBindingAfterNormalization() { @Test void playIgnoresExistingBindingWithoutRoomRegion() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext existingWithoutRoom = new SessionContext( 9L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -869,7 +896,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -890,13 +917,13 @@ void playIgnoresExistingBindingWithoutRoomRegion() { @Test void firstPartyPlayRejectsMismatchedConnectScope() { SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext(1L, 22L, ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "123", + ACCOUNT_ID, 22L, "demo", "production", @@ -922,13 +949,13 @@ void firstPartyPlayRejectsMismatchedConnectScope() { @Test void firstPartyPlayRejectsMismatchedWorldSlug() { SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "123", + ACCOUNT_ID, 22L, "sandbox", "production", @@ -950,13 +977,13 @@ void firstPartyPlayRejectsMismatchedWorldSlug() { void firstPartyPlayRejectsStalePointerVersion() { gameplayCatalogProperties.getWorlds().get(0).getRealms().get(0).setPointerVersion(9L); SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "123", + ACCOUNT_ID, 22L, "demo", "production", @@ -977,13 +1004,13 @@ void firstPartyPlayRejectsStalePointerVersion() { @Test void firstPartyPlayRejectsConnectContextMissingRealmSlug() { SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "123", 22L, "demo", null, 1L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); + ACCOUNT_ID, 22L, "demo", null, 1L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -997,13 +1024,13 @@ void firstPartyPlayRejectsConnectContextMissingRealmSlug() { @Test void firstPartyPlayRejectsConnectContextMissingConnectScope() { SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "123", 22L, "demo", "production", 1L, 1L, "", "jti-1", "req-1", "gw-1"))); + ACCOUNT_ID, 22L, "demo", "production", 1L, 1L, "", "jti-1", "req-1", "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1015,13 +1042,22 @@ void firstPartyPlayRejectsConnectContextMissingConnectScope() { @Test void firstPartyPlayRejectsConnectContextMissingConnectRequest() { SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "123", 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "", "gw-1"))); + ACCOUNT_ID, + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1043,7 +1079,7 @@ void playWithoutSessionReturnsLoginRequired() { @Test void playWithoutArgumentsReturnsInvalidArgument() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1055,7 +1091,7 @@ void playWithoutArgumentsReturnsInvalidArgument() { @Test void unknownWorldReturnsSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1104,7 +1140,7 @@ void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1159,7 +1195,7 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { scriptEventPublisher, meterRegistry); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1171,13 +1207,14 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); Mockito.verify(entityManagementClient, never()) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); } @Test void sandboxWithoutCharacterReturnsSelectionRequired() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1198,7 +1235,7 @@ void sandboxWithoutCharacterReturnsSelectionRequired() { @Test void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1228,7 +1265,7 @@ void playRejectsIsolatedStateRealm() { .getRealms() .get(1) .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1251,19 +1288,31 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { .get(1) .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); SessionContext context = - new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext(1L, 22L, ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - "123", 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", + ACCOUNT_ID, + 22L, + "sandbox", + "preview", + 41L, + 1L, + "scope-1", + "jti-1", + "req-1", "gw-1"))); when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + "22", ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn( characterRoster( - "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + "7002", + "Sora", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -1290,7 +1339,7 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "first-party:123", 0L, null, @@ -1307,10 +1356,14 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { "req-persisted"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + "22", ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn( characterRoster( - "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + "7002", + "Sora", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -1334,7 +1387,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "first-party:123", 0L, null, @@ -1370,13 +1423,13 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( void playDeniedByMembershipReturnsWorldAccessDenied() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) @@ -1408,7 +1461,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { new SessionContext( 1L, 23L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1426,7 +1479,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(false) @@ -1452,13 +1505,13 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(true) @@ -1503,7 +1556,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -1528,7 +1581,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -1616,7 +1669,7 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1643,13 +1696,13 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(true) @@ -1673,13 +1726,13 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) @@ -1698,17 +1751,56 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); } + @ParameterizedTest + @ValueSource( + strings = { + "123", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "5E1340F8-99C8-49FA-A4FE-5FC9D2075621", + " 5e1340f8-99c8-49fa-a4fe-5fc9d2075621" + }) + void playWhenMembershipAuthorityAccountDoesNotExactlyMatchFailsClosed(String responseAccountId) { + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(responseAccountId) + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(moderationPolicyClient, never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); + } + @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -1735,7 +1827,7 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1765,7 +1857,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1797,7 +1889,7 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { void playWhenMembershipAuthorityUnavailableFailsClosed() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1829,7 +1921,7 @@ void playWhenMembershipAuthorityUnavailableFailsClosed() { void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1859,7 +1951,8 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { @Test void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -1874,7 +1967,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1900,7 +1993,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1919,7 +2012,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1952,7 +2045,7 @@ private SessionContext previewRealmContext() { return new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 123L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 237ec04168..7f8cbb5a25 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -75,6 +75,7 @@ @SuppressWarnings("unchecked") class SessionResumptionFlowTest { + private static final String ACCOUNT_ID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final String LOGIN_PAYLOAD = "LOGIN demo@example.com swordfish"; private static final String PLAY_PAYLOAD = "PLAY demo production"; private static final String LOOK_PAYLOAD = "LOOK"; @@ -164,12 +165,12 @@ void setUp() { .thenReturn(CommandEnqueueResult.success()); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId("77").build()); + AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId(ACCOUNT_ID).build()); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("77") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -183,7 +184,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -208,7 +209,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("77") + .setAccountId(ACCOUNT_ID) .setName("Emberline") .setLevel(12) .setPlayableStateScope( @@ -466,7 +467,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("77") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index ddbf4bc986..9a2b99d9f8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -89,6 +89,7 @@ @SuppressWarnings("unchecked") class TextCommandInterpreterTest { + private static final String ACCOUNT_ID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final String PLAY_DEMO_PRODUCTION = "PLAY demo production"; private final CommandService commandService = Mockito.mock(CommandService.class); @@ -165,13 +166,13 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("auth-token") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -185,7 +186,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -404,14 +405,14 @@ void setUp() { lookCacheService, new TextPlayerOutputRenderer(new PresentationProperties())); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse.newBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("demo") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -852,7 +853,9 @@ void gameplayAfterLoginBeforePlayReturnsPlayRequired() { @Test void gameplayWithRoomOnlyPartialShellStillReturnsPlayRequired() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(56L, 22L, "123", "demo@example.com", 0L, null, 0L, "R-7", null)); + .save( + new SessionContext( + 56L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "R-7", null)); TextCommandInterpretationResult interpretation = interpreter.interpret("56", "LOOK", false); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index e404cbf03b..5636ae89ad 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -216,7 +216,7 @@ ModerationPolicyClient moderationPolicyClient() { ModerationPolicyClient client = org.mockito.Mockito.mock(ModerationPolicyClient.class); org.mockito.Mockito.when( client.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java index 09d353edb4..1241c8dba0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java @@ -8,13 +8,13 @@ final class SessionActorReaders { private SessionActorReaders() {} static String actorPrincipalOrInternalService() { - Long accountId = currentAccountIdOrNull(); - return accountId == null ? "internal-service" : Long.toString(accountId); + String accountUuid = currentAccountUuidOrNull(); + return accountUuid == null ? "internal-service" : accountUuid; } - static Long currentAccountIdOrNull() { + static String currentAccountUuidOrNull() { try { - return SessionContext.currentAccountIdOrNull(); + return SessionContext.currentAccountUuidOrNull(); } catch (IllegalArgumentException ex) { throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "current account claim was invalid"); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 1da50d55ab..9c03c0067f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -44,6 +44,8 @@ import org.springframework.web.server.ResponseStatusException; class AdmissionPointerServiceImplTest { + private static final String ACCOUNT_UUID = "11111111-1111-1111-1111-111111111111"; + @Mock private GameSessionControlPlaneClient gameSessionControlPlaneClient; @InjectMocks private AdmissionPointerServiceImpl service; @@ -271,7 +273,7 @@ void listPointerAuditRejectsMismatchedControlPlaneTenant() { @Test void setPointerUsesSessionAccountIdAsActorPrincipal() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.setAdmissionPointer(any())) .thenReturn( SetAdmissionPointerResponse.newBuilder() @@ -304,7 +306,7 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { .setAdmissionPointer( org.mockito.ArgumentMatchers.argThat( request -> - request.getActorPrincipal().equals("42") + request.getActorPrincipal().equals(ACCOUNT_UUID) && request.getExpectedPointerVersion() == 3L && request.getExpectedCatalogRevision() == 4L && request.getPreparedVersionUpgradeId().equals("pvu-1"))); @@ -312,7 +314,7 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { @Test void setPointerMapsVersionMismatchToConflict() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.setAdmissionPointer(any())) .thenReturn( SetAdmissionPointerResponse.newBuilder() @@ -350,8 +352,8 @@ void setPointerMapsVersionMismatchToConflict() { } @Test - void setPointerRejectsMalformedCurrentAccountClaimBeforeMutation() { - SessionContext.setContext("not-a-long", List.of("platformAdmin"), Map.of()); + void setPointerRejectsNonUuidCurrentAccountClaimBeforeMutation() { + SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); ResponseStatusException ex = assertThrows( @@ -382,7 +384,7 @@ void setPointerRejectsMalformedCurrentAccountClaimBeforeMutation() { @Test void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.executePreparedVersionCutover(any())) .thenReturn( ExecutePreparedVersionCutoverResponse.newBuilder() @@ -400,7 +402,7 @@ void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { .executePreparedVersionCutover( org.mockito.ArgumentMatchers.argThat( request -> - request.getActorPrincipal().equals("42") + request.getActorPrincipal().equals(ACCOUNT_UUID) && request.getPreparedVersionUpgradeId().equals("pvu-1") && request.getExpectedPointerVersion() == 3L && request.getExpectedCatalogRevision() == 4L)); From 9640a5cd564dedec6b5b5b9ca4c9a2e3c7842747 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:17:30 +1300 Subject: [PATCH 058/105] Bind runtime realm grants to Account UUID and exact owner scope --- .../account-service/api-contracts.md | 1 + .../player-access-and-session.md | 2 +- protos/account/v1/account_service.proto | 3 + .../service/impl/AccountGrpcService.java | 52 +++++-- .../src/main/resources/application-prod.yml | 1 + .../src/main/resources/application.yml | 1 + ...timeAccountIdentityGrpcAuthWiringTest.java | 140 +++++++++++++++++- .../service/impl/AccountGrpcServiceTest.java | 134 ++++++++++++++--- .../command/text/PlayCommandHandler.java | 37 ++++- .../command/text/PlayCommandHandlerTest.java | 71 ++++++++- 10 files changed, 402 insertions(+), 40 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ceef4ecd94..9f6ff81c01 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -271,6 +271,7 @@ The canonical membership, entitlement response shape, freshness, and sequence co - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` and `GetTenantEntitlementsForRuntime(tenantId, requestId)` are internal-only workload APIs for gameplay/runtime callers; they are not caller-facing substitutes for the billing-safe membership and entitlement variants listed above. - Current drift: both methods are listed under Account's gRPC `public-methods` in development and production configuration, bypassing shared bearer validation, and the handlers do not enforce the exact Game Session/World Management workload or typed tenant-bound caller context. The target internal-only boundary remains canonical; readiness requires removal of the bypass plus missing-token, wrong-workload, and cross-tenant negative proof. +- `GetRealmAccessGrantForRuntime(accountId, tenantId, worldSlug, realmSlug, requestId)` is an internal Game Session-only read for non-public gameplay admission. Its wire `accountId` is the canonical non-nil Account UUID; Account resolves the private row through its provenance-checked UUID resolver, verifies that the grant result still names that exact row and requested tenant/world/realm, and echoes the UUID. It requires the exact same-namespace Game Session mTLS identity without an end-user bearer token. Game Session fails closed unless the response echoes the exact requested UUID and realm scope, has a positive grant version and a parseable current evaluation timestamp, and reports `granted=true`. The existing grant persistence remains limited to the four-field scope; lifecycle-bound grant reads, expiry, revocation propagation, consumer reconciliation, and active-binding ejection remain incomplete. - `GetRealmAccessGrant` and `ListRealmAccessGrantsForAccount` remain Account-owned internal reads for non-public realm discovery and admission; both require `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` and reject an unscoped or tenant-global `realmSlug` lookup. Current implementation is limited to four-field grant persistence/internal lookup and limited text `PLAY` denial; it does not prove lifecycle-bound reads, expiry, revocation propagation, consumer reconciliation, or active-binding ejection. Tenant-admin grant management and user-facing account selection remain incomplete. - `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is consumed by Account through `GameSessionClient`. [Multi-Tenancy's realm-catalog-and-admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns the realm-catalog/admission-pointer identity and `OPEN`/`CLOSED` semantics; Game Session remains the runtime owner that persists, mutates, and serves the pointer read. Account applies a bounded deadline to its gameplay-routing RPCs and translates only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` failures to retryable HTTP `503` / `AUTH_UNAVAILABLE`; other transport statuses retain their transport classification. Reachable application outcomes are not availability failures. Account's local pointer validation requires `stateScope` to be exactly `SHARED` or `ISOLATED`: a complete `CLOSED` pointer becomes `REALM_UNAVAILABLE`, reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid pointer evidence becomes `ADMISSION_POINTER_UNAVAILABLE`, and a valid scope whose exact pair changed becomes `CONNECT_SCOPE_MISMATCH`. Account never treats a timeout as missing pointer evidence, coerces an unknown scope to shared state, or silently re-resolves a stale selector. The current response remains the implemented local pointer shape; target pointer fields and `CLOSED` handling are owned by that canonical runtime routing contract and remain implementation drift where noted there. - `GetTenantEntitlementsTenant` and `GetTenantEntitlementsCrossTenantSupportSafe` remain separate caller-bound and redacted support-safe API variants. They must not be multiplexed with the internal runtime surface. 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 2ea2d50b26..7847bee82e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -35,7 +35,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. The current candidate now emits canonical Account UUID identity in the covered authentication/bootstrap/profile producers and binds matching JWT subject/account claims, with the cross-service carriers and focused proof summarized above; owner-local numeric source-row storage is retained. Tenant identifiers and unrelated numeric-only account consumers remain unconverted, while full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. Lifecycle-state retention remains tracked under AA-1.3. | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [runtime_account_identity_service.proto](../../../protos/account/v1/runtime_account_identity_service.proto); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [RuntimeAccountIdentityGrpcAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. The current candidate now emits canonical Account UUID identity in the covered authentication/bootstrap/profile producers and binds matching JWT subject/account claims, with the cross-service carriers and focused proof summarized above; owner-local numeric source-row storage is retained. Tenant identifiers and unrelated numeric-only account consumers remain unconverted, while full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. | diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 0c80fda31e..8757e09c8c 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -18,6 +18,7 @@ service AccountService { // resolves its private storage row internally and echoes the requested UUID in the response. // tenant_id remains a positive numeric tenant identifier and request_id is passed unchanged. rpc GetTenantMembershipForRuntime(GetTenantMembershipForRuntimeRequest) returns (GetTenantMembershipForRuntimeResponse); + // Exact same-namespace Game Session mTLS only; no end-user bearer token is required. rpc GetRealmAccessGrantForRuntime(GetRealmAccessGrantForRuntimeRequest) returns (GetRealmAccessGrantForRuntimeResponse); rpc GetTenantEntitlementsForRuntime(GetTenantEntitlementsForRuntimeRequest) returns (GetTenantEntitlementsForRuntimeResponse); rpc IssueDirectTextConnectScope(IssueDirectTextConnectScopeRequest) returns (IssueDirectTextConnectScopeResponse); @@ -158,6 +159,7 @@ message GetTenantMembershipForRuntimeResponse { } message GetRealmAccessGrantForRuntimeRequest { + // Canonical non-nil Account UUID. Account resolves its private storage row internally. string account_id = 1; string tenant_id = 2; string world_slug = 3; @@ -166,6 +168,7 @@ message GetRealmAccessGrantForRuntimeRequest { } message GetRealmAccessGrantForRuntimeResponse { + // Echoes the canonical UUID from the request; never a private Account row identifier. string account_id = 1; string tenant_id = 2; string world_slug = 3; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 5ce1b5d35e..006a96c4f7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -5,6 +5,7 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Instant; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -502,25 +503,48 @@ public void getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + String worldSlug = requireText(request.getWorldSlug(), "worldSlug"); + String realmSlug = requireText(request.getRealmSlug(), "realmSlug"); + long accountStorageId = accountService.resolveAccountStorageId(accountUuid); var dto = accountService.getRealmAccessGrantForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getWorldSlug(), - request.getRealmSlug(), - request.getRequestId()); + accountStorageId, + tenantId, + worldSlug, + realmSlug, + requireText(request.getRequestId(), "requestId")); + if (dto.accountId() != accountStorageId + || dto.tenantId() != tenantId + || !worldSlug.equals(dto.worldSlug()) + || !realmSlug.equals(dto.realmSlug()) + || (dto.granted() && dto.grantVersion() <= 0L) + || dto.evaluatedAt() == null + || dto.evaluatedAt().isBlank() + || Instant.parse(dto.evaluatedAt()).isAfter(Instant.now().plusSeconds(5))) { + throw new IllegalStateException("Account returned mismatched realm-grant authority"); + } GetRealmAccessGrantForRuntimeResponse response = GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) - .setTenantId(String.valueOf(dto.tenantId())) - .setWorldSlug(dto.worldSlug()) - .setRealmSlug(dto.realmSlug()) + .setAccountId(accountUuid.toString()) + .setTenantId(Long.toString(tenantId)) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) .setGranted(dto.granted()) .setGrantVersion(dto.grantVersion()) .setEvaluatedAt(dto.evaluatedAt()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setError( + appError("GetRealmAccessGrantForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetRealmAccessGrantForRuntimeResponse response = GetRealmAccessGrantForRuntimeResponse.newBuilder() @@ -536,6 +560,16 @@ public void getRealmAccessGrantForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onNext( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setError( + appError( + "GetRealmAccessGrantForRuntime", + "AUTH_UNAVAILABLE", + AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index d37794baa1..f9f57d34f1 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -74,6 +74,7 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/ListPresenceVisibilityPolicies - account.v1.AccountService/GetTenantMembershipForRuntime + - account.v1.AccountService/GetRealmAccessGrantForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index bc0123d633..fa80e31b20 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -101,6 +101,7 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/ListPresenceVisibilityPolicies - account.v1.AccountService/GetTenantMembershipForRuntime + - account.v1.AccountService/GetRealmAccessGrantForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java index fde3feb614..6f570c94b5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -16,6 +16,7 @@ import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -27,6 +28,7 @@ import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse; import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.accountservice.dto.RealmAccessGrantResult; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; @@ -54,7 +56,8 @@ class RuntimeAccountIdentityGrpcAuthWiringTest { private static final String IDENTITY_METHOD = "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; - private static final String NONPUBLIC_METHOD = + private static final String NONPUBLIC_METHOD = "account.v1.AccountService/GetProfile"; + private static final String REALM_GRANT_METHOD = "account.v1.AccountService/GetRealmAccessGrantForRuntime"; private static final String PRESENCE_METHOD = "account.v1.AccountService/ListPresenceVisibilityPolicies"; @@ -79,6 +82,13 @@ class RuntimeAccountIdentityGrpcAuthWiringTest { NONPUBLIC_METHOD, GetRealmAccessGrantForRuntimeRequest.getDefaultInstance(), GetRealmAccessGrantForRuntimeResponse.getDefaultInstance()); + private static final MethodDescriptor< + GetRealmAccessGrantForRuntimeRequest, GetRealmAccessGrantForRuntimeResponse> + REALM_GRANT_METHOD_DESCRIPTOR = + unaryMethod( + REALM_GRANT_METHOD, + GetRealmAccessGrantForRuntimeRequest.getDefaultInstance(), + GetRealmAccessGrantForRuntimeResponse.getDefaultInstance()); private static final MethodDescriptor< ListPresenceVisibilityPoliciesRequest, ListPresenceVisibilityPoliciesResponse> PRESENCE_METHOD_DESCRIPTOR = @@ -193,6 +203,51 @@ void unrelatedAccountMethodRemainsBearerProtectedUnderBothYamlLayers() { } } + @Test + void realmGrantMethodAllowsOnlyExactSameNamespaceGameSessionWorkloadUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, jwtUtil) -> { + AccountService accountService = mock(AccountService.class); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + when(accountService.getRealmAccessGrantForRuntime(42L, 1L, "demo", "preview", "req-1")) + .thenReturn( + new RealmAccessGrantResult( + 42L, 1L, "demo", "preview", true, 2L, Instant.now().toString())); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), accountService, null, "test"); + String bearer = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); + + GrantDispatchResult valid = + dispatchRealmGrantMethod(interceptor, service, GAME_SESSION_URI, null); + assertThat(valid.handlerDispatched()).isTrue(); + assertThat(valid.observer().completed).isTrue(); + assertThat(valid.observer().response.getAccountId()).isEqualTo(ACCOUNT_UUID); + verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + + AccountService deniedService = mock(AccountService.class); + AccountGrpcService deniedHandler = + new AccountGrpcService(mock(PingService.class), deniedService, null, "test"); + GrantDispatchResult bearerOnly = + dispatchRealmGrantMethod(interceptor, deniedHandler, null, bearer); + GrantDispatchResult wrongNamespace = + dispatchRealmGrantMethod( + interceptor, + deniedHandler, + "spiffe://firemud/ns/other/sa/game-session-service", + null); + for (GrantDispatchResult denied : List.of(bearerOnly, wrongNamespace)) { + assertThat(denied.observer().completed).isTrue(); + assertThat(denied.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + } + verifyNoInteractions(deniedService); + }); + } + } + @Test void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers() { for (boolean productionLayer : List.of(false, true)) { @@ -377,6 +432,65 @@ public void onMessage(ListPresenceVisibilityPoliciesRequest request) { return new PresenceDispatchResult(observer, handlerDispatched.get()); } + private static GrantDispatchResult dispatchRealmGrantMethod( + AuthTokenInterceptor interceptor, + AccountGrpcService service, + String peerUri, + String bearerToken) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(REALM_GRANT_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + GrantTestObserver observer = new GrantTestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + GetRealmAccessGrantForRuntimeRequest, + GetRealmAccessGrantForRuntimeResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(GetRealmAccessGrantForRuntimeRequest request) { + service.getRealmAccessGrantForRuntime(request, observer); + } + }; + } + }; + GetRealmAccessGrantForRuntimeRequest request = + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("preview") + .setRequestId("req-1") + .build(); + Metadata headers = new Metadata(); + if (bearerToken != null) { + headers.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + bearerToken); + } + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, next); + listener.onMessage(request); + }; + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new GrantDispatchResult(observer, handlerDispatched.get()); + } + private static void withConfiguredInterceptor( boolean productionLayer, java.util.function.BiConsumer action) { @@ -417,6 +531,7 @@ private static void withConfiguredInterceptor( assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) .contains(IDENTITY_METHOD) .contains(PRESENCE_METHOD) + .contains(REALM_GRANT_METHOD) .doesNotContain(NONPUBLIC_METHOD); action.accept( context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); @@ -439,6 +554,29 @@ private record DispatchResult(TestObserver observer, boolean handlerDispatched) private record PresenceDispatchResult(PresenceTestObserver observer, boolean handlerDispatched) {} + private record GrantDispatchResult(GrantTestObserver observer, boolean handlerDispatched) {} + + private static final class GrantTestObserver + implements StreamObserver { + private GetRealmAccessGrantForRuntimeResponse response; + private boolean completed; + + @Override + public void onNext(GetRealmAccessGrantForRuntimeResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + throw new AssertionError("Expected Account application response", throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } + private static final class TestObserver implements StreamObserver { private ResolveRuntimeAccountIdentityResponse response; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index d594df2858..e33dff4908 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -8,6 +8,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; @@ -51,6 +52,7 @@ import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.RealmAccessGrantResult; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; @@ -1379,39 +1381,123 @@ void getTenantMembershipForRuntimeFailsClosedWhenPrivateTenantDoesNotCorrelate() } @Test - void getRealmAccessGrantForRuntimeRejectsZeroAccountIdBeforeLookup() { + void getRealmAccessGrantForRuntimeRejectsNumericAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - AtomicReference ref = new AtomicReference<>(); - service.getRealmAccessGrantForRuntime( - GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("0") - .setTenantId("1") - .setWorldSlug("demo") - .setRealmSlug("production") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetRealmAccessGrantForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("42") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("req-1") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertEquals( + "accountId must be a canonical non-nil UUID", observer.response().getError().getMessage()); + Mockito.verifyNoInteractions(accountService); + } - @Override - public void onCompleted() {} - }); + @Test + void getRealmAccessGrantForRuntimeRequiresExactGameSessionPeer() { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); Mockito.verifyNoInteractions(accountService); } + @Test + void getRealmAccessGrantForRuntimeResolvesUuidAndEchoesItAfterCorrelatedRead() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + Mockito.when(accountService.getRealmAccessGrantForRuntime(42L, 7L, "demo", "preview", "req-1")) + .thenReturn( + new RealmAccessGrantResult( + 42L, 7L, "demo", "preview", true, 3L, Instant.now().toString())); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("preview") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("7", observer.response().getTenantId()); + assertEquals("demo", observer.response().getWorldSlug()); + assertEquals("preview", observer.response().getRealmSlug()); + assertEquals(3L, observer.response().getGrantVersion()); + assertTrue(observer.response().getGranted()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + } + + @Test + void getRealmAccessGrantForRuntimeFailsUnavailableOnMismatchedPrivateOwnerEvidence() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + Mockito.when(accountService.getRealmAccessGrantForRuntime(42L, 7L, "demo", "preview", "req-1")) + .thenReturn( + new RealmAccessGrantResult( + 43L, 7L, "demo", "preview", true, 3L, Instant.now().toString())); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("preview") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + } + @Test void getTenantEntitlementsForRuntimeReturnsResponse() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 5cee6ebf15..506e8e9a7a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.HashSet; @@ -740,7 +741,17 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (grantError.isPresent() || !grantResponse.getGranted()) { + if (grantError.isPresent()) { + return Optional.of( + worldAccessDeniedFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } + if (!isSafeRealmGrantResponse(grantResponse, context, selectedWorld, selectedRealm)) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } + if (!grantResponse.getGranted()) { return Optional.of( worldAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); @@ -750,6 +761,30 @@ private Optional validateMembershipResponse( return Optional.empty(); } + private boolean isSafeRealmGrantResponse( + GetRealmAccessGrantForRuntimeResponse response, + SessionContext context, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm) { + if (!AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + || !context.accountId().equals(response.getAccountId()) + || !Long.toString(selectedRealm.tenantId()).equals(response.getTenantId()) + || !selectedWorld.slug().equals(response.getWorldSlug()) + || !selectedRealm.slug().equals(response.getRealmSlug()) + || (response.getGranted() && response.getGrantVersion() <= 0L) + || !StringUtils.hasText(response.getEvaluatedAt())) { + return false; + } + try { + Instant evaluatedAt = Instant.parse(response.getEvaluatedAt()); + Instant now = Instant.now(); + return !evaluatedAt.isAfter(now.plusSeconds(5)) + && !evaluatedAt.isBefore(now.minus(Duration.ofMinutes(5))); + } catch (DateTimeParseException ex) { + return false; + } + } + private PlayCommandHandlingResult worldAccessDeniedFailure( SessionContext context, String tenantTag, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index ac9a8627bb..98c34d0d46 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -6,6 +6,7 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -131,7 +132,14 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenAnswer( + invocation -> + realmGrantResponse( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + true)); when(sessionRoutingNormalizationService.normalizeProjectedContext( Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -1549,7 +1557,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenReturn(realmGrantResponse(true)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1573,7 +1581,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(realmGrantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1599,7 +1607,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(realmGrantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1664,6 +1672,44 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playMismatchedRealmGrantCorrelationFailsUnavailable() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(realmGrantResponse(true).toBuilder().setRealmSlug("other-realm").build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playGrantedRealmWithoutGrantGenerationFailsUnavailable() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(realmGrantResponse(true).toBuilder().setGrantVersion(0L).build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + @ParameterizedTest @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED"}) void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { @@ -2067,6 +2113,23 @@ private TextCommand previewRealmPlayCommand() { "PLAY sandbox preview Emberline"); } + private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse(boolean granted) { + return realmGrantResponse(ACCOUNT_ID, "22", "sandbox", "preview", granted); + } + + private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse( + String accountId, String tenantId, String worldSlug, String realmSlug, boolean granted) { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(accountId) + .setTenantId(tenantId) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .setGranted(granted) + .setGrantVersion(granted ? 3L : 0L) + .setEvaluatedAt(Instant.now().toString()) + .build(); + } + private static GameplayCatalogProperties.World world( String slug, String displayName, List realms) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); From 7e890d5ed57664b0cfc1dec96767055d14c14dc5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:32:23 +1300 Subject: [PATCH 059/105] Bound UUID authority errors and strengthen carrier regression proof --- .../account-service/api-contracts.md | 2 +- .../player-access-and-session.md | 2 + .../entity/AccountIdentityProvenance.java | 6 +++ .../service/impl/AccountGrpcService.java | 14 +++++ .../service/impl/AccountServiceImpl.java | 4 +- .../RuntimeAccountIdentityGrpcService.java | 7 +-- .../service/impl/AccountGrpcServiceTest.java | 53 +++++++++++++++++++ .../ScriptEventIngressServiceImplTest.java | 2 + .../filter/GameplayHandshakeFilterTest.java | 21 ++++---- 9 files changed, 92 insertions(+), 19 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 9f6ff81c01..87018849ab 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -270,7 +270,7 @@ The canonical token refresh, replacement, generation, revocation, fencing, logou The canonical membership, entitlement response shape, freshness, and sequence contract is [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). This API document retains only the local surfaces and transport consequences: - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` and `GetTenantEntitlementsForRuntime(tenantId, requestId)` are internal-only workload APIs for gameplay/runtime callers; they are not caller-facing substitutes for the billing-safe membership and entitlement variants listed above. -- Current drift: both methods are listed under Account's gRPC `public-methods` in development and production configuration, bypassing shared bearer validation, and the handlers do not enforce the exact Game Session/World Management workload or typed tenant-bound caller context. The target internal-only boundary remains canonical; readiness requires removal of the bypass plus missing-token, wrong-workload, and cross-tenant negative proof. +- Current enforcement differs by method: both remain in Account's gRPC `public-methods` list, but `GetTenantMembershipForRuntime` enforces the exact Game Session workload and privately resolves the canonical Account UUID. `GetTenantEntitlementsForRuntime` still accepts a caller-selected tenant without a workload-peer check or caller-context tenant binding. Its internal-workload boundary and wrong-workload/cross-tenant denial proof remain incomplete. - `GetRealmAccessGrantForRuntime(accountId, tenantId, worldSlug, realmSlug, requestId)` is an internal Game Session-only read for non-public gameplay admission. Its wire `accountId` is the canonical non-nil Account UUID; Account resolves the private row through its provenance-checked UUID resolver, verifies that the grant result still names that exact row and requested tenant/world/realm, and echoes the UUID. It requires the exact same-namespace Game Session mTLS identity without an end-user bearer token. Game Session fails closed unless the response echoes the exact requested UUID and realm scope, has a positive grant version and a parseable current evaluation timestamp, and reports `granted=true`. The existing grant persistence remains limited to the four-field scope; lifecycle-bound grant reads, expiry, revocation propagation, consumer reconciliation, and active-binding ejection remain incomplete. - `GetRealmAccessGrant` and `ListRealmAccessGrantsForAccount` remain Account-owned internal reads for non-public realm discovery and admission; both require `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` and reject an unscoped or tenant-global `realmSlug` lookup. Current implementation is limited to four-field grant persistence/internal lookup and limited text `PLAY` denial; it does not prove lifecycle-bound reads, expiry, revocation propagation, consumer reconciliation, or active-binding ejection. Tenant-admin grant management and user-facing account selection remain incomplete. - `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is consumed by Account through `GameSessionClient`. [Multi-Tenancy's realm-catalog-and-admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns the realm-catalog/admission-pointer identity and `OPEN`/`CLOSED` semantics; Game Session remains the runtime owner that persists, mutates, and serves the pointer read. Account applies a bounded deadline to its gameplay-routing RPCs and translates only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` failures to retryable HTTP `503` / `AUTH_UNAVAILABLE`; other transport statuses retain their transport classification. Reachable application outcomes are not availability failures. Account's local pointer validation requires `stateScope` to be exactly `SHARED` or `ISOLATED`: a complete `CLOSED` pointer becomes `REALM_UNAVAILABLE`, reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid pointer evidence becomes `ADMISSION_POINTER_UNAVAILABLE`, and a valid scope whose exact pair changed becomes `CONNECT_SCOPE_MISMATCH`. Account never treats a timeout as missing pointer evidence, coerces an unknown scope to shared state, or silently re-resolves a stale selector. The current response remains the implemented local pointer shape; target pointer fields and `CLOSED` handling are owned by that canonical runtime routing contract and remain implementation drift where noted there. 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 7847bee82e..b4b790d216 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -46,6 +46,8 @@ These links add decision provenance only; they do not upgrade player-access or s The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +At the Account gRPC boundary, `GetTenantMembershipForRuntime` enforces its exact Game Session peer and resolves the canonical Account UUID before reading the requested membership. The separate `GetTenantEntitlementsForRuntime` handler still lacks a workload-peer check and tenant binding; wrong-workload/cross-tenant denial proof is absent, so its internal runtime authorization boundary remains incomplete. + Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. ## Canonical Design Sources diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java index f3f17c8704..ebbd5b9b47 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java @@ -5,6 +5,12 @@ public enum AccountIdentityProvenance { ACCOUNT_REPOSITORY_INSERT, ACCOUNT_DATABASE_INSERT; + public static boolean isAccepted(AccountIdentityProvenance provenance) { + return provenance == ACCOUNT_V29_MIGRATION + || provenance == ACCOUNT_REPOSITORY_INSERT + || provenance == ACCOUNT_DATABASE_INSERT; + } + public static AccountIdentityProvenance fromStorageValue(String value) { if (value == null) { throw new IllegalStateException("Account UUID provenance must not be null"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 006a96c4f7..d21af640df 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -381,6 +381,13 @@ public void authenticate( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (IllegalStateException ex) { + AuthenticateResponse response = + AuthenticateResponse.newBuilder() + .setError(appError("Authenticate", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } } @@ -426,6 +433,13 @@ public void verifyEmailLoginOtp( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")) .build()); + } catch (IllegalStateException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError( + appError( + "VerifyEmailLoginOtp", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); } responseObserver.onCompleted(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index c5d538919f..2e819853fd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -2039,9 +2039,7 @@ public Long resolveAccountStorageId(UUID accountUuid) { || NIL_ACCOUNT_UUID.equals(account.getAccountUuid()) || account.getAccountUuidSourceNumericId() == null || !account.getId().equals(account.getAccountUuidSourceNumericId()) - || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT - && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION - && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT) + || !AccountIdentityProvenance.isAccepted(provenance) || !accountUuid.equals(account.getAccountUuid())) { throw new IllegalStateException( "Account UUID readback did not match its exact persisted source row"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java index 5e9dc7270a..a1de67ba58 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java @@ -156,12 +156,7 @@ private static boolean hasExactPersistedIdentity(Account account, UUID canonical || !account.getId().equals(account.getAccountUuidSourceNumericId())) { return false; } - for (AccountIdentityProvenance provenance : AccountIdentityProvenance.values()) { - if (provenance == account.getAccountUuidProvenance()) { - return true; - } - } - return false; + return AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()); } private static UUID parseCanonicalNonNilUuid(String value) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index e33dff4908..010957180a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -8,6 +8,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; import java.util.List; import java.util.Map; @@ -517,6 +518,32 @@ public void onCompleted() {} Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "bad"); } + @Test + void authenticateConvertsIllegalStateToBoundedAuthorityUnavailableError() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) + .thenThrow(new IllegalStateException("private provenance detail")); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + RecordingObserver observer = new RecordingObserver<>(); + + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + assertEquals( + 1.0, registry.get("grpc.app_error").tag("code", "AUTH_UNAVAILABLE").counter().count()); + } + @Test void requestEmailLoginOtpDispatchesNeutralChallengeRequest() { PingService pingService = Mockito.mock(PingService.class); @@ -645,6 +672,32 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { assertFalse(observer.receivedTransportError()); } + @Test + void verifyEmailLoginOtpConvertsIllegalStateToBoundedAuthorityUnavailableError() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) + .thenThrow(new IllegalStateException("private provenance detail")); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + RecordingObserver observer = new RecordingObserver<>(); + + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + assertEquals( + 1.0, registry.get("grpc.app_error").tag("code", "AUTH_UNAVAILABLE").counter().count()); + } + @Test void createAccountValidationErrorReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java index fe90ccfe14..6c4ef54238 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java @@ -3251,6 +3251,8 @@ void dryRunBudgetDenialStopsBeforeHandlerResolution() { assertThat(admission.outcome()) .isEqualTo(TriggerAdmissionOutcome.TRIGGER_ADMISSION_OUTCOME_QUOTA_DENIED.name()); assertThat(admission.reason()).isEqualTo("dry_run_budget_exceeded"); + verify(dryRunQuotaService) + .tryAcquire("1", "script-1", "account:11111111-1111-1111-1111-111111111111"); verify(bindingRepository, never()) .findByTenantIdAndScriptPatchVersionAndEventTypeAndEventSchemaVersionAndEnabledTrueOrderByPriorityAscScriptIdAsc( Mockito.anyLong(), diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java index 9cb6a7ab50..f440429ae3 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java @@ -318,18 +318,21 @@ void rejectsNumericAccountCarrierWithoutForwardingConnectContext() { MockServerHttpRequest.get("/ws/game/test") .cookie(new HttpCookie(GameplayHandshakeFilter.CONNECT_TOKEN_COOKIE, token)) .build()); - - filter.filter(exchange, e -> Mono.empty()).block(); - + AtomicBoolean delegated = new AtomicBoolean(); + + filter + .filter( + exchange, + e -> { + delegated.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(delegated).isFalse(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().getFirst("X-Firemud-Handshake-Error-Class")) .isEqualTo(GameplayHandshakeFilter.CONNECT_TOKEN_REJECTED); - assertThat( - exchange - .getRequest() - .getHeaders() - .getFirst(GameplayHandshakeFilter.CONNECT_CONTEXT_HEADER)) - .isNull(); } @Test From bed3f2dababe8eef5d3d101a5e66d30eb3155944 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:41:52 +1300 Subject: [PATCH 060/105] docs: align runtime identity and membership proof status --- .../implementation-tracking/player-access-and-session.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index b4b790d216..cbf15dfa60 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,7 +16,7 @@ Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, G 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). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. -Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). +Account runtime admission reads remain a security/proof blocker, but their implemented boundaries differ. `GetTenantMembershipForRuntime` requires the exact Game Session workload peer and resolves the canonical Account UUID through Account-owned identity evidence before reading membership; it verifies the private account/tenant/world/realm correlation and echoes the UUID. Focused negative proof covers malformed identifiers and unavailable or mismatched owner evidence. `GetTenantEntitlementsForRuntime` remains configured as a public gRPC method and lacks exact workload-peer and tenant binding, so it does not yet meet the target internal-workload boundary. The canonical target and remaining proof gap are recorded in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. @@ -40,7 +40,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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [GameplayPresence.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java); [AccountPresenceSnapshot.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java); [AccountRecentPresenceState.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. V11 adds nullable Account UUID evidence to the Game Session command ledger and repository round-trip mapping while preserving retained numeric Account IDs; focused repository and migration PostgreSQL cases are present but skipped locally because Docker is disabled. Internal Account-carrier typing is prepared across session, first-party, and presence records, while current numeric Account/JWT producers and numeric-only collaborators remain unchanged. Canonical Account UUID issuance and Entity roster/`PLAY` activation are absent; historical command `account_uuid` remains null without backfill, preserving numeric command evidence. Focused tests cover fail-closed first-party retained-context lookup, unreadable presence lookup without pruning, and bounded pre-mutation rejection of unreadable/wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests cover an unreadable session alias aborting before writes/deletes. Mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [GameplayPresence.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java); [AccountPresenceSnapshot.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java); [AccountRecentPresenceState.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. V11 adds nullable Account UUID evidence to the Game Session command ledger and repository round-trip mapping while preserving retained numeric Account IDs; focused repository and migration PostgreSQL cases are present but skipped locally because Docker is disabled. Covered canonical Account UUID issuance and matching subject/account claims now reach Account authentication, bootstrap, and profile producers, Common Security subject/account matching, Gateway gameplay-handshake validation, and the documented Game Session/Game Logic carriers. Numeric-only Account consumers and Game Session's numeric control-plane owner authorization remain unresolved; Entity roster/`PLAY` activation is not covered by this slice. Historical command `account_uuid` remains null without backfill, preserving numeric command evidence. Focused tests cover fail-closed first-party retained-context lookup, unreadable presence lookup without pruning, and bounded pre-mutation rejection of unreadable/wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests cover an unreadable session alias aborting before writes/deletes. Mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. | | `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. | | `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. | From 0031567b14d07535b92b08750edafb6bb9d16f0f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:52:06 +1300 Subject: [PATCH 061/105] Freeze and attest explicit published realm entry policy sets --- .../game-design-service/api-contracts.md | 20 +- ...ame-authoring-publishing-and-activation.md | 4 +- .../v1/tenant_identity_service.proto | 69 +++ .../PublishedRealmEntryPolicyEvidence.java | 232 ++++++++++ .../PublishedRealmEntryPolicySetEvidence.java | 211 +++++++++ .../common/publication/RealmEntryPolicy.java | 176 ++++++++ ...PublishedRealmEntryPolicyEvidenceTest.java | 184 ++++++++ .../entity/PublishedRealmEntryPolicy.java | 28 ++ .../gamedesign/repository/GameRepository.java | 19 + .../PublishedRealmEntryPolicyRepository.java | 143 ++++++ .../PublishedReleaseBundleService.java | 9 + ...shedRealmEntryPolicyNotFoundException.java | 8 + .../PublishedReleaseBundleServiceImpl.java | 348 ++++++++++++++- .../service/impl/RevisionServiceImpl.java | 13 + .../impl/TenantIdentityGrpcService.java | 259 ++++++++++- .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + .../V31__published_realm_entry_policy.sql | 50 +++ ...nantIdentityRepositoryIntegrationTest.java | 15 + .../TenantIdentityGrpcAuthWiringTest.java | 399 ++++++++++++++++- .../GameSessionTenantAssociationGrpcTest.java | 8 +- ...PublishedReleaseBundleServiceImplTest.java | 406 +++++++++++++++++- .../service/impl/RevisionServiceImplTest.java | 94 ++++ .../impl/TenantIdentityGrpcServiceTest.java | 346 ++++++++++++++- 24 files changed, 3033 insertions(+), 12 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedRealmEntryPolicy.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedRealmEntryPolicyRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedRealmEntryPolicyNotFoundException.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 31c8f7807e..3e8d320215 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -75,6 +75,8 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `SaveRevision` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. - `ResolveRuntimeTenantIdentity` – returns Game Design's persisted canonical tenant UUID and exact source-row/key provenance to Game Session; this owner-local metadata read does not resolve realm policy, realm routing, playable-state namespace/scope, or actor entry. - `ResolveLegacyGameSessionTenantAssociation` – returns the complete immutable signed Game Design approval for an exact retained Game Session tenant key and canonical tenant UUID to the same-namespace Game Session workload; it is a read-only, nonactivating owner receipt. +- `ResolvePublishedRealmEntryPolicy` – returns one immutable full-version realm-entry policy and its Game Design owner, source-revision, version, and release-bundle evidence to the same-namespace Game Session workload; it does not compose pointer, namespace, catalog, or actor-admission state. +- `ListPublishedRealmEntryPolicies` – returns the bounded, complete immutable policy set for one exact tenant/version, with deterministic selector order and an owner-bound count/digest; it does not activate runtime state. - `PublishVersion` – freezes a set of revisions and attempts durable full-version publish / release-attestation orchestration through the Game Design Temporal `publish` workflow family when Temporal is enabled; owner authorization is implemented, while end-to-end publication still lacks content-scope and live proof, as recorded above. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. @@ -113,7 +115,21 @@ The request contains exactly two fields: `canonical_tenant_id` and `request_id`, The response fields are `schema_version` (currently `1`), `target_namespace` (the configured workload namespace, not a playable-state namespace), the exact echoed `request_id`, `canonical_tenant_id`, positive internal `source_game_row_id`, exact retained `source_game_tenant_key`, and `provenance_kind` (`RETAINED_GAME_V29` or `NEW_GAME_ROW`). The tenant UUID and source provenance are issued/read from the same Game Design owner row; callers must not translate the legacy key or row ID into another identity. -Bounded transport outcomes are: `NOT_FOUND` when no owner row exists for the exact UUID; `FAILED_PRECONDITION` for missing, ambiguous, malformed, or inconsistent persisted provenance; `UNAVAILABLE` for unavailable storage/connection failures; and `INTERNAL` for other read failures. No partial evidence is returned on error. This method does not return a version-bound realm-entry policy, descriptor/template identity, current Game Session pointer, or playable-state namespace/scope; those owner compositions and [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md) actor-entry behavior remain separate, incomplete work. +Bounded transport outcomes are: `NOT_FOUND` when no owner row exists for the exact UUID; `FAILED_PRECONDITION` for missing, ambiguous, malformed, or inconsistent persisted provenance; `UNAVAILABLE` for unavailable storage/connection failures; and `INTERNAL` for other read failures. No partial evidence is returned on error. This method does not return a descriptor/template identity, current Game Session pointer, or playable-state namespace/scope; those owner compositions and [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md) actor-entry behavior remain separate, incomplete work. + +### Published realm-entry policy owner read + +`SaveRevision` accepts `revisionKind=REALM_ENTRY_POLICY` only when `data` is one closed v1 JSON object containing exactly `schemaVersion`, `worldSlug`, `worldDisplayName`, `realmSlug`, `realmDisplayName`, `visible`, `publicProduction`, `stateScope`, and `entryPolicy`. The schema version is the integer `1`; every listed field is required and typed, booleans have no defaults, slugs are canonical lower-case ASCII selectors of at most 64 characters, and display names are trimmed, control-free text of at most 128 Unicode code points. The UTF-8 JSON document is bounded to 4096 bytes. Unknown fields, duplicate JSON keys, malformed values, and unsupported entry policies fail with `INVALID_ARGUMENT`. V1 accepts only `entryPolicy=PRESEEDED_ONLY`, with `stateScope=SHARED|ISOLATED`; descriptor and template fields are not valid for this policy. Other policy kinds remain unsupported until their artifacts are implemented. Realm policy revisions require a full DRAFT version and inherit their tenant/version from the existing revision transaction. The normal published-version immutability rule then prevents later edits. + +When a full-version `PublishedReleaseBundle` is created, Game Design freezes every matching policy revision in the same transaction as the bundle, in separate insert-only policy rows. The write rechecks each exact source revision's tenant, version, kind, and positive owner-local revision ID; rejects duplicate `(worldSlug, realmSlug)` selector definitions; resolves the canonical tenant UUID, source game row, retained tenant key, and provenance kind through the exact Game Design `game` row; and allocates a separate UUID for each persisted policy. It does not guess or translate tenant identifiers. Policy JSON is stored in RFC 8785 canonical form. `release_bundle_identity` is `sha256:` over RFC 8785 canonical JSON containing the canonical tenant UUID, exact version ID, publish workflow ID, and manifest hash. `policy_digest` is `sha256:` over RFC 8785 canonical evidence binding the policy UUID, canonical tenant UUID and source provenance, exact version ID/number, source revision ID, release-bundle identity and its workflow/manifest values, and the canonical policy object. Database constraints reject duplicate selectors; update and delete attempts against frozen policy rows fail. + +Publication without a `REALM_ENTRY_POLICY` revision remains valid for unrelated legacy publication behavior, but creates no realm-policy evidence. `ResolvePublishedRealmEntryPolicy` never infers policy from a release bundle or from current mutable revision data. It accepts exactly a canonical nonnil `canonical_tenant_id`, positive `version_id`, and the exact canonical `world_slug`/`realm_slug` selector pair. This selector read proves only that row; it is not a complete catalog, addressability-cardinality, or admission proof. Only the verified same-namespace Game Session workload may call it; the mTLS listener remains required, and the full method name is exempted from bearer-token validation in both base and production configuration. + +The response returns schema version and target namespace, the canonical tenant UUID and exact version ID/number, persisted policy UUID, source revision ID and Game Design tenant provenance, the stable release-bundle identity plus publish workflow ID and manifest hash, every typed policy field, canonical policy JSON, and the policy digest. Before returning it, Game Design requires the exact owning version to be `PUBLISHED` or `ACTIVE`, a corresponding full-version release bundle, exactly one matching frozen policy, exact source-revision readback, matching tenant provenance, and recomputed bundle identity and policy digest. Missing version, bundle, or policy returns `NOT_FOUND`; wrong peers return `PERMISSION_DENIED`; malformed requests return `INVALID_ARGUMENT`; unpublished versions or contradictory owner evidence return `FAILED_PRECONDITION`; unavailable storage returns `UNAVAILABLE`; and other read failures return `INTERNAL`. No partial response is returned on error. + +`ListPublishedRealmEntryPolicies` accepts exactly a canonical nonnil tenant UUID and positive owner version. It returns every frozen policy for that tenant/version in ascending `(world_slug, realm_slug)` order, an exact count, and `policy_set_digest`, which binds tenant/source provenance, version number, release-bundle identity/workflow/manifest, count, and every ordered policy UUID, source revision, selector, and policy digest. The read is complete-or-error: Game Design reads at most 129 rows for the v1 limit of 128 and rejects an oversized set rather than returning a truncated prefix. It requires the exact `PUBLISHED` or `ACTIVE` full version and corresponding full-version release bundle, then validates every policy row against its immutable source revision, owner provenance, individual digest, and bundle. Empty sets return `NOT_FOUND`; contradictory rows, duplicate selectors, over-limit sets, or a set that does not contain exactly one `visible=true && publicProduction=true` policy return `FAILED_PRECONDITION`. The runtime receiver must verify the shared typed policy and set evidence digests; the selector read above is never a substitute for this complete-set evidence. + +The complete-set read is the only policy surface that can prove the authored set's public-production cardinality. This producer evidence still does not establish current runtime catalog validity, pointer consistency, lifecycle state, descriptor/template identity, namespace/scope resolution, or actor admission; those must be joined by Game Session and the other owners before discovery or admission. Neither read creates or activates a Game Session catalog, realm UUID, pointer, playable-state namespace, Entity row, or `PLAY` path. Missing policy evidence denies the corresponding policy read. Full actor-entry behavior and runtime composition remain tracked in [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the owning implementation trackers. ### Audited retained Game Session tenant association @@ -162,6 +178,8 @@ 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`. +- `ResolvePublishedRealmEntryPolicy(ResolvePublishedRealmEntryPolicyRequest) returns (ResolvePublishedRealmEntryPolicyResponse)` – returns immutable Game Design policy and provenance evidence for the exact canonical tenant UUID, published version, and world/realm selector pair. It requires the exact `PUBLISHED` or `ACTIVE` full version and release bundle; a missing policy never falls back to legacy bundle or mutable revision data. +- `ListPublishedRealmEntryPolicies(ListPublishedRealmEntryPoliciesRequest) returns (ListPublishedRealmEntryPoliciesResponse)` – returns the complete bounded frozen policy set and owner-bound count/digest for one canonical tenant UUID and exact published version; no pagination, truncation, legacy fallback, or partial success. - `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`. - `CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse)` – persists a draft remap set for a concrete `(tenantId, sourceVersionId, targetVersionId)` pair. 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 ca4a4faa4d..8612ae89ad 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. -Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; the issuance and source provenance are immutable. Reported compilation and `generateJooq` succeeded; focused `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2. The PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. This does not prove a Game Design-published version-bound realm-entry policy, descriptor/template identity, Game Session pointer/namespace/scope composition, Entity actor admission, or actor creation/activation. The method contract and status boundary are owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#runtime-tenant-identity-owner-read); actor-entry target behavior remains [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; the issuance and source provenance are immutable. Reported focused V29 proof remains `TenantIdentityGrpcServiceTest` 6/6, `TenantIdentityGrpcAuthWiringTest` 3/3, and `RuntimeTenantIdentityEvidenceTest` 2/2; the PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. The current bounded owner-producer slice adds a closed-v1 `REALM_ENTRY_POLICY` revision path, transactionally frozen immutable policy rows at full-version release-bundle creation, a same-namespace authenticated exact-row read, and a complete-set read capped at 128 rows with owner-bound set identity/count. The latest locked validation passed the focused common evidence tests (4/4), Game Design `RevisionServiceImplTest` (15/15), `PublishedReleaseBundleServiceImplTest` (15/15), `TenantIdentityGrpcServiceTest` (12/12), and `TenantIdentityGrpcAuthWiringTest` (8/8), plus `generateJooq`, `compileIntegrationTestJava`, Java formatting checks, `linkCheck`, and Markdown lint. The migration/readback integration test was compiled but not executed; no Docker or PostgreSQL runtime validation was performed. Only complete-set evidence can establish the authored set's exactly-one-visible-publicProduction cardinality; neither it nor the selector read proves current Game Session catalog validity, pointer/namespace/scope composition, descriptor/template identity, Entity actor admission, or actor creation/activation. Target semantics remain in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), and actor-entry target behavior remains [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). 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. @@ -180,7 +180,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the current participant observations and first World mutation handoff do not yet establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. The current implementation lacks the version-scoped asset mapping/authoring path and corresponding publication/export guard; purge and publication recovery also lack complete durable operation, CAS, and exact readback proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. -- Realm-authored controllable actor entry remains incomplete: no explicit published per-version `PLAYER_CREATED` / `PRESEEDED_ONLY` / `AUTO_PROVISIONED` policy with its required descriptor/template identity and version is resolved, and Game Session's current owner pointer/namespace/scope is not yet composed with Entity's fail-closed admission/creation path. The canonical tenant UUID read above supplies owner-row provenance only and is not entry-policy or actor-creation proof. +- Game Design now accepts the closed v1 `PRESEEDED_ONLY` realm policy through its version-scoped revision path, freezes exact source-revision and canonical-tenant provenance with full-version release-bundle creation, and exposes same-namespace Game Session selector and complete-set reads of immutable policy/version/digest evidence. Missing policy remains unavailable, and unrelated legacy publication without authored policy remains valid but supplies no policy proof. The complete-set read enforces its 128-row bound and exactly-one-visible-publicProduction rule; neither owner read activates runtime state or proves current catalog/pointer validity. Realm-authored actor entry remains incomplete: `PLAYER_CREATED` and `AUTO_PROVISIONED` artifacts are unsupported, and Game Session catalog, pointer, namespace, and scope ownership is not composed with Entity admission or creation. No `PLAY` readiness is established. - Normalized-template cutover phase is target-only: no tenant-scoped `GetTemplateReferencePhase` RPC, durable phase authority, or `BACKFILLING`/`VALIDATED`/`ENFORCED` consumer contract exists in the current slice; live launch checks only the per-template `ENFORCED`/`LEGACY` field. The target API and fail-before-launch behavior remain unimplemented and unproved. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. - World design authoring currently has the first typed revision-to-World handoff, including the transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. Broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain outside the current seam. diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 71cee1b983..a19f1c7129 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -12,6 +12,12 @@ service TenantIdentityService { // Exact audited retained Game Session association; never an Account manifest or admission. rpc ResolveLegacyGameSessionTenantAssociation(ResolveLegacyGameSessionTenantAssociationRequest) returns (ResolveLegacyGameSessionTenantAssociationResponse); + // Same-namespace Game Session read of immutable, version-scoped Game Design policy evidence. + rpc ResolvePublishedRealmEntryPolicy(ResolvePublishedRealmEntryPolicyRequest) + returns (ResolvePublishedRealmEntryPolicyResponse); + // Complete bounded policy set; required for catalog cardinality and public-production proof. + rpc ListPublishedRealmEntryPolicies(ListPublishedRealmEntryPoliciesRequest) + returns (ListPublishedRealmEntryPoliciesResponse); } message ResolveRuntimeTenantIdentityRequest { @@ -59,3 +65,66 @@ message ResolveLegacyGameSessionTenantAssociationResponse { string manifest_digest = 3; string ed25519_signature = 4; } + +message ResolvePublishedRealmEntryPolicyRequest { + string canonical_tenant_id = 1; + int64 version_id = 2; + string world_slug = 3; + string realm_slug = 4; +} + +enum PublishedRealmEntryStateScope { + PUBLISHED_REALM_ENTRY_STATE_SCOPE_UNSPECIFIED = 0; + PUBLISHED_REALM_ENTRY_STATE_SCOPE_SHARED = 1; + PUBLISHED_REALM_ENTRY_STATE_SCOPE_ISOLATED = 2; +} + +enum PublishedRealmEntryPolicyKind { + PUBLISHED_REALM_ENTRY_POLICY_KIND_UNSPECIFIED = 0; + PUBLISHED_REALM_ENTRY_POLICY_KIND_PRESEEDED_ONLY = 1; +} + +message ResolvePublishedRealmEntryPolicyResponse { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + int64 version_id = 4; + int32 version_number = 5; + string policy_id = 6; + int64 source_revision_id = 7; + int64 source_game_row_id = 8; + string source_game_tenant_key = 9; + string tenant_identity_provenance_kind = 10; + string release_bundle_identity = 11; + string publish_workflow_id = 12; + string manifest_hash = 13; + string world_slug = 14; + string world_display_name = 15; + string realm_slug = 16; + string realm_display_name = 17; + bool visible = 18; + bool public_production = 19; + PublishedRealmEntryStateScope state_scope = 20; + PublishedRealmEntryPolicyKind entry_policy = 21; + string policy_json = 22; + string policy_digest = 23; +} + +message ListPublishedRealmEntryPoliciesRequest { + string canonical_tenant_id = 1; + int64 version_id = 2; +} + +message ListPublishedRealmEntryPoliciesResponse { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + int64 version_id = 4; + int32 version_number = 5; + string release_bundle_identity = 6; + string publish_workflow_id = 7; + string manifest_hash = 8; + uint32 policy_count = 9; + string policy_set_digest = 10; + repeated ResolvePublishedRealmEntryPolicyResponse policies = 11; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java new file mode 100644 index 0000000000..089563b574 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Immutable typed owner evidence shared by Game Design producers and runtime receivers. */ +public record PublishedRealmEntryPolicyEvidence( + UUID policyId, + UUID canonicalTenantId, + String tenantIdentityProvenanceKind, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + long sourceRevisionId, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + RealmEntryPolicy policy, + String policyDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int MAX_TENANT_KEY_CODE_POINTS = 36; + private static final int MAX_TENANT_KEY_UTF16_LENGTH = 72; + + public PublishedRealmEntryPolicyEvidence { + requireNonNil(policyId, "policyId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (!"NEW_GAME_ROW".equals(tenantIdentityProvenanceKind) + && !"RETAINED_GAME_V29".equals(tenantIdentityProvenanceKind)) { + throw new IllegalArgumentException("Tenant identity provenance kind is not recognized"); + } + if (sourceGameRowId <= 0 + || sourceGameTenantKey == null + || sourceGameTenantKey.isBlank() + || sourceGameTenantKey.length() > MAX_TENANT_KEY_UTF16_LENGTH + || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) + > MAX_TENANT_KEY_CODE_POINTS + || !StandardCharsets.UTF_8.newEncoder().canEncode(sourceGameTenantKey) + || versionId <= 0 + || versionNumber <= 0 + || sourceRevisionId <= 0 + || releaseBundleIdentity == null + || !releaseBundleIdentity.matches("sha256:[0-9a-f]{64}") + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || manifestHash == null + || manifestHash.isBlank()) { + throw new IllegalArgumentException("Published realm-entry policy evidence is incomplete"); + } + Objects.requireNonNull(policy, "policy"); + if (policyDigest == null || !policyDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Published realm-entry policy digest is malformed"); + } + } + + public static PublishedRealmEntryPolicyEvidence create( + UUID policyId, + UUID canonicalTenantId, + String tenantIdentityProvenanceKind, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + long sourceRevisionId, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + RealmEntryPolicy policy, + ObjectMapper objectMapper) { + requireCanonicalPolicy(policy, objectMapper); + String digest = + calculateDigest( + policyId, + canonicalTenantId, + tenantIdentityProvenanceKind, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + sourceRevisionId, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policy, + objectMapper); + return new PublishedRealmEntryPolicyEvidence( + policyId, + canonicalTenantId, + tenantIdentityProvenanceKind, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + sourceRevisionId, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policy, + digest); + } + + /** Verifies the evidence digest against every immutable owner and policy field. */ + public boolean hasValidDigest(ObjectMapper objectMapper) { + try { + requireCanonicalPolicy(policy, objectMapper); + return policyDigest.equals( + calculateDigest( + policyId, + canonicalTenantId, + tenantIdentityProvenanceKind, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + sourceRevisionId, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policy, + objectMapper)); + } catch (IllegalArgumentException exception) { + return false; + } + } + + /** Requires exact digest agreement and returns this immutable evidence. */ + public PublishedRealmEntryPolicyEvidence requireValidDigest(ObjectMapper objectMapper) { + if (!hasValidDigest(objectMapper)) { + throw new IllegalArgumentException( + "Published realm-entry policy digest does not match evidence"); + } + return this; + } + + /** Deterministic identity for a full-version release bundle, excluding local database IDs. */ + public static String releaseBundleIdentity( + UUID canonicalTenantId, + long versionId, + String publishWorkflowId, + String manifestHash, + ObjectMapper objectMapper) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (versionId <= 0 || publishWorkflowId == null || publishWorkflowId.isBlank()) { + throw new IllegalArgumentException("Published release bundle identity is incomplete"); + } + ObjectNode identity = objectMapper.createObjectNode(); + identity.put("canonicalTenantId", canonicalTenantId.toString()); + identity.put("versionId", versionId); + identity.put("publishWorkflowId", publishWorkflowId); + identity.put("manifestHash", Objects.requireNonNull(manifestHash, "manifestHash")); + return sha256(canonicalize(identity.toString())); + } + + private static String calculateDigest( + UUID policyId, + UUID canonicalTenantId, + String tenantIdentityProvenanceKind, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + long sourceRevisionId, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + RealmEntryPolicy policy, + ObjectMapper objectMapper) { + Objects.requireNonNull(objectMapper, "objectMapper"); + ObjectNode preimage = objectMapper.createObjectNode(); + preimage.put("schemaVersion", RealmEntryPolicy.SCHEMA_VERSION); + preimage.put("policyId", requireNonNil(policyId, "policyId").toString()); + preimage.put( + "canonicalTenantId", requireNonNil(canonicalTenantId, "canonicalTenantId").toString()); + preimage.put("tenantIdentityProvenanceKind", tenantIdentityProvenanceKind); + preimage.put("sourceGameRowId", sourceGameRowId); + preimage.put("sourceGameTenantKey", sourceGameTenantKey); + preimage.put("versionId", versionId); + preimage.put("versionNumber", versionNumber); + preimage.put("sourceRevisionId", sourceRevisionId); + preimage.put("releaseBundleIdentity", releaseBundleIdentity); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + try { + preimage.set("policy", objectMapper.readTree(policy.canonicalJson())); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Published realm-entry policy JSON is invalid", exception); + } + return sha256(canonicalize(preimage.toString())); + } + + private static byte[] canonicalize(String json) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } catch (IOException exception) { + throw new IllegalStateException("RFC 8785 canonicalization failed", exception); + } + } + + private static void requireCanonicalPolicy(RealmEntryPolicy policy, ObjectMapper objectMapper) { + Objects.requireNonNull(policy, "policy"); + RealmEntryPolicy parsed = RealmEntryPolicy.parseCanonical(policy.canonicalJson(), objectMapper); + if (!parsed.equals(policy)) { + throw new IllegalArgumentException( + "Published realm-entry policy fields contradict canonical JSON"); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static UUID requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java new file mode 100644 index 0000000000..4d6d62ac2c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +/** Complete, bounded and owner-bound published realm policy set for one tenant version. */ +public record PublishedRealmEntryPolicySetEvidence( + UUID canonicalTenantId, + long versionId, + int versionNumber, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + List policies, + String policySetDigest) { + public static final int MAX_POLICIES = 128; + + public PublishedRealmEntryPolicySetEvidence { + if (canonicalTenantId == null || new UUID(0L, 0L).equals(canonicalTenantId)) { + throw new IllegalArgumentException("canonicalTenantId must be a non-nil UUID"); + } + if (versionId <= 0 || versionNumber <= 0) { + throw new IllegalArgumentException("Published policy set version must be positive"); + } + if (releaseBundleIdentity == null + || !releaseBundleIdentity.matches("sha256:[0-9a-f]{64}") + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || manifestHash == null + || manifestHash.isBlank()) { + throw new IllegalArgumentException("Published policy set owner identity is incomplete"); + } + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Published realm-entry policy set is empty or oversized"); + } + String sourceProvenance = null; + Long sourceGameRowId = null; + String sourceGameTenantKey = null; + String previousWorld = null; + String previousRealm = null; + int visiblePublicProductionCount = 0; + for (PublishedRealmEntryPolicyEvidence policy : policies) { + if (policy == null + || !canonicalTenantId.equals(policy.canonicalTenantId()) + || versionId != policy.versionId() + || versionNumber != policy.versionNumber() + || !releaseBundleIdentity.equals(policy.releaseBundleIdentity()) + || !publishWorkflowId.equals(policy.publishWorkflowId()) + || !manifestHash.equals(policy.manifestHash())) { + throw new IllegalArgumentException( + "Published policy set contains contradictory owner evidence"); + } + if (sourceProvenance == null) { + sourceProvenance = policy.tenantIdentityProvenanceKind(); + sourceGameRowId = policy.sourceGameRowId(); + sourceGameTenantKey = policy.sourceGameTenantKey(); + } else if (!sourceProvenance.equals(policy.tenantIdentityProvenanceKind()) + || !sourceGameRowId.equals(policy.sourceGameRowId()) + || !sourceGameTenantKey.equals(policy.sourceGameTenantKey())) { + throw new IllegalArgumentException( + "Published policy set contains contradictory tenant provenance"); + } + String world = policy.policy().worldSlug(); + String realm = policy.policy().realmSlug(); + if (previousWorld != null + && (previousWorld.compareTo(world) > 0 + || (previousWorld.equals(world) && previousRealm.compareTo(realm) >= 0))) { + throw new IllegalArgumentException("Published policy set selector order is not canonical"); + } + previousWorld = world; + previousRealm = realm; + if (policy.policy().visible() && policy.policy().publicProduction()) { + visiblePublicProductionCount++; + } + } + if (visiblePublicProductionCount != 1) { + throw new IllegalArgumentException( + "Published policy set must contain exactly one visible publicProduction realm"); + } + if (policySetDigest == null || !policySetDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Published realm-entry policy set digest is malformed"); + } + } + + public static PublishedRealmEntryPolicySetEvidence create( + UUID canonicalTenantId, + long versionId, + int versionNumber, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + List policies, + ObjectMapper objectMapper) { + Objects.requireNonNull(policies, "policies"); + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Published realm-entry policy set is empty or oversized"); + } + List ordered = + policies.stream() + .sorted( + (left, right) -> { + int worldOrder = left.policy().worldSlug().compareTo(right.policy().worldSlug()); + return worldOrder != 0 + ? worldOrder + : left.policy().realmSlug().compareTo(right.policy().realmSlug()); + }) + .toList(); + String digest = + calculateDigest( + canonicalTenantId, + versionId, + versionNumber, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + ordered, + objectMapper); + return new PublishedRealmEntryPolicySetEvidence( + canonicalTenantId, + versionId, + versionNumber, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + ordered, + digest); + } + + /** Verifies the complete-set digest and every child policy digest. */ + public boolean hasValidDigest(ObjectMapper objectMapper) { + return policies.stream().allMatch(policy -> policy.hasValidDigest(objectMapper)) + && policySetDigest.equals( + calculateDigest( + canonicalTenantId, + versionId, + versionNumber, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policies, + objectMapper)); + } + + public PublishedRealmEntryPolicySetEvidence requireValidDigest(ObjectMapper objectMapper) { + if (!hasValidDigest(objectMapper)) { + throw new IllegalArgumentException( + "Published realm-entry policy set digest does not match evidence"); + } + return this; + } + + private static String calculateDigest( + UUID canonicalTenantId, + long versionId, + int versionNumber, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + List policies, + ObjectMapper objectMapper) { + Objects.requireNonNull(objectMapper, "objectMapper"); + ObjectNode preimage = objectMapper.createObjectNode(); + preimage.put("schemaVersion", RealmEntryPolicy.SCHEMA_VERSION); + preimage.put("canonicalTenantId", canonicalTenantId.toString()); + preimage.put( + "tenantIdentityProvenanceKind", policies.getFirst().tenantIdentityProvenanceKind()); + preimage.put("sourceGameRowId", policies.getFirst().sourceGameRowId()); + preimage.put("sourceGameTenantKey", policies.getFirst().sourceGameTenantKey()); + preimage.put("versionId", versionId); + preimage.put("versionNumber", versionNumber); + preimage.put("releaseBundleIdentity", releaseBundleIdentity); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + preimage.put("policyCount", policies.size()); + ArrayNode selectors = objectMapper.createArrayNode(); + for (PublishedRealmEntryPolicyEvidence policy : policies) { + ObjectNode selector = objectMapper.createObjectNode(); + selector.put("policyId", policy.policyId().toString()); + selector.put("sourceRevisionId", policy.sourceRevisionId()); + selector.put("worldSlug", policy.policy().worldSlug()); + selector.put("realmSlug", policy.policy().realmSlug()); + selector.put("policyDigest", policy.policyDigest()); + selectors.add(selector); + } + preimage.set("policies", selectors); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString())); + } catch (IOException exception) { + throw new IllegalStateException("RFC 8785 canonicalization failed", exception); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java new file mode 100644 index 0000000000..75ccc90dc2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Closed v1 authored realm-entry policy shared by the publication owner and runtime receivers. */ +public record RealmEntryPolicy( + int schemaVersion, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + StateScope stateScope, + EntryPolicy entryPolicy, + String canonicalJson) { + public static final String REVISION_KIND = "REALM_ENTRY_POLICY"; + public static final int SCHEMA_VERSION = 1; + public static final int MAX_JSON_BYTES = 4096; + public static final int MAX_SLUG_LENGTH = 64; + public static final int MAX_DISPLAY_NAME_CODE_POINTS = 128; + + private static final Set FIELDS = + Set.of( + "schemaVersion", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "entryPolicy"); + private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + + public enum StateScope { + SHARED, + ISOLATED + } + + public enum EntryPolicy { + PRESEEDED_ONLY + } + + /** Parses valid v1 JSON and returns the RFC 8785 canonical policy representation. */ + public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { + if (json == null || json.isBlank()) { + throw invalid("data is required"); + } + if (!StandardCharsets.UTF_8.newEncoder().canEncode(json)) { + throw invalid("data must be valid UTF-8"); + } + ByteBuffer inputBytes = StandardCharsets.UTF_8.encode(json); + if (inputBytes.remaining() > MAX_JSON_BYTES) { + throw invalid("data exceeds the v1 byte limit"); + } + + JsonNode root; + String canonicalJson; + try { + canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + root = objectMapper.readTree(canonicalJson); + } catch (IOException | RuntimeException exception) { + throw invalid("data must be valid unambiguous JSON"); + } + if (root == null || !root.isObject()) { + throw invalid("must be a JSON object"); + } + for (String field : FIELDS) { + if (!root.has(field)) { + throw invalid(field + " is required"); + } + } + if (root.size() != FIELDS.size()) { + throw invalid("must contain exactly the v1 fields"); + } + + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != SCHEMA_VERSION) { + throw invalid("schemaVersion must be the integer 1"); + } + String worldSlug = requireSlug(root, "worldSlug"); + String worldDisplayName = requireDisplayName(root, "worldDisplayName"); + String realmSlug = requireSlug(root, "realmSlug"); + String realmDisplayName = requireDisplayName(root, "realmDisplayName"); + boolean visible = requireBoolean(root, "visible"); + boolean publicProduction = requireBoolean(root, "publicProduction"); + StateScope stateScope = requireEnum(root, "stateScope", StateScope.class); + EntryPolicy entryPolicy = requireEnum(root, "entryPolicy", EntryPolicy.class); + + return new RealmEntryPolicy( + SCHEMA_VERSION, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + entryPolicy, + canonicalJson); + } + + /** Parses policy evidence that is required to already use its exact canonical JSON spelling. */ + public static RealmEntryPolicy parseCanonical(String json, ObjectMapper objectMapper) { + RealmEntryPolicy policy = parse(json, objectMapper); + if (!json.equals(policy.canonicalJson())) { + throw invalid("published policy JSON is not canonical"); + } + return policy; + } + + public static boolean isCanonicalSlug(String value) { + return value != null + && value.length() <= MAX_SLUG_LENGTH + && SLUG_PATTERN.matcher(value).matches(); + } + + private static String requireSlug(JsonNode root, String field) { + String value = requireText(root, field); + if (!isCanonicalSlug(value)) { + throw invalid(field + " must be a canonical lower-case slug"); + } + return value; + } + + private static String requireDisplayName(JsonNode root, String field) { + String value = requireText(root, field); + if (!value.equals(value.strip()) + || value.codePointCount(0, value.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || value.codePoints().anyMatch(Character::isISOControl)) { + throw invalid(field + " is outside the v1 text bounds"); + } + return value; + } + + private static String requireText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw invalid(field + " must be a nonblank string"); + } + return value.asText(); + } + + private static boolean requireBoolean(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isBoolean()) { + throw invalid(field + " must be an explicit boolean"); + } + return value.booleanValue(); + } + + private static > T requireEnum(JsonNode root, String field, Class type) { + String value = requireText(root, field); + try { + return Enum.valueOf(type, value); + } catch (IllegalArgumentException exception) { + throw invalid("unsupported " + field); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("INVALID_ARGUMENT: realmEntryPolicy " + message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java new file mode 100644 index 0000000000..70353c3715 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java @@ -0,0 +1,184 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmEntryPolicyEvidenceTest { + private static final UUID TENANT_ID = UUID.fromString("e84e0676-77f2-4bac-8be5-e89d4f8b8f01"); + private static final String WORKFLOW = "publish:tenant:publish-request:req"; + private static final String MANIFEST = "manifest-sha256"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void parserAcceptsOnlyClosedV1AndCanonicalReadbackRequiresExactJson() { + String authored = + "{ \"schemaVersion\":1, \"worldSlug\":\"earth\", " + + "\"worldDisplayName\":\"Earth\", \"realmSlug\":\"main\", " + + "\"realmDisplayName\":\"Main\", \"visible\":true, " + + "\"publicProduction\":true, \"stateScope\":\"SHARED\", " + + "\"entryPolicy\":\"PRESEEDED_ONLY\" }"; + + RealmEntryPolicy policy = RealmEntryPolicy.parse(authored, MAPPER); + + assertThat(policy.stateScope()).isEqualTo(RealmEntryPolicy.StateScope.SHARED); + assertThat(policy.entryPolicy()).isEqualTo(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + assertThat(policy.canonicalJson()).doesNotContain(": "); + assertThat(RealmEntryPolicy.isCanonicalSlug("demo--world")).isFalse(); + assertThatIllegalArgumentException() + .isThrownBy(() -> RealmEntryPolicy.parseCanonical(authored, MAPPER)); + assertThat(RealmEntryPolicy.parseCanonical(policy.canonicalJson(), MAPPER)).isEqualTo(policy); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy.canonicalJson().replace("\"visible\":true", "\"visible\":1"), MAPPER)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy + .canonicalJson() + .replace("\"worldSlug\":\"earth\"", "\"worldSlug\":\"demo--world\""), + MAPPER)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy.canonicalJson().replace("\"entryPolicy\":\"PRESEEDED_ONLY\"", ""), + MAPPER)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + RealmEntryPolicy.parse( + policy.canonicalJson().substring(0, policy.canonicalJson().length() - 1) + + ",\"descriptor\":{}}", + MAPPER)); + } + + @Test + void policyEvidenceDigestBindsTenantSourceVersionBundleAndCanonicalPolicy() { + PublishedRealmEntryPolicyEvidence evidence = policyEvidence("main", true, true); + + assertThat(evidence.hasValidDigest(MAPPER)).isTrue(); + assertThat(evidence.requireValidDigest(MAPPER)).isSameAs(evidence); + assertThat(evidence.policyDigest()).startsWith("sha256:").hasSize(71); + assertThat( + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + TENANT_ID, 7L, WORKFLOW, MANIFEST, MAPPER)) + .isEqualTo(evidence.releaseBundleIdentity()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicyEvidence( + evidence.policyId(), + evidence.canonicalTenantId(), + evidence.tenantIdentityProvenanceKind(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.versionId() + 1, + evidence.versionNumber(), + evidence.sourceRevisionId(), + evidence.releaseBundleIdentity(), + evidence.publishWorkflowId(), + evidence.manifestHash(), + evidence.policy(), + evidence.policyDigest()) + .requireValidDigest(MAPPER)); + } + + @Test + void completeSetSortsRowsAndBindsCountAndEveryPolicyDigest() { + PublishedRealmEntryPolicyEvidence main = policyEvidence("main", true, true); + PublishedRealmEntryPolicyEvidence side = policyEvidence("side", false, false); + + PublishedRealmEntryPolicySetEvidence set = + PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, + 7L, + 3, + main.releaseBundleIdentity(), + WORKFLOW, + MANIFEST, + List.of(side, main), + MAPPER); + + assertThat(set.policies()).containsExactly(main, side); + assertThat(set.hasValidDigest(MAPPER)).isTrue(); + assertThat(set.requireValidDigest(MAPPER)).isSameAs(set); + assertThat(set.policySetDigest()).startsWith("sha256:").hasSize(71); + assertThat( + PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, + 7L, + 3, + main.releaseBundleIdentity(), + WORKFLOW, + MANIFEST, + List.of(main, side), + MAPPER) + .policySetDigest()) + .isEqualTo(set.policySetDigest()); + } + + @Test + void completeSetRejectsMissingMultipleOrOversizedAddressableSets() { + PublishedRealmEntryPolicyEvidence main = policyEvidence("main", true, true); + PublishedRealmEntryPolicyEvidence side = policyEvidence("side", true, true); + String identity = main.releaseBundleIdentity(); + + assertThatIllegalArgumentException() + .isThrownBy(() -> createSet(identity, List.of(policyEvidence("hidden", false, false)))); + assertThatIllegalArgumentException().isThrownBy(() -> createSet(identity, List.of(main, side))); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + createSet( + identity, + java.util.Collections.nCopies( + PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1, main))); + } + + private static PublishedRealmEntryPolicySetEvidence createSet( + String releaseBundleIdentity, List policies) { + return PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, 7L, 3, releaseBundleIdentity, WORKFLOW, MANIFEST, policies, MAPPER); + } + + private static PublishedRealmEntryPolicyEvidence policyEvidence( + String realmSlug, boolean visible, boolean publicProduction) { + String sourceJson = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"" + + realmSlug + + "\",\"realmDisplayName\":\"" + + realmSlug + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + RealmEntryPolicy policy = RealmEntryPolicy.parse(sourceJson, MAPPER); + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + TENANT_ID, 7L, WORKFLOW, MANIFEST, MAPPER); + return PublishedRealmEntryPolicyEvidence.create( + UUID.nameUUIDFromBytes(realmSlug.getBytes(java.nio.charset.StandardCharsets.UTF_8)), + TENANT_ID, + "NEW_GAME_ROW", + 12L, + "tenant-key", + 7L, + 3, + realmSlug.equals("main") ? 42L : 43L, + releaseIdentity, + WORKFLOW, + MANIFEST, + policy, + MAPPER); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedRealmEntryPolicy.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedRealmEntryPolicy.java new file mode 100644 index 0000000000..669d8938ed --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedRealmEntryPolicy.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamedesign.entity; + +import java.util.UUID; + +/** Insert-only storage record for frozen published realm-entry policy evidence. */ +public record PublishedRealmEntryPolicy( + UUID policyId, + UUID canonicalTenantId, + String tenantIdentityProvenanceKind, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + long releaseBundleId, + long sourceRevisionId, + String releaseBundleIdentity, + String publishWorkflowId, + String manifestHash, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String entryPolicy, + String policyJson, + String policyDigest) {} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java index 638f33c93d..e381634a72 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameRepository.java @@ -138,6 +138,25 @@ public Optional findRuntimeTenantIdentityByCanonicalTenantId .fetchOptional(this::toRuntimeTenantIdentity); } + /** + * Resolves the exact existing owner tenant key to its persisted canonical UUID and provenance. + */ + public Optional findRuntimeTenantIdentityByTenantKey(String tenantKey) { + if (tenantKey == null || tenantKey.isBlank()) { + throw new IllegalArgumentException("Exact Game Design tenant key is required"); + } + return dsl.select( + ID, + TENANT_ID, + CANONICAL_TENANT_ID, + TENANT_IDENTITY_PROVENANCE_KIND, + TENANT_IDENTITY_SOURCE_GAME_ID, + TENANT_IDENTITY_SOURCE_LEGACY_TENANT_ID) + .from(GAME_TABLE) + .where(TENANT_ID.eq(tenantKey)) + .fetchOptional(this::toRuntimeTenantIdentity); + } + private Game toEntity(Record record) { if (record == null) { return null; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedRealmEntryPolicyRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedRealmEntryPolicyRepository.java new file mode 100644 index 0000000000..3923f4f42b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedRealmEntryPolicyRepository.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamedesign.entity.PublishedRealmEntryPolicy; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class PublishedRealmEntryPolicyRepository { + private static final Table TABLE_REF = DSL.table(DSL.name("published_realm_entry_policy")); + private static final Field POLICY_ID = DSL.field(DSL.name("policy_id"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_IDENTITY_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field VERSION_NUMBER = + DSL.field(DSL.name("version_number"), Integer.class); + private static final Field RELEASE_BUNDLE_ID = + DSL.field(DSL.name("release_bundle_id"), Long.class); + private static final Field SOURCE_REVISION_ID = + DSL.field(DSL.name("source_revision_id"), Long.class); + private static final Field RELEASE_BUNDLE_IDENTITY = + DSL.field(DSL.name("release_bundle_identity"), String.class); + private static final Field PUBLISH_WORKFLOW_ID = + DSL.field(DSL.name("publish_workflow_id"), String.class); + private static final Field MANIFEST_HASH = + DSL.field(DSL.name("manifest_hash"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field REALM_SLUG = DSL.field(DSL.name("realm_slug"), String.class); + private static final Field REALM_DISPLAY_NAME = + DSL.field(DSL.name("realm_display_name"), String.class); + private static final Field VISIBLE = DSL.field(DSL.name("visible"), Boolean.class); + private static final Field PUBLIC_PRODUCTION = + DSL.field(DSL.name("public_production"), Boolean.class); + private static final Field STATE_SCOPE = DSL.field(DSL.name("state_scope"), String.class); + private static final Field ENTRY_POLICY = + DSL.field(DSL.name("entry_policy"), String.class); + private static final Field POLICY_JSON = DSL.field(DSL.name("policy_json"), String.class); + private static final Field POLICY_DIGEST = + DSL.field(DSL.name("policy_digest"), String.class); + + private final DSLContext dsl; + + public PublishedRealmEntryPolicyRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void insert(PublishedRealmEntryPolicy policy) { + int inserted = + dsl.insertInto(TABLE_REF) + .set(POLICY_ID, policy.policyId()) + .set(CANONICAL_TENANT_ID, policy.canonicalTenantId()) + .set(TENANT_IDENTITY_PROVENANCE_KIND, policy.tenantIdentityProvenanceKind()) + .set(SOURCE_GAME_ROW_ID, policy.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, policy.sourceGameTenantKey()) + .set(VERSION_ID, policy.versionId()) + .set(VERSION_NUMBER, policy.versionNumber()) + .set(RELEASE_BUNDLE_ID, policy.releaseBundleId()) + .set(SOURCE_REVISION_ID, policy.sourceRevisionId()) + .set(RELEASE_BUNDLE_IDENTITY, policy.releaseBundleIdentity()) + .set(PUBLISH_WORKFLOW_ID, policy.publishWorkflowId()) + .set(MANIFEST_HASH, policy.manifestHash()) + .set(WORLD_SLUG, policy.worldSlug()) + .set(WORLD_DISPLAY_NAME, policy.worldDisplayName()) + .set(REALM_SLUG, policy.realmSlug()) + .set(REALM_DISPLAY_NAME, policy.realmDisplayName()) + .set(VISIBLE, policy.visible()) + .set(PUBLIC_PRODUCTION, policy.publicProduction()) + .set(STATE_SCOPE, policy.stateScope()) + .set(ENTRY_POLICY, policy.entryPolicy()) + .set(POLICY_JSON, policy.policyJson()) + .set(POLICY_DIGEST, policy.policyDigest()) + .execute(); + if (inserted != 1) { + throw new IllegalStateException("Published realm-entry policy insert did not affect one row"); + } + } + + public List findByScope( + UUID canonicalTenantId, long versionId, String worldSlug, String realmSlug) { + return dsl.selectFrom(TABLE_REF) + .where( + CANONICAL_TENANT_ID + .eq(canonicalTenantId) + .and(VERSION_ID.eq(versionId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(REALM_SLUG.eq(realmSlug))) + .orderBy(POLICY_ID.asc()) + .fetch(this::toEntity); + } + + /** Reads at most the proof bound plus one so callers can reject, never truncate, large sets. */ + public List findByOwner(UUID canonicalTenantId, long versionId) { + return dsl.selectFrom(TABLE_REF) + .where(CANONICAL_TENANT_ID.eq(canonicalTenantId).and(VERSION_ID.eq(versionId))) + .orderBy(WORLD_SLUG.asc(), REALM_SLUG.asc()) + .limit(PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1) + .fetch(this::toEntity); + } + + private PublishedRealmEntryPolicy toEntity(Record record) { + return new PublishedRealmEntryPolicy( + record.get(POLICY_ID), + record.get(CANONICAL_TENANT_ID), + record.get(TENANT_IDENTITY_PROVENANCE_KIND), + record.get(SOURCE_GAME_ROW_ID), + record.get(SOURCE_GAME_TENANT_KEY), + record.get(VERSION_ID), + record.get(VERSION_NUMBER), + record.get(RELEASE_BUNDLE_ID), + record.get(SOURCE_REVISION_ID), + record.get(RELEASE_BUNDLE_IDENTITY), + record.get(PUBLISH_WORKFLOW_ID), + record.get(MANIFEST_HASH), + record.get(WORLD_SLUG), + record.get(WORLD_DISPLAY_NAME), + record.get(REALM_SLUG), + record.get(REALM_DISPLAY_NAME), + Boolean.TRUE.equals(record.get(VISIBLE)), + Boolean.TRUE.equals(record.get(PUBLIC_PRODUCTION)), + record.get(STATE_SCOPE), + record.get(ENTRY_POLICY), + record.get(POLICY_JSON), + record.get(POLICY_DIGEST)); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java index 4265e6884c..52ccbae6b2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java @@ -1,6 +1,9 @@ package net.firedevops.firemud.gamedesign.service; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -16,4 +19,10 @@ PublishedReleaseBundleDto createFullVersionBundle( PublishedReleaseBundleDto getPublishedReleaseBundle(String tenantId, long versionId); Optional findPublishedReleaseBundle(String tenantId, long versionId); + + PublishedRealmEntryPolicyEvidence resolvePublishedRealmEntryPolicy( + UUID canonicalTenantId, long versionId, String worldSlug, String realmSlug); + + PublishedRealmEntryPolicySetEvidence listPublishedRealmEntryPolicies( + UUID canonicalTenantId, long versionId); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedRealmEntryPolicyNotFoundException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedRealmEntryPolicyNotFoundException.java new file mode 100644 index 0000000000..40f5934109 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedRealmEntryPolicyNotFoundException.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +public class PublishedRealmEntryPolicyNotFoundException extends RuntimeException { + public PublishedRealmEntryPolicyNotFoundException() { + super( + "Published realm-entry policy is unavailable for the exact tenant, version, and selector"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 61800e105d..22ae7e263f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -9,12 +9,23 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; +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.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.entity.PublishedRealmEntryPolicy; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Revision; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.repository.PublishedRealmEntryPolicyRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import org.springframework.stereotype.Service; @@ -29,15 +40,27 @@ public class PublishedReleaseBundleServiceImpl implements PublishedReleaseBundle private final PublishedReleaseBundleRepository repository; private final RevisionRepository revisionRepository; + private final PublishedRealmEntryPolicyRepository realmEntryPolicyRepository; + private final GameRepository gameRepository; + private final VersionRepository versionRepository; private final ObjectMapper objectMapper; public PublishedReleaseBundleServiceImpl( PublishedReleaseBundleRepository repository, RevisionRepository revisionRepository, + PublishedRealmEntryPolicyRepository realmEntryPolicyRepository, + GameRepository gameRepository, + VersionRepository versionRepository, ObjectMapper objectMapper) { this.repository = Objects.requireNonNull(repository, "repository must not be null"); this.revisionRepository = Objects.requireNonNull(revisionRepository, "revisionRepository must not be null"); + this.realmEntryPolicyRepository = + Objects.requireNonNull( + realmEntryPolicyRepository, "realmEntryPolicyRepository must not be null"); + this.gameRepository = Objects.requireNonNull(gameRepository, "gameRepository must not be null"); + this.versionRepository = + Objects.requireNonNull(versionRepository, "versionRepository must not be null"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); } @@ -52,6 +75,7 @@ public PublishedReleaseBundleDto createFullVersionBundle( Objects.requireNonNull(version, "version must not be null"); Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); Objects.requireNonNull(participantDigests, "participantDigests must not be null"); + List realmPolicies = prepareRealmEntryPolicies(version); repository .findByTenantIdAndVersionId(version.tenantId(), version.id()) .ifPresent( @@ -81,7 +105,9 @@ public PublishedReleaseBundleDto createFullVersionBundle( entity.setCommandDefinitionsJson(serializeCommandDefinitions(commandDefinitions)); entity.setScriptOnly(version.scriptOnly()); entity.setScriptPatchVersion(version.scriptPatchVersion()); - return toDto(repository.save(entity)); + PublishedReleaseBundle saved = repository.save(entity); + freezeRealmEntryPolicies(version, saved, realmPolicies); + return toDto(saved); } @Override @@ -98,6 +124,326 @@ public Optional findPublishedReleaseBundle( return repository.findByTenantIdAndVersionId(tenantId, versionId).map(this::toDto); } + @Override + @Transactional(readOnly = true) + public PublishedRealmEntryPolicyEvidence resolvePublishedRealmEntryPolicy( + UUID canonicalTenantId, long versionId, String worldSlug, String realmSlug) { + requirePolicyReadRequest(canonicalTenantId, versionId); + if (!RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !RealmEntryPolicy.isCanonicalSlug(realmSlug)) { + throw new IllegalArgumentException("Published realm-entry policy selector is invalid"); + } + PolicyOwnerContext owner = resolvePolicyOwnerContext(canonicalTenantId, versionId); + List policies = + realmEntryPolicyRepository.findByScope(canonicalTenantId, versionId, worldSlug, realmSlug); + if (policies.isEmpty()) { + throw new PublishedRealmEntryPolicyNotFoundException(); + } + if (policies.size() != 1) { + throw new IllegalStateException("Published realm-entry policy selector is ambiguous"); + } + return validateStoredPolicy(policies.getFirst(), owner); + } + + @Override + @Transactional(readOnly = true) + public PublishedRealmEntryPolicySetEvidence listPublishedRealmEntryPolicies( + UUID canonicalTenantId, long versionId) { + requirePolicyReadRequest(canonicalTenantId, versionId); + PolicyOwnerContext owner = resolvePolicyOwnerContext(canonicalTenantId, versionId); + List storedPolicies = + realmEntryPolicyRepository.findByOwner(canonicalTenantId, versionId); + if (storedPolicies.isEmpty()) { + throw new PublishedRealmEntryPolicyNotFoundException(); + } + if (storedPolicies.size() > PublishedRealmEntryPolicySetEvidence.MAX_POLICIES) { + throw new IllegalStateException( + "Published realm-entry policy set exceeds the complete-read bound"); + } + List policies = + storedPolicies.stream().map(policy -> validateStoredPolicy(policy, owner)).toList(); + PublishedRealmEntryPolicySetEvidence set = + PublishedRealmEntryPolicySetEvidence.create( + canonicalTenantId, + versionId, + owner.version().getVersionNumber(), + owner.releaseBundleIdentity(), + owner.bundle().getPublishWorkflowId(), + owner.bundle().getManifestHash(), + policies, + objectMapper); + if (!set.hasValidDigest(objectMapper)) { + throw new IllegalStateException( + "Published realm-entry policy set digest does not match its evidence"); + } + return set; + } + + private PolicyOwnerContext resolvePolicyOwnerContext(UUID canonicalTenantId, long versionId) { + GameTenantIdentity identity = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId(canonicalTenantId) + .orElseThrow(PublishedRealmEntryPolicyNotFoundException::new); + validateTenantIdentity(identity, canonicalTenantId, identity.sourceLegacyTenantId()); + var version = + versionRepository + .findByTenantIdAndId(identity.sourceLegacyTenantId(), versionId) + .orElseThrow(PublishedRealmEntryPolicyNotFoundException::new); + if (!canonicalTenantId.equals(identity.canonicalTenantId()) + || !identity.sourceLegacyTenantId().equals(version.getTenantId()) + || !versionIdEquals(versionId, version.getId()) + || (version.getVersionState() != VersionLifecycleState.PUBLISHED + && version.getVersionState() != VersionLifecycleState.ACTIVE)) { + throw new IllegalStateException( + "Published realm-entry policy version evidence is inconsistent"); + } + if (version.isScriptOnly()) { + throw new IllegalStateException("Script-only version cannot attest a realm-entry policy"); + } + + PublishedReleaseBundle bundle = + repository + .findByTenantIdAndVersionId(identity.sourceLegacyTenantId(), versionId) + .orElseThrow(PublishedRealmEntryPolicyNotFoundException::new); + if (bundle.getId() == null + || bundle.getId() <= 0 + || !identity.sourceLegacyTenantId().equals(bundle.getTenantId()) + || !versionIdEquals(versionId, bundle.getVersionId()) + || version.getVersionNumber() != bundle.getVersionNumber() + || !PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals( + bundle.getAttestationSchemaVersion()) + || bundle.isScriptOnly()) { + throw new IllegalStateException("Published release bundle evidence is inconsistent"); + } + String releaseBundleIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + canonicalTenantId, + versionId, + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + objectMapper); + return new PolicyOwnerContext(identity, version, bundle, releaseBundleIdentity); + } + + private PublishedRealmEntryPolicyEvidence validateStoredPolicy( + PublishedRealmEntryPolicy stored, PolicyOwnerContext owner) { + if (stored == null) { + throw new IllegalStateException("Published realm-entry policy row is missing"); + } + GameTenantIdentity identity = owner.tenantIdentity(); + var version = owner.version(); + PublishedReleaseBundle bundle = owner.bundle(); + Revision source = revisionRepository.findById(stored.sourceRevisionId()); + if (source == null + || source.getId() == null + || source.getId() <= 0 + || !identity.sourceLegacyTenantId().equals(source.getTenantId()) + || !versionIdEquals(version.getId(), source.getVersionId()) + || !RealmEntryPolicy.REVISION_KIND.equals(source.getRevisionKind())) { + throw new IllegalStateException( + "Published realm-entry policy source revision is inconsistent"); + } + + RealmEntryPolicy frozenPolicy = + RealmEntryPolicy.parseCanonical(stored.policyJson(), objectMapper); + RealmEntryPolicy sourcePolicy = RealmEntryPolicy.parse(source.getData(), objectMapper); + if (!frozenPolicy.equals(sourcePolicy) + || !matchesStoredPolicyFields(stored, frozenPolicy) + || !identity.canonicalTenantId().equals(stored.canonicalTenantId()) + || !Objects.equals(identity.provenanceKind().name(), stored.tenantIdentityProvenanceKind()) + || !Objects.equals(identity.sourceGameId(), stored.sourceGameRowId()) + || !Objects.equals(identity.sourceLegacyTenantId(), stored.sourceGameTenantKey()) + || !Objects.equals(version.getId(), stored.versionId()) + || version.getVersionNumber() != stored.versionNumber() + || !Objects.equals(bundle.getId(), stored.releaseBundleId()) + || !Objects.equals(source.getId(), stored.sourceRevisionId()) + || !Objects.equals(owner.releaseBundleIdentity(), stored.releaseBundleIdentity()) + || !Objects.equals(bundle.getPublishWorkflowId(), stored.publishWorkflowId()) + || !Objects.equals(bundle.getManifestHash(), stored.manifestHash())) { + throw new IllegalStateException( + "Published realm-entry policy evidence contradicts its owners"); + } + + PublishedRealmEntryPolicyEvidence evidence = + new PublishedRealmEntryPolicyEvidence( + stored.policyId(), + stored.canonicalTenantId(), + stored.tenantIdentityProvenanceKind(), + stored.sourceGameRowId(), + stored.sourceGameTenantKey(), + stored.versionId(), + stored.versionNumber(), + stored.sourceRevisionId(), + stored.releaseBundleIdentity(), + stored.publishWorkflowId(), + stored.manifestHash(), + frozenPolicy, + stored.policyDigest()); + if (!evidence.hasValidDigest(objectMapper)) { + throw new IllegalStateException( + "Published realm-entry policy digest does not match its evidence"); + } + return evidence; + } + + private void requirePolicyReadRequest(UUID canonicalTenantId, long versionId) { + if (canonicalTenantId == null || new UUID(0L, 0L).equals(canonicalTenantId) || versionId <= 0) { + throw new IllegalArgumentException("Published realm-entry policy owner scope is invalid"); + } + } + + private List prepareRealmEntryPolicies(VersionDto version) { + List revisions = + revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + version.tenantId(), version.id(), RealmEntryPolicy.REVISION_KIND); + if (revisions.isEmpty()) { + return List.of(); + } + if (revisions.size() > PublishedRealmEntryPolicySetEvidence.MAX_POLICIES) { + throw new IllegalStateException("Realm-entry policy set exceeds the v1 complete-read bound"); + } + if (version.scriptOnly()) { + throw new IllegalStateException("Script-only publication cannot freeze realm-entry policy"); + } + if (version.id() == null || version.id() <= 0 || version.versionNumber() <= 0) { + throw new IllegalStateException("Realm-entry policy requires an exact owner version"); + } + + Set selectorPairs = new HashSet<>(); + List sources = new java.util.ArrayList<>(); + for (Revision revision : revisions) { + if (revision == null + || revision.getId() == null + || revision.getId() <= 0 + || !Objects.equals(version.tenantId(), revision.getTenantId()) + || !Objects.equals(version.id(), revision.getVersionId()) + || !RealmEntryPolicy.REVISION_KIND.equals(revision.getRevisionKind())) { + throw new IllegalStateException( + "Realm-entry policy source revision is outside its owner scope"); + } + RealmEntryPolicy policy = RealmEntryPolicy.parse(revision.getData(), objectMapper); + String pair = policy.worldSlug() + "\u0000" + policy.realmSlug(); + if (!selectorPairs.add(pair)) { + throw new IllegalStateException("Duplicate published realm-entry policy selector"); + } + sources.add(new RealmEntryPolicySource(revision, policy)); + } + return List.copyOf(sources); + } + + private void freezeRealmEntryPolicies( + VersionDto version, PublishedReleaseBundle bundle, List sources) { + if (sources.isEmpty()) { + return; + } + if (bundle == null + || bundle.getId() == null + || bundle.getId() <= 0 + || !Objects.equals(version.tenantId(), bundle.getTenantId()) + || !Objects.equals(version.id(), bundle.getVersionId())) { + throw new IllegalStateException( + "Published release bundle did not persist its exact owner scope"); + } + GameTenantIdentity identity = + gameRepository + .findRuntimeTenantIdentityByTenantKey(version.tenantId()) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical Game Design tenant provenance is unavailable")); + validateTenantIdentity(identity, identity.canonicalTenantId(), version.tenantId()); + String releaseBundleIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + identity.canonicalTenantId(), + version.id(), + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + objectMapper); + + for (RealmEntryPolicySource source : sources) { + PublishedRealmEntryPolicyEvidence evidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.randomUUID(), + identity.canonicalTenantId(), + identity.provenanceKind().name(), + identity.sourceGameId(), + identity.sourceLegacyTenantId(), + version.id(), + version.versionNumber(), + source.revision().getId(), + releaseBundleIdentity, + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + source.policy(), + objectMapper); + RealmEntryPolicy policy = evidence.policy(); + realmEntryPolicyRepository.insert( + new PublishedRealmEntryPolicy( + evidence.policyId(), + evidence.canonicalTenantId(), + evidence.tenantIdentityProvenanceKind(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.versionId(), + evidence.versionNumber(), + bundle.getId(), + evidence.sourceRevisionId(), + evidence.releaseBundleIdentity(), + evidence.publishWorkflowId(), + evidence.manifestHash(), + policy.worldSlug(), + policy.worldDisplayName(), + policy.realmSlug(), + policy.realmDisplayName(), + policy.visible(), + policy.publicProduction(), + policy.stateScope().name(), + policy.entryPolicy().name(), + policy.canonicalJson(), + evidence.policyDigest())); + } + } + + private void validateTenantIdentity( + GameTenantIdentity identity, UUID expectedCanonicalTenantId, String expectedTenantKey) { + if (identity == null + || identity.canonicalTenantId() == null + || !identity.canonicalTenantId().equals(expectedCanonicalTenantId) + || identity.provenanceKind() == null + || identity.sourceGameId() == null + || identity.sourceGameId() <= 0 + || identity.sourceLegacyTenantId() == null + || identity.sourceLegacyTenantId().isBlank() + || !Objects.equals(identity.sourceLegacyTenantId(), expectedTenantKey)) { + throw new IllegalStateException( + "Game Design tenant identity provenance is incomplete or inconsistent"); + } + } + + private boolean matchesStoredPolicyFields( + PublishedRealmEntryPolicy stored, RealmEntryPolicy policy) { + return Objects.equals(stored.worldSlug(), policy.worldSlug()) + && Objects.equals(stored.worldDisplayName(), policy.worldDisplayName()) + && Objects.equals(stored.realmSlug(), policy.realmSlug()) + && Objects.equals(stored.realmDisplayName(), policy.realmDisplayName()) + && stored.visible() == policy.visible() + && stored.publicProduction() == policy.publicProduction() + && Objects.equals(stored.stateScope(), policy.stateScope().name()) + && Objects.equals(stored.entryPolicy(), policy.entryPolicy().name()); + } + + private boolean versionIdEquals(long requestedVersionId, Long persistedVersionId) { + return persistedVersionId != null && requestedVersionId == persistedVersionId; + } + + private record RealmEntryPolicySource(Revision revision, RealmEntryPolicy policy) {} + + private record PolicyOwnerContext( + GameTenantIdentity tenantIdentity, + net.firedevops.firemud.gamedesign.entity.Version version, + PublishedReleaseBundle bundle, + String releaseBundleIdentity) {} + private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { return new PublishedReleaseBundleDto( entity.getId(), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java index 7dac9d7d3b..28e7a2c102 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java @@ -4,6 +4,7 @@ import java.util.Optional; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.gamedesign.client.WorldManagementClient; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.RevisionDto; @@ -57,6 +58,7 @@ public RevisionDto saveRevision(RevisionDto dto) { throw new IllegalArgumentException("INVALID_ARGUMENT: published versions are immutable"); } validateCommandDefinitionIfPresent(dto); + validateRealmEntryPolicyIfPresent(dto, version.isScriptOnly()); AppliedWorldDesignMutationDto appliedWorldDesignMutation = applyWorldDesignMutationIfPresent(dto); Revision entity = revisionMapper.toEntity(dto); @@ -126,6 +128,17 @@ private void validateCommandDefinitionIfPresent(RevisionDto dto) { } } + private void validateRealmEntryPolicyIfPresent(RevisionDto dto, boolean scriptOnlyVersion) { + if (!RealmEntryPolicy.REVISION_KIND.equals(dto.revisionKind())) { + return; + } + if (scriptOnlyVersion) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: realmEntryPolicy requires a full version"); + } + RealmEntryPolicy.parse(dto.data(), objectMapper); + } + private void requireText(JsonNode definition, String field) { if (!definition.path(field).isTextual() || definition.path(field).asText().isBlank()) { throw invalidCommandDefinition(field + " is required"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index d0f1cb8ca3..1697204559 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -6,14 +6,24 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.v1.GameSessionTenantAssociationManifestEvidence; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyKind; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryStateScope; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -22,6 +32,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.grpc.server.service.GrpcService; +import tools.jackson.databind.ObjectMapper; /** Authenticated read of Game Design's own retained tenant identity provenance. */ @GrpcService @@ -29,15 +40,21 @@ public class TenantIdentityGrpcService extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { private final GameRepository gameRepository; private final GameSessionTenantAssociationRepository gameSessionAssociationRepository; + private final PublishedReleaseBundleService publishedReleaseBundleService; private final String workloadNamespace; + private final ObjectMapper objectMapper; public TenantIdentityGrpcService( GameRepository gameRepository, GameSessionTenantAssociationRepository gameSessionAssociationRepository, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + PublishedReleaseBundleService publishedReleaseBundleService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace, + ObjectMapper objectMapper) { this.gameRepository = gameRepository; this.gameSessionAssociationRepository = gameSessionAssociationRepository; + this.publishedReleaseBundleService = publishedReleaseBundleService; this.workloadNamespace = workloadNamespace; + this.objectMapper = objectMapper; } @Override @@ -236,6 +253,246 @@ public void resolveLegacyGameSessionTenantAssociation( responseObserver.onCompleted(); } + @Override + public void resolvePublishedRealmEntryPolicy( + ResolvePublishedRealmEntryPolicyRequest request, + StreamObserver responseObserver) { + if (!isGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Game Session workload identity is required") + .asRuntimeException()); + return; + } + + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (canonicalTenantId == null + || request.getVersionId() <= 0 + || !RealmEntryPolicy.isCanonicalSlug(request.getWorldSlug()) + || !RealmEntryPolicy.isCanonicalSlug(request.getRealmSlug()) + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription( + "Canonical tenant UUID, positive version, exact slugs, and the v1 request schema are required") + .asRuntimeException()); + return; + } + + PublishedRealmEntryPolicyEvidence evidence; + try { + evidence = + publishedReleaseBundleService.resolvePublishedRealmEntryPolicy( + canonicalTenantId, + request.getVersionId(), + request.getWorldSlug(), + request.getRealmSlug()); + } catch (PublishedRealmEntryPolicyNotFoundException ex) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("Published realm-entry policy is unavailable for the exact scope") + .asRuntimeException()); + return; + } catch (IllegalArgumentException | IllegalStateException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Published realm-entry policy evidence is inconsistent") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Published realm-entry policy is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Published realm-entry policy is temporarily unavailable" + : "Published realm-entry policy could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Published realm-entry policy could not be read") + .asRuntimeException()); + return; + } + + if (evidence == null + || !evidence.canonicalTenantId().equals(canonicalTenantId) + || evidence.versionId() != request.getVersionId() + || !evidence.policy().worldSlug().equals(request.getWorldSlug()) + || !evidence.policy().realmSlug().equals(request.getRealmSlug())) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Published realm-entry policy readback does not match the request") + .asRuntimeException()); + return; + } + try { + evidence.requireValidDigest(objectMapper); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Published realm-entry policy evidence failed canonical verification") + .asRuntimeException()); + return; + } + responseObserver.onNext(toPolicyResponse(evidence)); + responseObserver.onCompleted(); + } + + @Override + public void listPublishedRealmEntryPolicies( + ListPublishedRealmEntryPoliciesRequest request, + StreamObserver responseObserver) { + if (!isGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Game Session workload identity is required") + .asRuntimeException()); + return; + } + + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (canonicalTenantId == null + || request.getVersionId() <= 0 + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription( + "Canonical tenant UUID, positive version, and the v1 request schema are required") + .asRuntimeException()); + return; + } + + PublishedRealmEntryPolicySetEvidence evidence; + try { + evidence = + publishedReleaseBundleService.listPublishedRealmEntryPolicies( + canonicalTenantId, request.getVersionId()); + } catch (PublishedRealmEntryPolicyNotFoundException ex) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription( + "Complete published realm-entry policy set is unavailable for the exact scope") + .asRuntimeException()); + return; + } catch (IllegalArgumentException | IllegalStateException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Complete published realm-entry policy set is inconsistent or unsupported") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Published realm-entry policy set is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Published realm-entry policy set is temporarily unavailable" + : "Published realm-entry policy set could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Published realm-entry policy set could not be read") + .asRuntimeException()); + return; + } + + if (evidence == null + || !evidence.canonicalTenantId().equals(canonicalTenantId) + || evidence.versionId() != request.getVersionId() + || evidence.policies().isEmpty() + || evidence.policies().size() > PublishedRealmEntryPolicySetEvidence.MAX_POLICIES) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Complete published realm-entry policy set does not match the request") + .asRuntimeException()); + return; + } + try { + evidence.requireValidDigest(objectMapper); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Complete published realm-entry policy set failed canonical verification") + .asRuntimeException()); + return; + } + + ListPublishedRealmEntryPoliciesResponse.Builder response = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setSchemaVersion(RealmEntryPolicy.SCHEMA_VERSION) + .setTargetNamespace(workloadNamespace) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setVersionId(evidence.versionId()) + .setVersionNumber(evidence.versionNumber()) + .setReleaseBundleIdentity(evidence.releaseBundleIdentity()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setManifestHash(evidence.manifestHash()) + .setPolicyCount(evidence.policies().size()) + .setPolicySetDigest(evidence.policySetDigest()); + evidence.policies().stream().map(this::toPolicyResponse).forEach(response::addPolicies); + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + private ResolvePublishedRealmEntryPolicyResponse toPolicyResponse( + PublishedRealmEntryPolicyEvidence evidence) { + RealmEntryPolicy policy = evidence.policy(); + return ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setSchemaVersion(RealmEntryPolicy.SCHEMA_VERSION) + .setTargetNamespace(workloadNamespace) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setVersionId(evidence.versionId()) + .setVersionNumber(evidence.versionNumber()) + .setPolicyId(evidence.policyId().toString()) + .setSourceRevisionId(evidence.sourceRevisionId()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setTenantIdentityProvenanceKind(evidence.tenantIdentityProvenanceKind()) + .setReleaseBundleIdentity(evidence.releaseBundleIdentity()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setManifestHash(evidence.manifestHash()) + .setWorldSlug(policy.worldSlug()) + .setWorldDisplayName(policy.worldDisplayName()) + .setRealmSlug(policy.realmSlug()) + .setRealmDisplayName(policy.realmDisplayName()) + .setVisible(policy.visible()) + .setPublicProduction(policy.publicProduction()) + .setStateScope( + switch (policy.stateScope()) { + case SHARED -> PublishedRealmEntryStateScope.PUBLISHED_REALM_ENTRY_STATE_SCOPE_SHARED; + case ISOLATED -> + PublishedRealmEntryStateScope.PUBLISHED_REALM_ENTRY_STATE_SCOPE_ISOLATED; + }) + .setEntryPolicy( + PublishedRealmEntryPolicyKind.PUBLISHED_REALM_ENTRY_POLICY_KIND_PRESEEDED_ONLY) + .setPolicyJson(policy.canonicalJson()) + .setPolicyDigest(evidence.policyDigest()) + .build(); + } + private boolean isGameSessionPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null 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 800591b8b2..b8156df086 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -52,6 +52,8 @@ firemud: public-methods: - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation + - gamedesign.v1.TenantIdentityService/ResolvePublishedRealmEntryPolicy + - gamedesign.v1.TenantIdentityService/ListPublishedRealmEntryPolicies grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 13b9520bb1..5c541923d0 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -63,6 +63,8 @@ firemud: public-methods: - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation + - gamedesign.v1.TenantIdentityService/ResolvePublishedRealmEntryPolicy + - gamedesign.v1.TenantIdentityService/ListPublishedRealmEntryPolicies http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql b/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql new file mode 100644 index 0000000000..3e840852fc --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql @@ -0,0 +1,50 @@ +CREATE TABLE published_realm_entry_policy ( + policy_id UUID PRIMARY KEY, + canonical_tenant_id UUID NOT NULL REFERENCES game(canonical_tenant_id), + tenant_identity_provenance_kind VARCHAR(32) NOT NULL + CHECK (tenant_identity_provenance_kind IN ('RETAINED_GAME_V29', 'NEW_GAME_ROW')), + source_game_row_id BIGINT NOT NULL REFERENCES game(id) CHECK (source_game_row_id > 0), + source_game_tenant_key VARCHAR(36) NOT NULL + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key ~ '[^[:space:]]'), + version_id BIGINT NOT NULL REFERENCES version(id) CHECK (version_id > 0), + version_number INT NOT NULL CHECK (version_number > 0), + release_bundle_id BIGINT NOT NULL REFERENCES published_release_bundle(id), + source_revision_id BIGINT NOT NULL REFERENCES revision(id), + release_bundle_identity VARCHAR(71) NOT NULL + CHECK (release_bundle_identity ~ '^sha256:[0-9a-f]{64}$'), + publish_workflow_id VARCHAR(64) NOT NULL CHECK (publish_workflow_id <> ''), + manifest_hash VARCHAR(128) NOT NULL CHECK (manifest_hash <> ''), + world_slug VARCHAR(64) NOT NULL + CHECK (world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + world_display_name VARCHAR(512) NOT NULL + CHECK (char_length(world_display_name) BETWEEN 1 AND 128 + AND btrim(world_display_name) = world_display_name), + realm_slug VARCHAR(64) NOT NULL + CHECK (realm_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + realm_display_name VARCHAR(512) NOT NULL + CHECK (char_length(realm_display_name) BETWEEN 1 AND 128 + AND btrim(realm_display_name) = realm_display_name), + visible BOOLEAN NOT NULL, + public_production BOOLEAN NOT NULL, + state_scope VARCHAR(16) NOT NULL CHECK (state_scope IN ('SHARED', 'ISOLATED')), + entry_policy VARCHAR(32) NOT NULL CHECK (entry_policy = 'PRESEEDED_ONLY'), + policy_json TEXT NOT NULL CHECK (octet_length(policy_json) BETWEEN 1 AND 4096), + policy_digest VARCHAR(71) NOT NULL CHECK (policy_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT uq_published_realm_entry_policy_selector + UNIQUE (canonical_tenant_id, version_id, world_slug, realm_slug) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_published_realm_entry_policy_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'published realm-entry policy evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_realm_entry_policy_immutable + BEFORE UPDATE OR DELETE ON published_realm_entry_policy + FOR EACH ROW + EXECUTE FUNCTION reject_published_realm_entry_policy_mutation(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java index ef2dab2ea3..19fd7faabf 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java @@ -80,6 +80,14 @@ void migratesOnlyExactOwnerKeysAndReadsImmutableGameRowProvenance() throws Excep GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V29, retainedGameId, "legacy-owner-alpha")); + assertThat(repository.findRuntimeTenantIdentityByTenantKey("legacy-owner-alpha")) + .contains( + new GameTenantIdentity( + retainedTenantId, + GameTenantIdentity.ProvenanceKind.RETAINED_GAME_V29, + retainedGameId, + "legacy-owner-alpha")); + assertThat(repository.findRuntimeTenantIdentityByTenantKey("missing-owner-key")).isEmpty(); assertThat( dsl.select( CANONICAL_TENANT_ID, PROVENANCE_KIND, SOURCE_GAME_ID, SOURCE_LEGACY_TENANT_ID) @@ -110,6 +118,13 @@ void migratesOnlyExactOwnerKeysAndReadsImmutableGameRowProvenance() throws Excep GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, saved.getId(), "new-owner-key")); + assertThat(repository.findRuntimeTenantIdentityByTenantKey("new-owner-key")) + .contains( + new GameTenantIdentity( + saved.getCanonicalTenantId(), + GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, + saved.getId(), + "new-owner-key")); Game forgedGame = new Game(); forgedGame.setTenantId("forged-owner-key"); 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 0b1c968fc7..79d9382724 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 @@ -16,19 +16,28 @@ import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.security.AuthTokenInterceptor; import net.firedevops.firemud.common.security.GrpcAuthProperties; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; import net.firedevops.firemud.gamedesign.v1.PingRequest; import net.firedevops.firemud.gamedesign.v1.PingResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import org.junit.jupiter.api.Test; @@ -39,12 +48,17 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.core.env.PropertySource; import org.springframework.core.io.FileSystemResource; +import tools.jackson.databind.ObjectMapper; class TenantIdentityGrpcAuthWiringTest { private static final String TENANT_METHOD = "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity"; private static final String ASSOCIATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"; + private static final String REALM_POLICY_METHOD = + "gamedesign.v1.TenantIdentityService/ResolvePublishedRealmEntryPolicy"; + private static final String REALM_POLICY_SET_METHOD = + "gamedesign.v1.TenantIdentityService/ListPublishedRealmEntryPolicies"; private static final String PING_METHOD = "gamedesign.v1.GameDesignService/Ping"; private static final String TENANT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; @@ -58,6 +72,20 @@ class TenantIdentityGrpcAuthWiringTest { ResolveRuntimeTenantIdentityResponse.getDefaultInstance()); private static final MethodDescriptor PING_METHOD_DESCRIPTOR = unaryMethod(PING_METHOD, PingRequest.getDefaultInstance(), PingResponse.getDefaultInstance()); + private static final MethodDescriptor< + ResolvePublishedRealmEntryPolicyRequest, ResolvePublishedRealmEntryPolicyResponse> + REALM_POLICY_METHOD_DESCRIPTOR = + unaryMethod( + REALM_POLICY_METHOD, + ResolvePublishedRealmEntryPolicyRequest.getDefaultInstance(), + ResolvePublishedRealmEntryPolicyResponse.getDefaultInstance()); + private static final MethodDescriptor< + ListPublishedRealmEntryPoliciesRequest, ListPublishedRealmEntryPoliciesResponse> + REALM_POLICY_SET_METHOD_DESCRIPTOR = + unaryMethod( + REALM_POLICY_SET_METHOD, + ListPublishedRealmEntryPoliciesRequest.getDefaultInstance(), + ListPublishedRealmEntryPoliciesResponse.getDefaultInstance()); @Test void noTokenWithValidSameNamespacePeerReachesTenantIdentityService() { @@ -75,7 +103,11 @@ void noTokenWithValidSameNamespacePeerReachesTenantIdentityService() { "legacy-owner-key-42"))); TenantIdentityGrpcService service = new TenantIdentityGrpcService( - repository, mock(GameSessionTenantAssociationRepository.class), "test"); + repository, + mock(GameSessionTenantAssociationRepository.class), + mock(PublishedReleaseBundleService.class), + "test", + new ObjectMapper()); DispatchResult result = dispatchTenantMethod(interceptor, service, GAME_SESSION_URI); @@ -87,6 +119,173 @@ void noTokenWithValidSameNamespacePeerReachesTenantIdentityService() { }); } + @Test + void noTokenWithValidSameNamespacePeerReachesPublishedRealmPolicyRead() { + withConfiguredInterceptor( + interceptor -> { + PublishedReleaseBundleService publishedReleaseBundleService = + mock(PublishedReleaseBundleService.class); + UUID tenantId = UUID.fromString(TENANT_UUID); + RealmEntryPolicy policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Realm\"," + + "\"visible\":true,\"publicProduction\":false,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + var evidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("22222222-2222-4222-8222-222222222222"), + tenantId, + "NEW_GAME_ROW", + 42L, + "source-game-key", + 7L, + 3, + 18L, + "sha256:" + "1".repeat(64), + "publish-workflow-3", + "manifest-3", + policy, + new ObjectMapper()); + when(publishedReleaseBundleService.resolvePublishedRealmEntryPolicy( + tenantId, 7L, "earth", "main")) + .thenReturn(evidence); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + mock(GameRepository.class), + mock(GameSessionTenantAssociationRepository.class), + publishedReleaseBundleService, + "test", + new ObjectMapper()); + + PolicyDispatchResult result = + dispatchRealmPolicyMethod(interceptor, service, GAME_SESSION_URI); + + assertThat(result.observer().failure).isFalse(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getPolicyId()) + .isEqualTo(evidence.policyId().toString()); + assertThat(result.handlerDispatched()).isTrue(); + verify(publishedReleaseBundleService) + .resolvePublishedRealmEntryPolicy(tenantId, 7L, "earth", "main"); + }); + } + + @Test + void noTokenWithValidSameNamespacePeerReachesCompleteRealmPolicySetRead() { + withConfiguredInterceptor( + interceptor -> { + PublishedReleaseBundleService publishedReleaseBundleService = + mock(PublishedReleaseBundleService.class); + UUID tenantId = UUID.fromString(TENANT_UUID); + ObjectMapper mapper = new ObjectMapper(); + RealmEntryPolicy policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Realm\"," + + "\"visible\":true,\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + mapper); + var policyEvidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("22222222-2222-4222-8222-222222222222"), + tenantId, + "NEW_GAME_ROW", + 42L, + "source-game-key", + 7L, + 3, + 18L, + "sha256:" + "1".repeat(64), + "publish-workflow-3", + "manifest-3", + policy, + mapper); + var setEvidence = + PublishedRealmEntryPolicySetEvidence.create( + tenantId, + 7L, + 3, + policyEvidence.releaseBundleIdentity(), + "publish-workflow-3", + "manifest-3", + List.of(policyEvidence), + mapper); + when(publishedReleaseBundleService.listPublishedRealmEntryPolicies(tenantId, 7L)) + .thenReturn(setEvidence); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + mock(GameRepository.class), + mock(GameSessionTenantAssociationRepository.class), + publishedReleaseBundleService, + "test", + new ObjectMapper()); + + PolicySetDispatchResult result = + dispatchRealmPolicySetMethod(interceptor, service, GAME_SESSION_URI); + + assertThat(result.observer().failure).isFalse(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getPolicyCount()).isEqualTo(1); + assertThat(result.observer().response.getPolicySetDigest()) + .isEqualTo(setEvidence.policySetDigest()); + assertThat(result.observer().response.getPolicies(0).getPublicProduction()).isTrue(); + assertThat(result.handlerDispatched()).isTrue(); + verify(publishedReleaseBundleService).listPublishedRealmEntryPolicies(tenantId, 7L); + }); + } + + @Test + void publishedRealmPolicyMethodIsDeniedBeforeOwnerReadForWrongPeer() { + withConfiguredInterceptor( + interceptor -> { + PublishedReleaseBundleService publishedReleaseBundleService = + mock(PublishedReleaseBundleService.class); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + mock(GameRepository.class), + mock(GameSessionTenantAssociationRepository.class), + publishedReleaseBundleService, + "test", + new ObjectMapper()); + + PolicyDispatchResult wrong = + dispatchRealmPolicyMethod( + interceptor, service, "spiffe://firemud/ns/test/sa/account-service"); + + assertThat(wrong.observer().failure).isTrue(); + assertThat(wrong.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrong.handlerDispatched()).isTrue(); + org.mockito.Mockito.verifyNoInteractions(publishedReleaseBundleService); + }); + } + + @Test + void completeRealmPolicySetMethodIsDeniedBeforeOwnerReadForWrongPeer() { + withConfiguredInterceptor( + interceptor -> { + PublishedReleaseBundleService publishedReleaseBundleService = + mock(PublishedReleaseBundleService.class); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + mock(GameRepository.class), + mock(GameSessionTenantAssociationRepository.class), + publishedReleaseBundleService, + "test", + new ObjectMapper()); + + PolicySetDispatchResult wrong = + dispatchRealmPolicySetMethod( + interceptor, service, "spiffe://firemud/ns/test/sa/account-service"); + + assertThat(wrong.observer().failure).isTrue(); + assertThat(wrong.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrong.handlerDispatched()).isTrue(); + org.mockito.Mockito.verifyNoInteractions(publishedReleaseBundleService); + }); + } + @Test void noTokenWithAbsentOrWrongPeerIsDeniedBeforeOwnerRead() { withConfiguredInterceptor( @@ -94,7 +293,11 @@ void noTokenWithAbsentOrWrongPeerIsDeniedBeforeOwnerRead() { GameRepository repository = mock(GameRepository.class); TenantIdentityGrpcService service = new TenantIdentityGrpcService( - repository, mock(GameSessionTenantAssociationRepository.class), "test"); + repository, + mock(GameSessionTenantAssociationRepository.class), + mock(PublishedReleaseBundleService.class), + "test", + new ObjectMapper()); DispatchResult absent = dispatchTenantMethod(interceptor, service, null); DispatchResult wrong = @@ -180,6 +383,106 @@ public void onMessage(ResolveRuntimeTenantIdentityRequest request) { return new DispatchResult(observer, handlerDispatched.get()); } + private static PolicyDispatchResult dispatchRealmPolicyMethod( + AuthTokenInterceptor interceptor, TenantIdentityGrpcService service, String peerUri) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall + call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(REALM_POLICY_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + PolicyTestObserver observer = new PolicyTestObserver(); + ServerCallHandler< + ResolvePublishedRealmEntryPolicyRequest, ResolvePublishedRealmEntryPolicyResponse> + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ResolvePublishedRealmEntryPolicyRequest, + ResolvePublishedRealmEntryPolicyResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ResolvePublishedRealmEntryPolicyRequest request) { + service.resolvePublishedRealmEntryPolicy(request, observer); + } + }; + } + }; + ResolvePublishedRealmEntryPolicyRequest request = + ResolvePublishedRealmEntryPolicyRequest.newBuilder() + .setCanonicalTenantId(TENANT_UUID) + .setVersionId(7L) + .setWorldSlug("earth") + .setRealmSlug("main") + .build(); + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, new Metadata(), next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new PolicyDispatchResult(observer, handlerDispatched.get()); + } + + private static PolicySetDispatchResult dispatchRealmPolicySetMethod( + AuthTokenInterceptor interceptor, TenantIdentityGrpcService service, String peerUri) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall + call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(REALM_POLICY_SET_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + PolicySetTestObserver observer = new PolicySetTestObserver(); + ServerCallHandler< + ListPublishedRealmEntryPoliciesRequest, ListPublishedRealmEntryPoliciesResponse> + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ListPublishedRealmEntryPoliciesRequest, + ListPublishedRealmEntryPoliciesResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ListPublishedRealmEntryPoliciesRequest request) { + service.listPublishedRealmEntryPolicies(request, observer); + } + }; + } + }; + ListPublishedRealmEntryPoliciesRequest request = + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setCanonicalTenantId(TENANT_UUID) + .setVersionId(7L) + .build(); + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, new Metadata(), next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new PolicySetDispatchResult(observer, handlerDispatched.get()); + } + private static void withConfiguredInterceptor( java.util.function.Consumer action) { new ApplicationContextRunner() @@ -207,11 +510,48 @@ private static void withConfiguredInterceptor( context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(TENANT_METHOD, ASSOCIATION_METHOD); + .containsExactly( + TENANT_METHOD, + ASSOCIATION_METHOD, + REALM_POLICY_METHOD, + REALM_POLICY_SET_METHOD); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } + @Test + void productionConfigurationExemptsExactlyTheOwnerReadMethods() throws IOException { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withInitializer( + context -> { + try { + PropertySource production = + new YamlPropertySourceLoader() + .load( + "game-design-production", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(production); + } catch (IOException exception) { + throw new IllegalStateException( + "Could not load Game Design production config", exception); + } + }) + .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .run( + context -> + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .containsExactly( + TENANT_METHOD, + ASSOCIATION_METHOD, + REALM_POLICY_METHOD, + REALM_POLICY_SET_METHOD)); + } + private static MethodDescriptor unaryMethod( String fullMethodName, ReqT requestDefault, RespT responseDefault) { @@ -225,6 +565,11 @@ MethodDescriptor unaryMethod( private record DispatchResult(TestObserver observer, boolean handlerDispatched) {} + private record PolicyDispatchResult(PolicyTestObserver observer, boolean handlerDispatched) {} + + private record PolicySetDispatchResult( + PolicySetTestObserver observer, boolean handlerDispatched) {} + private static final class TestObserver implements StreamObserver { private ResolveRuntimeTenantIdentityResponse response; @@ -248,4 +593,52 @@ public void onCompleted() { completed = true; } } + + private static final class PolicyTestObserver + implements StreamObserver { + private ResolvePublishedRealmEntryPolicyResponse response; + private Status.Code statusCode; + private boolean failure; + private boolean completed; + + @Override + public void onNext(ResolvePublishedRealmEntryPolicyResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = true; + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class PolicySetTestObserver + implements StreamObserver { + private ListPublishedRealmEntryPoliciesResponse response; + private Status.Code statusCode; + private boolean failure; + private boolean completed; + + @Override + public void onNext(ListPublishedRealmEntryPoliciesResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = true; + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java index e1f52c1a3b..2188800ad1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import org.junit.jupiter.api.Test; @@ -34,7 +35,12 @@ class GameSessionTenantAssociationGrpcTest { private final GameSessionTenantAssociationRepository repository = mock(GameSessionTenantAssociationRepository.class); private final TenantIdentityGrpcService service = - new TenantIdentityGrpcService(mock(GameRepository.class), repository, "test"); + new TenantIdentityGrpcService( + mock(GameRepository.class), + repository, + mock(PublishedReleaseBundleService.class), + "test", + new tools.jackson.databind.ObjectMapper()); @Test void exactGameSessionPeerPrecedesSyntaxAndOwnerReads() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 22cfa90253..865b8bc19c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -5,18 +5,29 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +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.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.entity.PublishedRealmEntryPolicy; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Revision; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.repository.PublishedRealmEntryPolicyRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -25,8 +36,20 @@ import tools.jackson.databind.ObjectMapper; class PublishedReleaseBundleServiceImplTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); + private static final UUID POLICY_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String VALID_REALM_ENTRY_POLICY = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Realm\"," + + "\"visible\":true,\"publicProduction\":false,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + @Mock private PublishedReleaseBundleRepository repository; + @Mock private PublishedRealmEntryPolicyRepository realmEntryPolicyRepository; + @Mock private GameRepository gameRepository; @Mock private RevisionRepository revisionRepository; + @Mock private VersionRepository versionRepository; private PublishedReleaseBundleServiceImpl service; @@ -34,7 +57,13 @@ class PublishedReleaseBundleServiceImplTest { void setUp() { MockitoAnnotations.openMocks(this); service = - new PublishedReleaseBundleServiceImpl(repository, revisionRepository, new ObjectMapper()); + new PublishedReleaseBundleServiceImpl( + repository, + revisionRepository, + realmEntryPolicyRepository, + gameRepository, + versionRepository, + new ObjectMapper()); } @Test @@ -87,6 +116,269 @@ void createFullVersionBundlePersistsImmutableAttestation() { assertEquals("v1", dto.attestationSchemaVersion()); } + @Test + void createFullVersionBundleFreezesPolicyWithExactOwnerAndSourceEvidence() { + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) + .thenReturn(List.of(policyRevision(21L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY))); + when(gameRepository.findRuntimeTenantIdentityByTenantKey("tenant-1")) + .thenReturn(Optional.of(tenantIdentity("tenant-1"))); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle entity = invocation.getArgument(0); + entity.setId(11L); + return entity; + }); + + service.createFullVersionBundle( + version(), + "workflow-1", + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of()); + + org.mockito.ArgumentCaptor policyCaptor = + org.mockito.ArgumentCaptor.forClass(PublishedRealmEntryPolicy.class); + verify(realmEntryPolicyRepository).insert(policyCaptor.capture()); + PublishedRealmEntryPolicy frozen = policyCaptor.getValue(); + assertEquals(CANONICAL_TENANT_ID, frozen.canonicalTenantId()); + assertEquals("NEW_GAME_ROW", frozen.tenantIdentityProvenanceKind()); + assertEquals(42L, frozen.sourceGameRowId()); + assertEquals("tenant-1", frozen.sourceGameTenantKey()); + assertEquals(7L, frozen.versionId()); + assertEquals(8, frozen.versionNumber()); + assertEquals(11L, frozen.releaseBundleId()); + assertEquals(21L, frozen.sourceRevisionId()); + assertEquals( + RealmEntryPolicy.parse(VALID_REALM_ENTRY_POLICY, new ObjectMapper()).canonicalJson(), + frozen.policyJson()); + assertEquals("sha256:", frozen.policyDigest().substring(0, 7)); + } + + @Test + void createFullVersionBundlePreservesLegacyPublicationWhenNoPolicyExists() { + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle entity = invocation.getArgument(0); + entity.setId(11L); + return entity; + }); + + var result = + service.createFullVersionBundle( + version(), + "workflow-1", + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of()); + + assertEquals(11L, result.id()); + verify(realmEntryPolicyRepository, never()).insert(any(PublishedRealmEntryPolicy.class)); + verify(gameRepository, never()).findRuntimeTenantIdentityByTenantKey("tenant-1"); + } + + @Test + void createFullVersionBundleRejectsWrongTenantVersionSourceAndDuplicateSelectors() { + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) + .thenReturn(List.of(policyRevision(21L, "tenant-2", 7L, VALID_REALM_ENTRY_POLICY))); + + assertThrows( + IllegalStateException.class, + () -> + service.createFullVersionBundle( + version(), + "workflow-1", + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of())); + verify(repository, never()).save(any(PublishedReleaseBundle.class)); + + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) + .thenReturn( + List.of( + policyRevision(21L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY), + policyRevision(22L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY))); + assertThrows( + IllegalStateException.class, + () -> + service.createFullVersionBundle( + version(), + "workflow-1", + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of())); + verify(gameRepository, never()).findRuntimeTenantIdentityByTenantKey("tenant-1"); + } + + @Test + void publishedPolicyReadRequiresPublishedBundleAndVerifiesFrozenEvidence() { + PublishedReleaseBundle bundle = publishedBundle(); + Revision source = policyRevision(21L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY); + RealmEntryPolicy policy = RealmEntryPolicy.parse(VALID_REALM_ENTRY_POLICY, new ObjectMapper()); + String bundleIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, 7L, "workflow-1", "abc123", new ObjectMapper()); + PublishedRealmEntryPolicyEvidence evidence = + PublishedRealmEntryPolicyEvidence.create( + POLICY_ID, + CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 42L, + "tenant-1", + 7L, + 8, + 21L, + bundleIdentity, + "workflow-1", + "abc123", + policy, + new ObjectMapper()); + when(gameRepository.findRuntimeTenantIdentityByCanonicalTenantId(CANONICAL_TENANT_ID)) + .thenReturn(Optional.of(tenantIdentity("tenant-1"))); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)) + .thenReturn(Optional.of(publishedVersion())); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(bundle)); + when(realmEntryPolicyRepository.findByScope(CANONICAL_TENANT_ID, 7L, "earth", "main")) + .thenReturn(List.of(storedPolicy(evidence, bundle.getId()))); + when(revisionRepository.findById(21L)).thenReturn(source); + + var resolved = + service.resolvePublishedRealmEntryPolicy(CANONICAL_TENANT_ID, 7L, "earth", "main"); + + assertEquals(POLICY_ID, resolved.policyId()); + assertEquals( + RealmEntryPolicy.parse(VALID_REALM_ENTRY_POLICY, new ObjectMapper()).canonicalJson(), + resolved.policy().canonicalJson()); + assertEquals(bundleIdentity, resolved.releaseBundleIdentity()); + assertEquals(evidence.policyDigest(), resolved.policyDigest()); + } + + @Test + void publishedPolicyReadDeniesLegacyBundleAndContradictoryEvidence() { + when(gameRepository.findRuntimeTenantIdentityByCanonicalTenantId(CANONICAL_TENANT_ID)) + .thenReturn(Optional.of(tenantIdentity("tenant-1"))); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)) + .thenReturn(Optional.of(publishedVersion())); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.of(publishedBundle())); + when(realmEntryPolicyRepository.findByScope(CANONICAL_TENANT_ID, 7L, "earth", "main")) + .thenReturn(List.of()); + assertThrows( + PublishedRealmEntryPolicyNotFoundException.class, + () -> service.resolvePublishedRealmEntryPolicy(CANONICAL_TENANT_ID, 7L, "earth", "main")); + + RealmEntryPolicy policy = RealmEntryPolicy.parse(VALID_REALM_ENTRY_POLICY, new ObjectMapper()); + var bundleIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, 7L, "workflow-1", "abc123", new ObjectMapper()); + var validEvidence = + PublishedRealmEntryPolicyEvidence.create( + POLICY_ID, + CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 42L, + "tenant-1", + 7L, + 8, + 21L, + bundleIdentity, + "workflow-1", + "abc123", + policy, + new ObjectMapper()); + PublishedRealmEntryPolicy contradictory = + storedPolicy(validEvidence, 11L, "sha256:" + "0".repeat(64)); + when(realmEntryPolicyRepository.findByScope(CANONICAL_TENANT_ID, 7L, "earth", "main")) + .thenReturn(List.of(contradictory)); + when(revisionRepository.findById(21L)) + .thenReturn(policyRevision(21L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY)); + + assertThrows( + IllegalStateException.class, + () -> service.resolvePublishedRealmEntryPolicy(CANONICAL_TENANT_ID, 7L, "earth", "main")); + } + + @Test + void completePolicySetReadReturnsAllRowsInCanonicalOrderWithStableOwnerDigest() { + stubPolicyOwnerRead(); + PublishedRealmEntryPolicyEvidence main = policyEvidence("main", true, true, 21L); + PublishedRealmEntryPolicyEvidence side = policyEvidence("side", false, false, 22L); + when(realmEntryPolicyRepository.findByOwner(CANONICAL_TENANT_ID, 7L)) + .thenReturn(List.of(storedPolicy(side, 11L), storedPolicy(main, 11L))); + when(revisionRepository.findById(21L)) + .thenReturn(policyRevision(21L, "tenant-1", 7L, main.policy().canonicalJson())); + when(revisionRepository.findById(22L)) + .thenReturn(policyRevision(22L, "tenant-1", 7L, side.policy().canonicalJson())); + + PublishedRealmEntryPolicySetEvidence set = + service.listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID, 7L); + + assertEquals(2, set.policies().size()); + assertEquals("main", set.policies().getFirst().policy().realmSlug()); + assertEquals("side", set.policies().get(1).policy().realmSlug()); + assertEquals(true, set.policies().getFirst().policy().publicProduction()); + assertEquals(true, set.hasValidDigest(new ObjectMapper())); + assertEquals(21L, set.policies().getFirst().sourceRevisionId()); + } + + @Test + void completePolicySetReadRejectsMissingDuplicateInvalidCardinalityAndContradictoryRows() { + stubPolicyOwnerRead(); + when(realmEntryPolicyRepository.findByOwner(CANONICAL_TENANT_ID, 7L)).thenReturn(List.of()); + assertThrows( + PublishedRealmEntryPolicyNotFoundException.class, + () -> service.listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID, 7L)); + + PublishedRealmEntryPolicyEvidence hidden = policyEvidence("hidden", false, false, 23L); + when(realmEntryPolicyRepository.findByOwner(CANONICAL_TENANT_ID, 7L)) + .thenReturn(List.of(storedPolicy(hidden, 11L))); + when(revisionRepository.findById(23L)) + .thenReturn(policyRevision(23L, "tenant-1", 7L, hidden.policy().canonicalJson())); + assertThrows( + IllegalArgumentException.class, + () -> service.listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID, 7L)); + + PublishedRealmEntryPolicyEvidence first = policyEvidence("main", true, true, 24L); + PublishedRealmEntryPolicyEvidence duplicate = policyEvidence("main", true, true, 25L); + when(realmEntryPolicyRepository.findByOwner(CANONICAL_TENANT_ID, 7L)) + .thenReturn(List.of(storedPolicy(first, 11L), storedPolicy(duplicate, 11L))); + when(revisionRepository.findById(24L)) + .thenReturn(policyRevision(24L, "tenant-1", 7L, first.policy().canonicalJson())); + when(revisionRepository.findById(25L)) + .thenReturn(policyRevision(25L, "tenant-1", 7L, duplicate.policy().canonicalJson())); + assertThrows( + IllegalArgumentException.class, + () -> service.listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID, 7L)); + + when(realmEntryPolicyRepository.findByOwner(CANONICAL_TENANT_ID, 7L)) + .thenReturn(List.of(storedPolicy(first, 12L))); + assertThrows( + IllegalStateException.class, + () -> service.listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID, 7L)); + } + + @Test + void completePolicySetReadRejectsOverLimitInsteadOfReturningATruncatedPrefix() { + stubPolicyOwnerRead(); + PublishedRealmEntryPolicyEvidence main = policyEvidence("main", true, true, 21L); + when(realmEntryPolicyRepository.findByOwner(CANONICAL_TENANT_ID, 7L)) + .thenReturn( + java.util.Collections.nCopies( + PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1, storedPolicy(main, 11L))); + + assertThrows( + IllegalStateException.class, + () -> service.listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID, 7L)); + verify(revisionRepository, never()).findById(21L); + } + @Test void createFullVersionBundleRejectsDuplicateAttestation() { VersionDto version = @@ -240,4 +532,116 @@ private VersionDto version() { LocalDateTime.now(), LocalDateTime.now()); } + + private static Revision policyRevision( + long revisionId, String tenantId, long versionId, String data) { + Revision revision = new Revision(); + revision.setId(revisionId); + revision.setTenantId(tenantId); + revision.setVersionId(versionId); + revision.setRevisionKind(RealmEntryPolicy.REVISION_KIND); + revision.setData(data); + return revision; + } + + private static GameTenantIdentity tenantIdentity(String tenantKey) { + return new GameTenantIdentity( + CANONICAL_TENANT_ID, GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, 42L, tenantKey); + } + + private static net.firedevops.firemud.gamedesign.entity.Version publishedVersion() { + net.firedevops.firemud.gamedesign.entity.Version version = + new net.firedevops.firemud.gamedesign.entity.Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionNumber(8); + version.setVersionState(VersionLifecycleState.PUBLISHED); + return version; + } + + private static PublishedReleaseBundle publishedBundle() { + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setId(11L); + bundle.setTenantId("tenant-1"); + bundle.setVersionId(7L); + bundle.setVersionNumber(8); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("workflow-1"); + bundle.setManifestHash("abc123"); + return bundle; + } + + private static PublishedRealmEntryPolicy storedPolicy( + PublishedRealmEntryPolicyEvidence evidence, long bundleId) { + return storedPolicy(evidence, bundleId, evidence.policyDigest()); + } + + private static PublishedRealmEntryPolicy storedPolicy( + PublishedRealmEntryPolicyEvidence evidence, long bundleId, String digest) { + RealmEntryPolicy policy = evidence.policy(); + return new PublishedRealmEntryPolicy( + evidence.policyId(), + evidence.canonicalTenantId(), + evidence.tenantIdentityProvenanceKind(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.versionId(), + evidence.versionNumber(), + bundleId, + evidence.sourceRevisionId(), + evidence.releaseBundleIdentity(), + evidence.publishWorkflowId(), + evidence.manifestHash(), + policy.worldSlug(), + policy.worldDisplayName(), + policy.realmSlug(), + policy.realmDisplayName(), + policy.visible(), + policy.publicProduction(), + policy.stateScope().name(), + policy.entryPolicy().name(), + policy.canonicalJson(), + digest); + } + + private void stubPolicyOwnerRead() { + when(gameRepository.findRuntimeTenantIdentityByCanonicalTenantId(CANONICAL_TENANT_ID)) + .thenReturn(Optional.of(tenantIdentity("tenant-1"))); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)) + .thenReturn(Optional.of(publishedVersion())); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.of(publishedBundle())); + } + + private static PublishedRealmEntryPolicyEvidence policyEvidence( + String realmSlug, boolean visible, boolean publicProduction, long sourceRevisionId) { + ObjectMapper objectMapper = new ObjectMapper(); + String json = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"" + + realmSlug + + "\",\"realmDisplayName\":\"" + + realmSlug + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + RealmEntryPolicy policy = RealmEntryPolicy.parse(json, objectMapper); + return PublishedRealmEntryPolicyEvidence.create( + UUID.nameUUIDFromBytes(realmSlug.concat(Long.toString(sourceRevisionId)).getBytes()), + CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 42L, + "tenant-1", + 7L, + 8, + sourceRevisionId, + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, 7L, "workflow-1", "abc123", objectMapper), + "workflow-1", + "abc123", + policy, + objectMapper); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java index 34efaaa994..7deeaa37f1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java @@ -31,6 +31,12 @@ import tools.jackson.databind.ObjectMapper; class RevisionServiceImplTest { + private static final String VALID_REALM_ENTRY_POLICY = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Realm\"," + + "\"visible\":true,\"publicProduction\":false,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + @Mock private RevisionRepository revisionRepository; @Mock private GameRepository gameRepository; @Mock private VersionRepository versionRepository; @@ -262,6 +268,94 @@ void saveRevisionRejectsFractionalActionStateDurationBeforePersisting() { verify(revisionRepository, never()).save(any(Revision.class)); } + @Test + void saveRevisionPersistsClosedV1PreseededRealmEntryPolicy() { + Game game = setupGameAndVersion(); + Revision saved = new Revision(); + saved.setId(13L); + saved.setTenantId(game.getTenantId()); + saved.setVersionId(7L); + saved.setRevisionKind("REALM_ENTRY_POLICY"); + saved.setData(VALID_REALM_ENTRY_POLICY); + when(revisionRepository.save(any(Revision.class))).thenReturn(saved); + + RevisionDto result = + service.saveRevision( + new RevisionDto( + null, + "1", + 7L, + 3L, + VALID_REALM_ENTRY_POLICY, + "REALM_ENTRY_POLICY", + null, + null, + null, + null)); + + assertEquals(13L, result.id()); + assertEquals("REALM_ENTRY_POLICY", result.revisionKind()); + verify(revisionRepository).save(any(Revision.class)); + } + + @Test + void saveRevisionRejectsUnsupportedOrOpenRealmEntryPolicyBeforePersisting() { + setupGameAndVersion(); + String unsupported = VALID_REALM_ENTRY_POLICY.replace("PRESEEDED_ONLY", "AUTO_PROVISIONED"); + String descriptor = + VALID_REALM_ENTRY_POLICY.replace( + "\"entryPolicy\":\"PRESEEDED_ONLY\"", + "\"entryPolicy\":\"PRESEEDED_ONLY\",\"descriptor\":{}"); + String missingBoolean = VALID_REALM_ENTRY_POLICY.replace("\"publicProduction\":false,", ""); + String duplicateField = + VALID_REALM_ENTRY_POLICY.replace( + "\"schemaVersion\":1,", "\"schemaVersion\":1,\"schemaVersion\":1,"); + + for (String invalid : List.of(unsupported, descriptor, missingBoolean, duplicateField)) { + assertThrows( + IllegalArgumentException.class, + () -> + service.saveRevision( + new RevisionDto( + null, "1", 7L, 3L, invalid, "REALM_ENTRY_POLICY", null, null, null, null))); + } + + verify(revisionRepository, never()).save(any(Revision.class)); + verify(worldManagementClient, never()) + .applyWorldDesignMutation(any(), anyLong(), any(WorldDesignMutationRevisionDto.class)); + } + + @Test + void saveRevisionRejectsRealmEntryPolicyOnScriptOnlyVersion() { + setupGameAndVersion(); + Version scriptOnly = new Version(); + scriptOnly.setId(7L); + scriptOnly.setTenantId("1"); + scriptOnly.setScriptOnly(true); + when(versionRepository.findByTenantIdAndId("1", 7L)) + .thenReturn(java.util.Optional.of(scriptOnly)); + + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, + () -> + service.saveRevision( + new RevisionDto( + null, + "1", + 7L, + 3L, + VALID_REALM_ENTRY_POLICY, + "REALM_ENTRY_POLICY", + null, + null, + null, + null))); + + assertEquals("INVALID_ARGUMENT: realmEntryPolicy requires a full version", ex.getMessage()); + verify(revisionRepository, never()).save(any(Revision.class)); + } + @Test void saveRevisionAppliesWorldMutationBeforePersisting() { Game game = setupGameAndVersion(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index 2add931163..ce7a2bc81d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -14,14 +15,23 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import org.jooq.exception.TooManyRowsException; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; +import tools.jackson.databind.ObjectMapper; class TenantIdentityGrpcServiceTest { private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; @@ -31,8 +41,15 @@ class TenantIdentityGrpcServiceTest { private final GameRepository repository = mock(GameRepository.class); private final GameSessionTenantAssociationRepository associationRepository = mock(GameSessionTenantAssociationRepository.class); + private final PublishedReleaseBundleService publishedReleaseBundleService = + mock(PublishedReleaseBundleService.class); private final TenantIdentityGrpcService service = - new TenantIdentityGrpcService(repository, associationRepository, "test"); + new TenantIdentityGrpcService( + repository, + associationRepository, + publishedReleaseBundleService, + "test", + new ObjectMapper()); @Test void resolvesExactOwnerIdentityForAuthenticatedGameSessionPeer() { @@ -83,7 +100,12 @@ void rejectsUnauthenticatedWrongNamespaceAndWrongServiceBeforeOwnerRead() { @Test void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { TenantIdentityGrpcService inactiveService = - new TenantIdentityGrpcService(repository, associationRepository, ""); + new TenantIdentityGrpcService( + repository, + associationRepository, + publishedReleaseBundleService, + "", + new ObjectMapper()); TestObserver observer = new TestObserver(); GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); @@ -160,6 +182,222 @@ void mapsUnavailableOwnerReadWithoutReturningPartialEvidence() { assertThat(observer.completed).isFalse(); } + @Test + void resolvesPublishedPolicyForExactSameNamespaceGameSessionPeer() { + RealmEntryPolicy policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Realm\"," + + "\"visible\":true,\"publicProduction\":false,\"stateScope\":\"ISOLATED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new ObjectMapper()); + var evidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("22222222-2222-4222-8222-222222222222"), + TENANT_ID, + "NEW_GAME_ROW", + 42L, + "source-game-key", + 7L, + 3, + 18L, + "sha256:" + "1".repeat(64), + "publish-workflow-3", + "manifest-3", + policy, + new ObjectMapper()); + when(publishedReleaseBundleService.resolvePublishedRealmEntryPolicy( + TENANT_ID, 7L, "earth", "main")) + .thenReturn(evidence); + + PolicyObserver observer = + callPolicy(policyRequest(TENANT_ID.toString(), 7L, "earth", "main"), GAME_SESSION_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getSchemaVersion()).isEqualTo(1); + assertThat(observer.value.getTargetNamespace()).isEqualTo("test"); + assertThat(observer.value.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(observer.value.getVersionId()).isEqualTo(7L); + assertThat(observer.value.getVersionNumber()).isEqualTo(3); + assertThat(observer.value.getPolicyId()).isEqualTo(evidence.policyId().toString()); + assertThat(observer.value.getSourceRevisionId()).isEqualTo(18L); + assertThat(observer.value.getSourceGameRowId()).isEqualTo(42L); + assertThat(observer.value.getSourceGameTenantKey()).isEqualTo("source-game-key"); + assertThat(observer.value.getReleaseBundleIdentity()) + .isEqualTo(evidence.releaseBundleIdentity()); + assertThat(observer.value.getWorldSlug()).isEqualTo("earth"); + assertThat(observer.value.getRealmSlug()).isEqualTo("main"); + assertThat(observer.value.getVisible()).isTrue(); + assertThat(observer.value.getPublicProduction()).isFalse(); + assertThat(observer.value.getPolicyDigest()).isEqualTo(evidence.policyDigest()); + verify(publishedReleaseBundleService) + .resolvePublishedRealmEntryPolicy(TENANT_ID, 7L, "earth", "main"); + } + + @Test + void publishedPolicyReadRejectsWrongPeerAndOpenOrMalformedSelectorsBeforeOwnerRead() { + assertThat( + status( + callPolicy( + policyRequest(TENANT_ID.toString(), 7L, "earth", "main"), + "spiffe://firemud/ns/other/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callPolicy( + policyRequest(TENANT_ID.toString(), 7L, "earth", "main"), + "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callPolicy( + policyRequest(TENANT_ID.toString().toUpperCase(), 7L, "earth", "main"), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + callPolicy( + policyRequest(TENANT_ID.toString(), 7L, "Earth", "main"), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + ResolvePublishedRealmEntryPolicyRequest unknownFieldRequest = + policyRequest(TENANT_ID.toString(), 7L, "earth", "main").toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(status(callPolicy(unknownFieldRequest, GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + org.mockito.Mockito.verifyNoInteractions(publishedReleaseBundleService); + } + + @Test + void publishedPolicyReadMapsMissingAndUnavailableEvidenceWithoutPartialResponse() { + when(publishedReleaseBundleService.resolvePublishedRealmEntryPolicy( + TENANT_ID, 7L, "earth", "main")) + .thenThrow(new PublishedRealmEntryPolicyNotFoundException()); + PolicyObserver missing = + callPolicy(policyRequest(TENANT_ID.toString(), 7L, "earth", "main"), GAME_SESSION_URI); + assertThat(status(missing)).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.value).isNull(); + + doThrow(new DataAccessResourceFailureException("unavailable")) + .when(publishedReleaseBundleService) + .resolvePublishedRealmEntryPolicy(TENANT_ID, 7L, "earth", "main"); + PolicyObserver unavailable = + callPolicy(policyRequest(TENANT_ID.toString(), 7L, "earth", "main"), GAME_SESSION_URI); + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.value).isNull(); + } + + @Test + void resolvesCompletePublishedPolicySetWithOwnerBoundCountAndDigest() { + ObjectMapper mapper = new ObjectMapper(); + RealmEntryPolicy policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Realm\"," + + "\"visible\":true,\"publicProduction\":true,\"stateScope\":\"ISOLATED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + mapper); + var row = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("22222222-2222-4222-8222-222222222222"), + TENANT_ID, + "NEW_GAME_ROW", + 42L, + "source-game-key", + 7L, + 3, + 18L, + "sha256:" + "1".repeat(64), + "publish-workflow-3", + "manifest-3", + policy, + mapper); + var set = + PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, + 7L, + 3, + row.releaseBundleIdentity(), + "publish-workflow-3", + "manifest-3", + java.util.List.of(row), + mapper); + when(publishedReleaseBundleService.listPublishedRealmEntryPolicies(TENANT_ID, 7L)) + .thenReturn(set); + + PolicySetObserver observer = + callPolicySet(policySetRequest(TENANT_ID.toString(), 7L), GAME_SESSION_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getSchemaVersion()).isEqualTo(1); + assertThat(observer.value.getTargetNamespace()).isEqualTo("test"); + assertThat(observer.value.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(observer.value.getVersionId()).isEqualTo(7L); + assertThat(observer.value.getVersionNumber()).isEqualTo(3); + assertThat(observer.value.getPolicyCount()).isEqualTo(1); + assertThat(observer.value.getPoliciesCount()).isEqualTo(1); + assertThat(observer.value.getPolicySetDigest()).isEqualTo(set.policySetDigest()); + assertThat(observer.value.getPolicies(0).getPolicyDigest()).isEqualTo(row.policyDigest()); + assertThat(observer.value.getPolicies(0).getPolicyJson()).isEqualTo(policy.canonicalJson()); + verify(publishedReleaseBundleService).listPublishedRealmEntryPolicies(TENANT_ID, 7L); + } + + @Test + void completePolicySetReadRejectsWrongPeerAndOpenRequestsBeforeOwnerRead() { + assertThat( + status( + callPolicySet( + policySetRequest(TENANT_ID.toString(), 7L), + "spiffe://firemud/ns/other/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callPolicySet( + policySetRequest(TENANT_ID.toString(), 7L), + "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callPolicySet( + policySetRequest(TENANT_ID.toString().toUpperCase(), 7L), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(callPolicySet(policySetRequest(TENANT_ID.toString(), 0L), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + ListPublishedRealmEntryPoliciesRequest unknownFieldRequest = + policySetRequest(TENANT_ID.toString(), 7L).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(status(callPolicySet(unknownFieldRequest, GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(publishedReleaseBundleService); + } + + @Test + void completePolicySetReadMapsMissingAndUnavailableWithoutPartialResponse() { + when(publishedReleaseBundleService.listPublishedRealmEntryPolicies(TENANT_ID, 7L)) + .thenThrow(new PublishedRealmEntryPolicyNotFoundException()); + PolicySetObserver missing = + callPolicySet(policySetRequest(TENANT_ID.toString(), 7L), GAME_SESSION_URI); + assertThat(status(missing)).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.value).isNull(); + + doThrow(new DataAccessResourceFailureException("unavailable")) + .when(publishedReleaseBundleService) + .listPublishedRealmEntryPolicies(TENANT_ID, 7L); + PolicySetObserver unavailable = + callPolicySet(policySetRequest(TENANT_ID.toString(), 7L), GAME_SESSION_URI); + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.value).isNull(); + } + private static ResolveRuntimeTenantIdentityRequest request(String tenantId, String requestId) { return ResolveRuntimeTenantIdentityRequest.newBuilder() .setCanonicalTenantId(tenantId) @@ -179,12 +417,68 @@ private TestObserver call(ResolveRuntimeTenantIdentityRequest request, String pe return observer; } + private PolicyObserver callPolicy( + ResolvePublishedRealmEntryPolicyRequest request, String peerUri) { + PolicyObserver observer = new PolicyObserver(); + Runnable invocation = () -> service.resolvePublishedRealmEntryPolicy(request, observer); + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private PolicySetObserver callPolicySet( + ListPublishedRealmEntryPoliciesRequest request, String peerUri) { + PolicySetObserver observer = new PolicySetObserver(); + Runnable invocation = () -> service.listPublishedRealmEntryPolicies(request, observer); + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private static ResolvePublishedRealmEntryPolicyRequest policyRequest( + String tenantId, long versionId, String worldSlug, String realmSlug) { + return ResolvePublishedRealmEntryPolicyRequest.newBuilder() + .setCanonicalTenantId(tenantId) + .setVersionId(versionId) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .build(); + } + + private static ListPublishedRealmEntryPoliciesRequest policySetRequest( + String tenantId, long versionId) { + return ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setCanonicalTenantId(tenantId) + .setVersionId(versionId) + .build(); + } + private static Status.Code status(TestObserver observer) { assertThat(observer.grpcFailure).isTrue(); assertThat(observer.failure).isNotNull(); return observer.failure; } + private static Status.Code status(PolicyObserver observer) { + assertThat(observer.grpcFailure).isTrue(); + assertThat(observer.failure).isNotNull(); + return observer.failure; + } + + private static Status.Code status(PolicySetObserver observer) { + assertThat(observer.grpcFailure).isTrue(); + assertThat(observer.failure).isNotNull(); + return observer.failure; + } + private static final class TestObserver implements StreamObserver { private ResolveRuntimeTenantIdentityResponse value; @@ -208,4 +502,52 @@ public void onCompleted() { completed = true; } } + + private static final class PolicyObserver + implements StreamObserver { + private ResolvePublishedRealmEntryPolicyResponse value; + private Status.Code failure; + private boolean grpcFailure; + private boolean completed; + + @Override + public void onNext(ResolvePublishedRealmEntryPolicyResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + grpcFailure = throwable instanceof StatusRuntimeException; + failure = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class PolicySetObserver + implements StreamObserver { + private ListPublishedRealmEntryPoliciesResponse value; + private Status.Code failure; + private boolean grpcFailure; + private boolean completed; + + @Override + public void onNext(ListPublishedRealmEntryPoliciesResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + grpcFailure = throwable instanceof StatusRuntimeException; + failure = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } } From 7a9884811f9a4e6baf5d90736fd3728a903bcbd2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:57:34 +1300 Subject: [PATCH 062/105] Document immutable mapper injection for Game Design owner reads --- .../gamedesign/service/impl/TenantIdentityGrpcService.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index 1697204559..416dd454f2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.sql.SQLException; @@ -36,6 +37,9 @@ /** Authenticated read of Game Design's own retained tenant identity provenance. */ @GrpcService +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected Jackson 3 ObjectMapper is an immutable configured collaborator.") public class TenantIdentityGrpcService extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { private final GameRepository gameRepository; From 93b837abbfb6fd4131d5b3cbf9bc18559411767a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:02:52 +1300 Subject: [PATCH 063/105] Tighten Account identity wire and failed-login session cleanup --- .../account-service/api-contracts.md | 4 +- .../v1/runtime_account_identity_service.proto | 3 +- .../RuntimeAccountIdentityGrpcService.java | 1 - ...RuntimeAccountIdentityGrpcServiceTest.java | 1 - .../RuntimeAccountIdentityEvidence.java | 10 +- .../RuntimeAccountIdentityEvidenceTest.java | 46 +---- .../client/AccountRuntimeIdentityClient.java | 3 +- .../AccountRuntimeIdentityClientTest.java | 4 - .../command/text/LoginCommandHandler.java | 45 +++++ .../command/text/LoginCommandHandlerTest.java | 189 +++++++++++++++++- 10 files changed, 251 insertions(+), 55 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 87018849ab..a5e5de1f81 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -116,7 +116,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – exact Game Session workload-only membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. `accountId` is the canonical non-nil Account UUID on the wire; Account alone resolves it through its provenance-checked UUID-to-private-row resolver, verifies the returned private membership DTO still identifies that resolved Account row and requested tenant, and echoes the requested canonical UUID. `tenantId` remains a positive numeric tenant identifier, and `requestId` is forwarded unchanged. The proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. -- `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, UUID provenance, and persisted source numeric row identity. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. +- `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. @@ -138,7 +138,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu The only permitted peers are verified Game Session and Entity Management workload identities in the exact configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. The RPC is exempted by its exact full method name from bearer-token validation because it is workload-only; the listener remains mTLS-only, and the handler verifies the exact peer service and namespace. JWT claims and request metadata do not establish workload identity. -The request contains exactly `canonical_account_id` and `request_id`; both must be canonical, lower-case, nonnil UUID strings, and unknown fields or invalid/missing values are rejected. The schema-version-1 response contains the configured `target_namespace`, exact echoed `request_id` and `canonical_account_id`, `source_account_row_id`, `account_uuid_provenance`, and `source_numeric_row_id`. Both source-row fields and the provenance value must come from the same persisted Account row whose UUID exactly matches the request selector. Numeric row values are provenance only and must not be used as gameplay identity. Account returns no partial evidence when persisted UUID/provenance/source-row evidence is missing, ambiguous, malformed, or inconsistent. +The request contains exactly `canonical_account_id` and `request_id`; both must be canonical, lower-case, nonnil UUID strings, and unknown fields or invalid/missing values are rejected. The schema-version-1 response contains the configured `target_namespace`, exact echoed `request_id` and `canonical_account_id`, `source_account_row_id`, and `account_uuid_provenance`. The returned source row and provenance must come from the same persisted Account row whose UUID exactly matches the request selector. The numeric row value is provenance only and must not be used as gameplay identity. Account independently verifies that its persisted `account_uuid_source_numeric_id` equals that row's `id` before returning evidence. Account returns no partial evidence when persisted UUID/provenance/source-row evidence is missing, ambiguous, malformed, or inconsistent. This read is not an authentication, membership, entitlement, realm-grant, actor-owner, playable-state namespace, or admission decision. It creates no membership or grant and does not select or activate an actor. Game Session and Entity Management retain their respective runtime composition and admission contracts. diff --git a/protos/account/v1/runtime_account_identity_service.proto b/protos/account/v1/runtime_account_identity_service.proto index 4441a9e463..4a07b9bf3a 100644 --- a/protos/account/v1/runtime_account_identity_service.proto +++ b/protos/account/v1/runtime_account_identity_service.proto @@ -24,5 +24,6 @@ message ResolveRuntimeAccountIdentityResponse { // Private Account provenance evidence; never use this row key as gameplay identity. int64 source_account_row_id = 5; string account_uuid_provenance = 6; - int64 source_numeric_row_id = 7; + reserved 7; + reserved "source_numeric_row_id"; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java index a1de67ba58..6607f43f82 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java @@ -125,7 +125,6 @@ public void resolveRuntimeAccountIdentity( .setCanonicalAccountId(canonicalAccountId.toString()) .setSourceAccountRowId(account.getId()) .setAccountUuidProvenance(account.getAccountUuidProvenance().name()) - .setSourceNumericRowId(account.getAccountUuidSourceNumericId()) .build()); responseObserver.onCompleted(); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java index 19f76ace6c..2cad980ed2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java @@ -54,7 +54,6 @@ void resolvesExactPersistedIdentityForEachAllowedRuntimePeer(String peerUri) { assertThat(observer.value.getCanonicalAccountId()).isEqualTo(ACCOUNT_ID.toString()); assertThat(observer.value.getSourceAccountRowId()).isEqualTo(42L); assertThat(observer.value.getAccountUuidProvenance()).isEqualTo("ACCOUNT_V29_MIGRATION"); - assertThat(observer.value.getSourceNumericRowId()).isEqualTo(42L); verify(repository).findByAccountUuid(ACCOUNT_ID); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java index 575d73484a..981380c587 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java @@ -15,8 +15,7 @@ public record RuntimeAccountIdentityEvidence( UUID requestId, UUID canonicalAccountId, long sourceAccountRowId, - String accountUuidProvenance, - long sourceNumericRowId) { + String accountUuidProvenance) { private static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -29,11 +28,8 @@ public record RuntimeAccountIdentityEvidence( } requireNonNil(requestId, "requestId"); requireNonNil(canonicalAccountId, "canonicalAccountId"); - if (sourceAccountRowId <= 0L || sourceNumericRowId <= 0L) { - throw new IllegalArgumentException("Account source row identities must be positive"); - } - if (sourceAccountRowId != sourceNumericRowId) { - throw new IllegalArgumentException("Account source row identities must match exactly"); + if (sourceAccountRowId <= 0L) { + throw new IllegalArgumentException("Account source row identity must be positive"); } if (!isRecognizedProvenance(accountUuidProvenance)) { throw new IllegalArgumentException("Account UUID provenance is not recognized"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java index b2373a0f38..aab060d32a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java @@ -28,77 +28,53 @@ void rejectsUnsupportedSchemaNamespaceIdentitySourceRowAndProvenance() { valid.requestId(), valid.canonicalAccountId(), valid.sourceAccountRowId(), - valid.accountUuidProvenance(), - valid.sourceNumericRowId()); + valid.accountUuidProvenance()); assertInvalid( 1, "test.invalid", valid.requestId(), valid.canonicalAccountId(), valid.sourceAccountRowId(), - valid.accountUuidProvenance(), - valid.sourceNumericRowId()); + valid.accountUuidProvenance()); assertInvalid( 1, valid.targetNamespace(), new UUID(0L, 0L), valid.canonicalAccountId(), valid.sourceAccountRowId(), - valid.accountUuidProvenance(), - valid.sourceNumericRowId()); + valid.accountUuidProvenance()); assertInvalid( 1, valid.targetNamespace(), valid.requestId(), new UUID(0L, 0L), valid.sourceAccountRowId(), - valid.accountUuidProvenance(), - valid.sourceNumericRowId()); + valid.accountUuidProvenance()); assertInvalid( 1, valid.targetNamespace(), valid.requestId(), valid.canonicalAccountId(), 0L, - valid.accountUuidProvenance(), - valid.sourceNumericRowId()); + valid.accountUuidProvenance()); assertInvalid( 1, valid.targetNamespace(), valid.requestId(), valid.canonicalAccountId(), valid.sourceAccountRowId(), - valid.accountUuidProvenance(), - 0L); + null); assertInvalid( 1, valid.targetNamespace(), valid.requestId(), valid.canonicalAccountId(), valid.sourceAccountRowId(), - valid.accountUuidProvenance(), - valid.sourceNumericRowId() + 1L); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalAccountId(), - valid.sourceAccountRowId(), - null, - valid.sourceNumericRowId()); - assertInvalid( - 1, - valid.targetNamespace(), - valid.requestId(), - valid.canonicalAccountId(), - valid.sourceAccountRowId(), - "UNKNOWN", - valid.sourceNumericRowId()); + "UNKNOWN"); } private static RuntimeAccountIdentityEvidence evidence(String provenance) { - return new RuntimeAccountIdentityEvidence( - 1, "test", REQUEST_ID, ACCOUNT_ID, 73L, provenance, 73L); + return new RuntimeAccountIdentityEvidence(1, "test", REQUEST_ID, ACCOUNT_ID, 73L, provenance); } private static void assertInvalid( @@ -107,8 +83,7 @@ private static void assertInvalid( UUID requestId, UUID canonicalAccountId, long sourceAccountRowId, - String provenance, - long sourceNumericRowId) { + String provenance) { assertThatThrownBy( () -> new RuntimeAccountIdentityEvidence( @@ -117,8 +92,7 @@ private static void assertInvalid( requestId, canonicalAccountId, sourceAccountRowId, - provenance, - sourceNumericRowId)) + provenance)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java index 7fe4b89ca7..f9d54c2164 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java @@ -103,8 +103,7 @@ public RuntimeAccountIdentityEvidence resolveRuntimeAccountIdentity( parseCanonicalNonNilUuid( response.getCanonicalAccountId(), "response canonical account ID"), response.getSourceAccountRowId(), - response.getAccountUuidProvenance(), - response.getSourceNumericRowId()); + response.getAccountUuidProvenance()); } catch (IllegalArgumentException exception) { throw new IllegalStateException("Account runtime identity response is invalid", exception); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java index b98b2fe449..ea92185812 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java @@ -54,7 +54,6 @@ void forwardsExactCanonicalRequestAndReturnsTypedOwnerEvidence() throws Exceptio assertThat(evidence.requestId()).isEqualTo(REQUEST_ID); assertThat(evidence.canonicalAccountId()).isEqualTo(ACCOUNT_ID); assertThat(evidence.sourceAccountRowId()).isEqualTo(SOURCE_ROW_ID); - assertThat(evidence.sourceNumericRowId()).isEqualTo(SOURCE_ROW_ID); assertThat(evidence.accountUuidProvenance()).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); ArgumentCaptor requestCaptor = @@ -126,8 +125,6 @@ void rejectsSchemaMismatchAndEveryResponseFieldOutsideTheExactRequest() throws E assertRejected(valid.toBuilder().setRequestId("22222222-2222-4222-8222-22222222222").build()); assertRejected(valid.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build()); assertRejected(valid.toBuilder().setSourceAccountRowId(0L).build()); - assertRejected(valid.toBuilder().setSourceNumericRowId(0L).build()); - assertRejected(valid.toBuilder().setSourceNumericRowId(SOURCE_ROW_ID + 1L).build()); assertRejected(valid.toBuilder().setAccountUuidProvenance("").build()); assertRejected(valid.toBuilder().setAccountUuidProvenance("UNKNOWN").build()); assertRejected( @@ -286,7 +283,6 @@ private static ResolveRuntimeAccountIdentityResponse validResponse(String proven .setCanonicalAccountId(ACCOUNT_ID.toString()) .setSourceAccountRowId(SOURCE_ROW_ID) .setAccountUuidProvenance(provenance) - .setSourceNumericRowId(SOURCE_ROW_ID) .build(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index fd209a04d7..514e90ad7c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -174,10 +174,37 @@ private boolean invalidateStaleFirstPartyConnectContext(long sessionId, String a .ifPresent(ignored -> firstPartyConnectContextRegistry.unregister(sessionId)); return true; } catch (SerializationException | ClassCastException ex) { + neutralizeKnownProjectedSessionAfterUnreadableConnectContext(sessionId, accountId); return false; } } + private void neutralizeKnownProjectedSessionAfterUnreadableConnectContext( + long sessionId, String authenticatedAccountId) { + SessionContext projectedExisting; + try { + projectedExisting = + sessionRoutingNormalizationService + .resolveProjectedSessionContext(Long.toString(sessionId)) + .orElse(null); + } catch (SerializationException | ClassCastException ex) { + return; + } + if (projectedExisting == null + || !AccountIds.isCanonicalNonNilUuid(projectedExisting.accountId()) + || Objects.equals(projectedExisting.accountId(), authenticatedAccountId)) { + return; + } + clearFailedLoginSessionState( + sessionId, + projectedExisting.tenantId(), + projectedExisting.bootstrapGameInstanceId(), + projectedExisting.worldSlug(), + projectedExisting.realmSlug(), + projectedExisting.pointerVersion(), + projectedExisting); + } + private LoginCommandHandlingResult handleEmailLoginChallenge( String sessionId, TextCommandPayload.EmailLoginChallengeRequest challengeRequest) { SessionIdParsing.ParsedSessionId parsedSessionId = parseSessionId(sessionId); @@ -574,6 +601,24 @@ private void clearFailedLoginSessionState( sessionAuthenticationService .resolveUnverifiedSessionContext(Long.toString(sessionId)) .orElse(null); + clearFailedLoginSessionState( + sessionId, + fallbackTenantId, + fallbackBootstrapGameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + projectedExisting); + } + + private void clearFailedLoginSessionState( + long sessionId, + long fallbackTenantId, + long fallbackBootstrapGameInstanceId, + String worldSlug, + String realmSlug, + long pointerVersion, + SessionContext projectedExisting) { long tenantId = projectedExisting != null ? projectedExisting.tenantId() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index 517fcf43a8..8aed26b6f6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -672,6 +672,26 @@ void credentialLoginFailsClosedWhenFirstPartyContextIsUnreadable() { List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + SessionContext priorAccount = + new SessionContext( + 1L, + 22L, + OTHER_ACCOUNT_UUID, + "old@example.com", + 88L, + "Sora", + 1L, + "R-2045", + "old-jwt", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "scope-old", + "req-old"); + stubSessionContext(priorAccount); when(firstPartyConnectContextRegistry.find(1L)) .thenThrow(new SerializationException("retained connect context is unreadable")); @@ -679,7 +699,14 @@ void credentialLoginFailsClosedWhenFirstPartyContextIsUnreadable() { assertFalse(result.commandResult().accepted()); assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - verify(sessionContextService, never()).save(any(SessionContext.class)); + ArgumentCaptor cleared = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(cleared.capture()); + assertNull(cleared.getValue().accountId()); + assertEquals(0L, cleared.getValue().characterId()); + assertEquals(0L, cleared.getValue().gameInstanceId()); + assertEquals("scope-old", cleared.getValue().connectScopeId()); + assertEquals("req-old", cleared.getValue().connectRequestId()); + verify(gameplayPresenceLifecycleService).clearGameplayBinding(priorAccount, "LOGIN_FAILED"); verify(firstPartyConnectContextRegistry, never()).unregister(1L); } @@ -691,14 +718,174 @@ void credentialLoginFailsClosedWhenFirstPartyContextHasWrongType() { List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + SessionContext priorAccount = + new SessionContext( + 1L, + 22L, + OTHER_ACCOUNT_UUID, + "old@example.com", + 88L, + "Sora", + 1L, + "R-2045", + "old-jwt", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "scope-old", + "req-old"); + stubSessionContext(priorAccount); when(firstPartyConnectContextRegistry.find(1L)) .thenThrow(new ClassCastException("retained connect context has the wrong type")); LoginCommandHandlingResult result = handler.handle("1", credentialLogin, false); + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + ArgumentCaptor cleared = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(cleared.capture()); + assertNull(cleared.getValue().accountId()); + assertEquals(0L, cleared.getValue().characterId()); + assertEquals(0L, cleared.getValue().gameInstanceId()); + assertEquals("scope-old", cleared.getValue().connectScopeId()); + assertEquals("req-old", cleared.getValue().connectRequestId()); + verify(gameplayPresenceLifecycleService).clearGameplayBinding(priorAccount, "LOGIN_FAILED"); + verify(firstPartyConnectContextRegistry, never()).unregister(1L); + } + + @Test + void unreadableFirstPartyContextDoesNotReplaceUnknownLegacyProjectedIdentity() { + TextCommand credentialLogin = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + stubSessionContext( + new SessionContext( + 1L, 22L, "legacy-account-key", "old@example.com", 0L, null, 0L, null, null, 1L)); + when(firstPartyConnectContextRegistry.find(1L)) + .thenThrow(new SerializationException("retained connect context is unreadable")); + + LoginCommandHandlingResult result = handler.handle("1", credentialLogin, false); + assertFalse(result.commandResult().accepted()); assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(gameplayPresenceLifecycleService, never()).clearGameplayBinding(any(), anyString()); + verify(firstPartyConnectContextRegistry, never()).unregister(1L); + } + + @Test + void unreadableFirstPartyContextDoesNotCreateSessionStateWhenProjectionIsAbsent() { + TextCommand credentialLogin = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + SessionContext bootstrap = bootstrapShell(1L, 1L); + when(sessionContextService.findBySessionId(1L)) + .thenReturn(Optional.of(bootstrap)) + .thenReturn(Optional.empty()); + when(sessionContextService.findByTenantAndSessionId(bootstrap.tenantId(), 1L)) + .thenReturn(Optional.of(bootstrap)); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + when(firstPartyConnectContextRegistry.find(1L)) + .thenThrow(new SerializationException("retained connect context is unreadable")); + + LoginCommandHandlingResult result = handler.handle("1", credentialLogin, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(gameplayPresenceLifecycleService, never()).clearGameplayBinding(any(), anyString()); + verify(firstPartyConnectContextRegistry, never()).unregister(1L); + } + + @Test + void unreadableFirstPartyContextDoesNotReplaceUnreadableProjectedSession() { + TextCommand credentialLogin = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + SessionContext priorAccount = + new SessionContext( + 1L, + 22L, + OTHER_ACCOUNT_UUID, + "old@example.com", + 88L, + "Sora", + 1L, + "R-2045", + "old-jwt", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "scope-old", + "req-old"); + when(sessionContextService.findBySessionId(1L)) + .thenReturn(Optional.of(priorAccount)) + .thenThrow(new SerializationException("projected session is unreadable")); + when(sessionContextService.findByTenantAndSessionId(priorAccount.tenantId(), 1L)) + .thenReturn(Optional.of(priorAccount)); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + when(firstPartyConnectContextRegistry.find(1L)) + .thenThrow(new SerializationException("retained connect context is unreadable")); + + LoginCommandHandlingResult result = handler.handle("1", credentialLogin, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(gameplayPresenceLifecycleService, never()).clearGameplayBinding(any(), anyString()); + verify(firstPartyConnectContextRegistry, never()).unregister(1L); + } + + @Test + void unreadableFirstPartyContextPreservesProjectedSessionForSameAccount() { + TextCommand credentialLogin = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + SessionContext sameAccount = + new SessionContext( + 1L, + 22L, + ACCOUNT_UUID, + "demo@example.com", + 88L, + "Sora", + 1L, + "R-2045", + "old-jwt", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "scope-old", + "req-old"); + stubSessionContext(sameAccount); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + when(firstPartyConnectContextRegistry.find(1L)) + .thenThrow(new SerializationException("retained connect context is unreadable")); + + LoginCommandHandlingResult result = handler.handle("1", credentialLogin, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(gameplayPresenceLifecycleService, never()).clearGameplayBinding(any(), anyString()); verify(firstPartyConnectContextRegistry, never()).unregister(1L); } From b5de67cf939b7e9ea50a6b3c1cb4e79c930d30af Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:04:06 +1300 Subject: [PATCH 064/105] Verify complete published realm policies at Game Session receiver --- .../GameDesignPublishedRealmPolicyClient.java | 305 +++++++++++++ ...eDesignPublishedRealmPolicyClientTest.java | 429 ++++++++++++++++++ 2 files changed, 734 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java 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..0d06000d28 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java @@ -0,0 +1,305 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +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.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyKind; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryStateScope; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import tools.jackson.databind.ObjectMapper; + +/** Unwired Game Session receiver for complete immutable Game Design realm-policy sets. */ +public final class GameDesignPublishedRealmPolicyClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + 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 TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + return TenantIdentityServiceGrpc.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( + String canonicalTenantId, long versionId) { + UUID requestedTenantId = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); + if (versionId <= 0) { + throw new IllegalArgumentException("Published version ID must be positive"); + } + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Design published realm policy client is not initialized"); + } + + ListPublishedRealmEntryPoliciesResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .listPublishedRealmEntryPolicies( + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setCanonicalTenantId(requestedTenantId.toString()) + .setVersionId(versionId) + .build()); + if (response == null) { + throw invalidResponse("is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("contains unsupported fields"); + } + if (response.getSchemaVersion() != RealmEntryPolicy.SCHEMA_VERSION + || !workloadNamespace.equals(response.getTargetNamespace()) + || !requestedTenantId.toString().equals(response.getCanonicalTenantId()) + || response.getVersionId() != versionId + || response.getVersionNumber() <= 0) { + throw invalidResponse("does not match the exact schema, owner namespace, tenant, or version"); + } + String expectedReleaseBundleIdentity; + try { + expectedReleaseBundleIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + requestedTenantId, + versionId, + response.getPublishWorkflowId(), + response.getManifestHash(), + OBJECT_MAPPER); + } catch (IllegalArgumentException exception) { + throw invalidResponse("has incomplete release-bundle workflow or manifest identity"); + } + if (!expectedReleaseBundleIdentity.equals(response.getReleaseBundleIdentity())) { + throw invalidResponse("release-bundle identity does not match its owner evidence"); + } + + int policyCount = response.getPolicyCount(); + if (policyCount <= 0 + || policyCount > PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + || response.getPoliciesCount() != policyCount) { + throw invalidResponse("does not contain the declared complete bounded policy set"); + } + + List policies = new ArrayList<>(policyCount); + String previousWorldSlug = null; + String previousRealmSlug = null; + for (ResolvePublishedRealmEntryPolicyResponse child : response.getPoliciesList()) { + if (!child.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("contains a policy with unsupported fields"); + } + PublishedRealmEntryPolicyEvidence evidence = toEvidence(child, response, requestedTenantId); + String worldSlug = evidence.policy().worldSlug(); + String realmSlug = evidence.policy().realmSlug(); + if (previousWorldSlug != null + && (previousWorldSlug.compareTo(worldSlug) > 0 + || (previousWorldSlug.equals(worldSlug) + && previousRealmSlug.compareTo(realmSlug) >= 0))) { + throw invalidResponse("policy selectors are not in canonical unique order"); + } + previousWorldSlug = worldSlug; + previousRealmSlug = realmSlug; + policies.add(evidence); + } + + try { + PublishedRealmEntryPolicySetEvidence setEvidence = + PublishedRealmEntryPolicySetEvidence.create( + requestedTenantId, + versionId, + response.getVersionNumber(), + response.getReleaseBundleIdentity(), + response.getPublishWorkflowId(), + response.getManifestHash(), + policies, + OBJECT_MAPPER); + if (!setEvidence.policySetDigest().equals(response.getPolicySetDigest())) { + throw invalidResponse("policy-set digest does not match the complete owner evidence"); + } + return setEvidence.requireValidDigest(OBJECT_MAPPER); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design published realm policy response is invalid", exception); + } + } + + private PublishedRealmEntryPolicyEvidence toEvidence( + ResolvePublishedRealmEntryPolicyResponse child, + ListPublishedRealmEntryPoliciesResponse response, + UUID requestedTenantId) { + if (child.getSchemaVersion() != RealmEntryPolicy.SCHEMA_VERSION + || !workloadNamespace.equals(child.getTargetNamespace()) + || !requestedTenantId.toString().equals(child.getCanonicalTenantId()) + || child.getVersionId() != response.getVersionId() + || child.getVersionNumber() != response.getVersionNumber() + || !response.getReleaseBundleIdentity().equals(child.getReleaseBundleIdentity()) + || !response.getPublishWorkflowId().equals(child.getPublishWorkflowId()) + || !response.getManifestHash().equals(child.getManifestHash()) + || child.getSourceRevisionId() <= 0 + || child.getSourceGameRowId() <= 0) { + throw invalidResponse("contains a policy with contradictory owner or version evidence"); + } + + PublishedRealmEntryStateScope wireStateScope = + PublishedRealmEntryStateScope.forNumber(child.getStateScopeValue()); + RealmEntryPolicy.StateScope stateScope = + switch (wireStateScope == null + ? PublishedRealmEntryStateScope.UNRECOGNIZED + : wireStateScope) { + case PUBLISHED_REALM_ENTRY_STATE_SCOPE_SHARED -> RealmEntryPolicy.StateScope.SHARED; + case PUBLISHED_REALM_ENTRY_STATE_SCOPE_ISOLATED -> RealmEntryPolicy.StateScope.ISOLATED; + default -> throw invalidResponse("contains an unsupported state-scope enum"); + }; + PublishedRealmEntryPolicyKind wireEntryPolicy = + PublishedRealmEntryPolicyKind.forNumber(child.getEntryPolicyValue()); + if (wireEntryPolicy + != PublishedRealmEntryPolicyKind.PUBLISHED_REALM_ENTRY_POLICY_KIND_PRESEEDED_ONLY) { + throw invalidResponse("contains an unsupported entry-policy enum"); + } + + RealmEntryPolicy policy; + try { + policy = RealmEntryPolicy.parseCanonical(child.getPolicyJson(), OBJECT_MAPPER); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design published realm policy response contains invalid canonical policy JSON", + exception); + } + if (!policy.worldSlug().equals(child.getWorldSlug()) + || !policy.worldDisplayName().equals(child.getWorldDisplayName()) + || !policy.realmSlug().equals(child.getRealmSlug()) + || !policy.realmDisplayName().equals(child.getRealmDisplayName()) + || policy.visible() != child.getVisible() + || policy.publicProduction() != child.getPublicProduction() + || policy.stateScope() != stateScope + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY) { + throw invalidResponse("contains selector or enum fields that contradict its policy JSON"); + } + + PublishedRealmEntryPolicyEvidence evidence; + try { + evidence = + PublishedRealmEntryPolicyEvidence.create( + parseCanonicalNonNilUuid(child.getPolicyId(), "policy ID"), + requestedTenantId, + child.getTenantIdentityProvenanceKind(), + child.getSourceGameRowId(), + child.getSourceGameTenantKey(), + response.getVersionId(), + response.getVersionNumber(), + child.getSourceRevisionId(), + response.getReleaseBundleIdentity(), + response.getPublishWorkflowId(), + response.getManifestHash(), + policy, + OBJECT_MAPPER); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design published realm policy response contains invalid owner provenance", + exception); + } + if (!evidence.policyDigest().equals(child.getPolicyDigest())) { + throw invalidResponse("policy digest does not match the owner and selector evidence"); + } + return evidence.requireValidDigest(OBJECT_MAPPER); + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static IllegalStateException invalidResponse(String detail) { + return new IllegalStateException("Game Design published realm policy response " + detail); + } + + 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/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..6ba6ecd77b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -0,0 +1,429 @@ +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.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.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyKind; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryStateScope; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class GameDesignPublishedRealmPolicyClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final long VERSION_ID = 42L; + private static final int VERSION_NUMBER = 7; + private static final long SOURCE_GAME_ROW_ID = 91L; + private static final String SOURCE_GAME_TENANT_KEY = "game-design-tenant-91"; + private static final String WORKFLOW_ID = "publish-42"; + private static final String MANIFEST_HASH = "manifest-hash-42"; + private static final String PROVENANCE_KIND = "NEW_GAME_ROW"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @Test + void returnsCompleteTypedEvidenceAndSendsExactRequestWithDeadline() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + ListPublishedRealmEntryPoliciesResponse response = validResponse(); + when(stub.listPublishedRealmEntryPolicies(any())).thenReturn(response); + GameDesignPublishedRealmPolicyClient client = newClient(stub); + + PublishedRealmEntryPolicySetEvidence result = + client.listPublishedRealmEntryPolicies(TENANT_ID.toString(), VERSION_ID); + + assertThat(result).isEqualTo(validEvidenceSet()); + assertThat(result.policies()).hasSize(2); + assertThat(result.policies().getFirst().policy().realmSlug()).isEqualTo("playtest"); + assertThat(result.hasValidDigest(OBJECT_MAPPER)).isTrue(); + org.mockito.ArgumentCaptor requestCaptor = + org.mockito.ArgumentCaptor.forClass(ListPublishedRealmEntryPoliciesRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).listPublishedRealmEntryPolicies(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(requestCaptor.getValue().getVersionId()).isEqualTo(VERSION_ID); + } + + @Test + void rejectsMalformedTenantOrVersionBeforeStubUse() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignPublishedRealmPolicyClient client = newClientWithoutStub(channelFactory); + + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies("bad", VERSION_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.listPublishedRealmEntryPolicies( + "00000000-0000-0000-0000-000000000000", VERSION_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.listPublishedRealmEntryPolicies( + "11111111-1111-4111-8111-11111111111", VERSION_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(TENANT_ID.toString(), 0L)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsUninitializedClientAndPropagatesUnavailableOwner() throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignPublishedRealmPolicyClient uninitialized = newClientWithoutStub(channelFactory); + assertThatThrownBy( + () -> uninitialized.listPublishedRealmEntryPolicies(TENANT_ID.toString(), VERSION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + Status.UNAVAILABLE.withDescription("Game Design unavailable").asRuntimeException(); + when(stub.listPublishedRealmEntryPolicies(any())).thenThrow(unavailable); + GameDesignPublishedRealmPolicyClient client = newClient(stub); + assertThatThrownBy( + () -> client.listPublishedRealmEntryPolicies(TENANT_ID.toString(), VERSION_ID)) + .isSameAs(unavailable); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsIncompleteOrContradictoryTopLevelOwnerEvidence() throws Exception { + ListPublishedRealmEntryPoliciesResponse valid = validResponse(); + assertRejected(valid.toBuilder().setSchemaVersion(2).build()); + assertRejected(valid.toBuilder().setTargetNamespace("other").build()); + assertRejected(valid.toBuilder().setTargetNamespace("").build()); + assertRejected( + valid.toBuilder().setCanonicalTenantId("22222222-2222-4222-8222-222222222222").build()); + assertRejected(valid.toBuilder().setVersionId(VERSION_ID + 1).build()); + assertRejected(valid.toBuilder().setVersionNumber(0).build()); + assertRejected(valid.toBuilder().setPolicyCount(1).build()); + assertRejected(valid.toBuilder().setPolicySetDigest("sha256:" + "0".repeat(64)).build()); + assertRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + } + + @Test + void rejectsChildSchemaUnknownFieldsEnumsProvenanceSelectorsAndDigests() throws Exception { + ListPublishedRealmEntryPoliciesResponse valid = validResponse(); + ResolvePublishedRealmEntryPolicyResponse child = valid.getPolicies(0); + + assertRejected(replaceFirst(valid, child.toBuilder().setSchemaVersion(2).build())); + assertRejected(replaceFirst(valid, child.toBuilder().setTargetNamespace("other").build())); + assertRejected( + replaceFirst( + valid, + child.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())); + assertRejected(replaceFirst(valid, child.toBuilder().setStateScopeValue(99).build())); + assertRejected(replaceFirst(valid, child.toBuilder().setEntryPolicyValue(99).build())); + assertRejected( + replaceFirst(valid, child.toBuilder().setTenantIdentityProvenanceKind("OTHER").build())); + assertRejected(replaceFirst(valid, child.toBuilder().setWorldSlug("wrong-world").build())); + assertRejected( + replaceFirst(valid, child.toBuilder().setPolicyDigest("sha256:" + "0".repeat(64)).build())); + assertRejected(replaceFirst(valid, child.toBuilder().setSourceRevisionId(0L).build())); + } + + @Test + void rejectsUnsortedDuplicateAndPartialPolicySets() throws Exception { + ListPublishedRealmEntryPoliciesResponse valid = validResponse(); + ResolvePublishedRealmEntryPolicyResponse first = valid.getPolicies(0); + ResolvePublishedRealmEntryPolicyResponse second = valid.getPolicies(1); + + assertRejected( + valid.toBuilder().clearPolicies().addPolicies(second).addPolicies(first).build()); + assertRejected(valid.toBuilder().clearPolicies().addPolicies(first).addPolicies(first).build()); + assertRejected(valid.toBuilder().removePolicies(1).build()); + assertRejected(valid.toBuilder().setPolicyCount(3).build()); + } + + @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); + listener.onMessage(validResponse()); + listener.onClose(Status.OK, new Metadata()); + return null; + }) + .when(call) + .start(any(), any()); + when(channel + . + newCall(any(), any())) + .thenReturn(call); + + GameDesignPublishedRealmPolicyClient client = newClientWithChannel(channel); + assertThatThrownBy( + () -> client.listPublishedRealmEntryPolicies(TENANT_ID.toString(), VERSION_ID)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + } + + @Test + void rejectsPlaintextIncompleteClasspathTlsAndInvalidNamespaceBeforeChannelCreation() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties 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"); + + CommonGrpcClientProperties 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 validEvidenceSet() { + List policies = + List.of( + evidence( + "00000000-0000-4000-8000-000000000002", + 502L, + policy("production", true, true, RealmEntryPolicy.StateScope.SHARED)), + evidence( + "00000000-0000-4000-8000-000000000001", + 501L, + policy("playtest", true, false, RealmEntryPolicy.StateScope.ISOLATED))); + return PublishedRealmEntryPolicySetEvidence.create( + TENANT_ID, + VERSION_ID, + VERSION_NUMBER, + policies.getFirst().releaseBundleIdentity(), + WORKFLOW_ID, + MANIFEST_HASH, + policies, + OBJECT_MAPPER); + } + + private static PublishedRealmEntryPolicyEvidence evidence( + String policyId, long revisionId, RealmEntryPolicy policy) { + return PublishedRealmEntryPolicyEvidence.create( + UUID.fromString(policyId), + TENANT_ID, + PROVENANCE_KIND, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + revisionId, + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + TENANT_ID, VERSION_ID, WORKFLOW_ID, MANIFEST_HASH, OBJECT_MAPPER), + WORKFLOW_ID, + MANIFEST_HASH, + policy, + OBJECT_MAPPER); + } + + private static RealmEntryPolicy policy( + String realmSlug, + boolean visible, + boolean publicProduction, + RealmEntryPolicy.StateScope scope) { + String json = + "{\"entryPolicy\":\"PRESEEDED_ONLY\",\"publicProduction\":" + + publicProduction + + ",\"realmDisplayName\":" + + quote(realmSlug.equals("production") ? "Production" : "Playtest") + + ",\"realmSlug\":" + + quote(realmSlug) + + ",\"schemaVersion\":1,\"stateScope\":" + + quote(scope.name()) + + ",\"visible\":" + + visible + + ",\"worldDisplayName\":\"FireMUD\",\"worldSlug\":\"firemud\"}"; + return RealmEntryPolicy.parse(json, OBJECT_MAPPER); + } + + private static String quote(String value) { + return "\"" + value + "\""; + } + + private static ListPublishedRealmEntryPoliciesResponse validResponse() { + PublishedRealmEntryPolicySetEvidence evidence = validEvidenceSet(); + ListPublishedRealmEntryPoliciesResponse.Builder response = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(TENANT_ID.toString()) + .setVersionId(VERSION_ID) + .setVersionNumber(VERSION_NUMBER) + .setReleaseBundleIdentity(evidence.releaseBundleIdentity()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setManifestHash(evidence.manifestHash()) + .setPolicyCount(evidence.policies().size()) + .setPolicySetDigest(evidence.policySetDigest()); + evidence.policies().stream() + .map(GameDesignPublishedRealmPolicyClientTest::toWire) + .forEach(response::addPolicies); + return response.build(); + } + + private static ResolvePublishedRealmEntryPolicyResponse toWire( + PublishedRealmEntryPolicyEvidence evidence) { + return ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setVersionId(evidence.versionId()) + .setVersionNumber(evidence.versionNumber()) + .setPolicyId(evidence.policyId().toString()) + .setSourceRevisionId(evidence.sourceRevisionId()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setTenantIdentityProvenanceKind(evidence.tenantIdentityProvenanceKind()) + .setReleaseBundleIdentity(evidence.releaseBundleIdentity()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setManifestHash(evidence.manifestHash()) + .setWorldSlug(evidence.policy().worldSlug()) + .setWorldDisplayName(evidence.policy().worldDisplayName()) + .setRealmSlug(evidence.policy().realmSlug()) + .setRealmDisplayName(evidence.policy().realmDisplayName()) + .setVisible(evidence.policy().visible()) + .setPublicProduction(evidence.policy().publicProduction()) + .setStateScope( + evidence.policy().stateScope() == RealmEntryPolicy.StateScope.SHARED + ? PublishedRealmEntryStateScope.PUBLISHED_REALM_ENTRY_STATE_SCOPE_SHARED + : PublishedRealmEntryStateScope.PUBLISHED_REALM_ENTRY_STATE_SCOPE_ISOLATED) + .setEntryPolicy( + PublishedRealmEntryPolicyKind.PUBLISHED_REALM_ENTRY_POLICY_KIND_PRESEEDED_ONLY) + .setPolicyJson(evidence.policy().canonicalJson()) + .setPolicyDigest(evidence.policyDigest()) + .build(); + } + + private static ListPublishedRealmEntryPoliciesResponse replaceFirst( + ListPublishedRealmEntryPoliciesResponse response, + ResolvePublishedRealmEntryPolicyResponse replacement) { + return response.toBuilder().setPolicies(0, replacement).build(); + } + + private static void assertRejected(ListPublishedRealmEntryPoliciesResponse response) + throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.listPublishedRealmEntryPolicies(any())).thenReturn(response); + GameDesignPublishedRealmPolicyClient client = newClient(stub); + assertThatThrownBy( + () -> client.listPublishedRealmEntryPolicies(TENANT_ID.toString(), VERSION_ID)) + .isInstanceOf(IllegalStateException.class); + } + + private static GameDesignPublishedRealmPolicyClient newClient( + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) throws Exception { + GameDesignPublishedRealmPolicyClient 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 { + GameDesignPublishedRealmPolicyClient 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 TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub mockStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = + mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties 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; + } +} From 5f2135de5e2d5077595b95dc59ee9e5bbda93326 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:09:09 +1300 Subject: [PATCH 065/105] Record published policy receiver proof and remaining activation gates --- .../microservices/game-session-service/api-contracts.md | 2 ++ .../game-session-runtime-and-tick-coordination.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 4a846dd7a5..fc5fc9a02d 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -14,6 +14,8 @@ Realm-catalog identity status: Game Session pointer and audit rows persist a sep V12 adds the retained tenant-association receiver and a closed schema-3 snapshot codec for the current Game Session database shape. The candidate service performs the authenticated Game Design read before opening its short owner transaction, fences and re-captures the retained identity projection, and stores exact signed approval plus snapshot evidence under immutable one-to-one constraints. `owner_account_id` is included as the actual required numeric current field; no canonical Account UUID is inferred. This receipt is audited retained identity only: it is not a pointer seed, admission result, membership, actor promotion, or `PLAY` authorization. The service remains explicitly unwired; focused snapshot and service unit proof, integration compilation, formatting and documentation checks passed, while PostgreSQL execution and operational approval custody remain outstanding. +Published realm-policy receiving foundation: the standalone `GameDesignPublishedRealmPolicyClient` reads the complete same-namespace owner set and returns validated typed set evidence, rejecting incomplete or contradictory owner, child, digest, selector, and cardinality evidence. Its [focused test](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) passes 8/8. The client is unwired; no Game Session catalog or playable-state namespace materialization, World-held pointer binding, actor validation, or `PLAY` admission proof is established. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and [test](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java). + This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: - the shipped pause/resume control path is `PauseTicksForScope` / `ResumeTicksForScope` at the current `{tenantId, gameInstanceId}` runtime boundary; 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 f57a4b0491..17a3a748f5 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,6 +14,8 @@ Retained bootstrap correction: V8 recognizes only the unchanged, provenance-back Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. +Published realm-policy receiving foundation: the standalone Game Design client validates the complete typed policy set and passed 8 focused unit tests. It remains unwired and does not materialize Game Session catalog identity or playable-state namespaces, bind a World-held admission pointer, validate actors, or prove `PLAY` admission. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java). + Initial-admission owner boundary: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). The authenticated internal `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiving APIs currently fail closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command, coordinator, follow-up, or queue mutation. Ordinary gameplay APIs are unchanged. [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) covers the receiving-boundary gate; lower-level admission tests do not prove durable receiver-epoch projection or the cross-service pause-versus-handoff race. The gate and remaining successor proof are recorded in the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). From 272fe8c580b5c697ff083b64ee2facdfeb653a25 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:29:31 +1300 Subject: [PATCH 066/105] Use canonical Account UUIDs in integration fixtures and readiness canary --- .../AccountApplicationIntegrationTest.java | 10 ++-- .../GameplayLocalPathReadinessProbe.java | 4 +- .../GameplayLocalPathReadinessProbeTest.java | 52 ++++++++++++++++++- 3 files changed, 58 insertions(+), 8 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index ca7c8d7ec0..9dbcf68369 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -164,7 +164,7 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws "operator", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); HttpRequest request = HttpRequest.newBuilder( - URI.create("http://localhost:" + port + "/accounts/not-a-number/export")) + URI.create("http://localhost:" + port + "/accounts/not-a-uuid/export")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); @@ -173,7 +173,8 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); - assertThat(response.body()).contains("\"message\":\"accountId must be numeric\""); + assertThat(response.body()) + .contains("\"message\":\"accountId must be a canonical non-nil UUID\""); } @Test @@ -199,9 +200,10 @@ void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { @Test void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Exception { - String token = jwtUtil.generateToken("2", java.util.Map.of("accountId", "2")); + String accountUuid = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + String token = jwtUtil.generateToken(accountUuid, java.util.Map.of("accountId", accountUuid)); HttpRequest request = - HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/profiles/2")) + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/profiles/" + accountUuid)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .header(HttpHeaders.CONTENT_TYPE, "application/json") .PUT( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java index 95621033df..9b31c88226 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -18,7 +18,7 @@ public final class GameplayLocalPathReadinessProbe { private static final long PROBE_TENANT_ID = 0L; private static final long PROBE_SESSION_ID = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; private static final long PROBE_GAME_INSTANCE_ID = 0L; private static final String PROBE_ROOM_INSTANCE_ID_PREFIX = "readiness-room-"; @@ -44,7 +44,7 @@ public ProbeResult probeSessionContextStore() { new SessionContext( probeSessionId, PROBE_TENANT_ID, - Long.toString(PROBE_ACCOUNT_ID), + PROBE_ACCOUNT_ID, PROBE_CHARACTER_ID, PROBE_GAME_INSTANCE_ID, probeRoomInstanceId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index c970c7cfe7..27892167f1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -2,25 +2,30 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamesession.health.GameplayLocalPathReadinessProbe.ProbeResult; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.impl.RedisSessionContextService; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; class GameplayLocalPathReadinessProbeTest { private static final long PROBE_SESSION_ID_BASE = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; @Test @@ -37,7 +42,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { new SessionContext( sessionId, 0L, - Long.toString(PROBE_ACCOUNT_ID), + PROBE_ACCOUNT_ID, PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, @@ -59,6 +64,49 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { verify(sessionContextService).deleteBySessionId(0L, savedContext.sessionId()); } + @Test + void sessionContextProbeUsesCanonicalAccountIdentityAcceptedByRedisLookup() { + SessionContextService sessionContextService = mock(SessionContextService.class); + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + doAnswer( + invocation -> { + SessionContext context = invocation.getArgument(0, SessionContext.class); + when(valueOperations.get("sessionctx:0:" + context.sessionId() + ":context")) + .thenReturn(context); + return null; + }) + .when(sessionContextService) + .save(any(SessionContext.class)); + RedisSessionContextService strictLookup = new RedisSessionContextService(redisTemplate, 1000L); + when(sessionContextService.findByTenantAndSessionId(anyLong(), anyLong())) + .thenAnswer( + invocation -> + strictLookup.findByTenantAndSessionId( + invocation.getArgument(0, Long.class), invocation.getArgument(1, Long.class))); + + GameplayLocalPathReadinessProbe probe = + new GameplayLocalPathReadinessProbe(sessionContextService, redisTemplate); + + ProbeResult result = probe.probeSessionContextStore(); + + assertTrue(result.ready()); + assertEquals("ROUND_TRIP_OK", result.detail()); + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(contextCaptor.capture()); + SessionContext savedContext = contextCaptor.getValue(); + assertEquals(PROBE_ACCOUNT_ID, savedContext.accountId()); + assertEquals(UUID.fromString(savedContext.accountId()).toString(), savedContext.accountId()); + assertTrue(savedContext.hasAccountIdentity()); + assertEquals( + Optional.of(savedContext), + strictLookup.findByTenantAndSessionId(savedContext.tenantId(), savedContext.sessionId())); + verify(sessionContextService).deleteBySessionId(0L, savedContext.sessionId()); + } + @Test void commandQueueProbeReturnsUpWhenQueueWriteRoundTrips() { SessionContextService sessionContextService = mock(SessionContextService.class); From e7fe44878c41a8788c3d17b0229a7480719c6123 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:33:37 +1300 Subject: [PATCH 067/105] Bound retained tenant raw evidence to original capture lifetime --- .../game-design-service/api-contracts.md | 4 +- .../game-session-service/api-contracts.md | 8 +- .../game-session-service/runtime-and-data.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 + .../player-access-and-session.md | 2 +- .../v1/tenant_identity_service.proto | 3 + .../GameSessionTenantAssociationEvidence.java | 27 +- ...eSessionTenantAssociationEvidenceTest.java | 52 +++- .../GameDesignServiceApplication.java | 2 + ...nTenantAssociationPayloadRetentionJob.java | 42 +++ ...ameSessionTenantAssociationRepository.java | 131 +++++++-- .../impl/TenantIdentityGrpcService.java | 4 +- ...n_tenant_association_payload_retention.sql | 226 +++++++++++++++ ...tAssociationRepositoryIntegrationTest.java | 234 +++++++++++++++- ...TenantAssociationManifestVerifierTest.java | 29 +- ...antAssociationPayloadRetentionJobTest.java | 31 +++ .../GameSessionTenantAssociationGrpcTest.java | 11 +- ...GameDesignRuntimeTenantIdentityClient.java | 2 + ...onRetainedTenantAssociationRepository.java | 254 ++++++++++++++--- .../GameSessionRetainedTenantSnapshot.java | 117 +++++++- ...ssionRetainedTenantSnapshotRepository.java | 17 +- ...ssionRetainedTenantAssociationService.java | 2 + ...sionRetainedTenantPayloadRetentionJob.java | 38 +++ ...V13__retained_tenant_payload_retention.sql | 257 +++++++++++++++++ ...tAssociationRepositoryIntegrationTest.java | 258 +++++++++++++++++- ...nantSnapshotRepositoryIntegrationTest.java | 16 +- ...DesignRuntimeTenantIdentityClientTest.java | 6 +- ...GameSessionRetainedTenantSnapshotTest.java | 99 +++++-- ...nRetainedTenantAssociationServiceTest.java | 4 +- ...RetainedTenantPayloadRetentionJobTest.java | 43 +++ 30 files changed, 1797 insertions(+), 126 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJobTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJobTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 3e8d320215..38a97c65f5 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -37,7 +37,7 @@ The release-attestation, launch-resolution, version-state, settings, asset-purge Game Design now issues a canonical tenant UUID on its owner `game` row and serves the authenticated owner-local `ResolveRuntimeTenantIdentity` read. Migration V29 records exact source-row/key provenance for valid retained keys and leaves blank or out-of-bounds retained keys quarantined without a canonical identity; row identity and provenance are immutable after issuance. This evidence is only a tenant-owner read: it does not publish realm-entry policy or resolve a realm descriptor/template, current realm pointer, playable-state namespace/scope, or actor admission. Reported focused proof: compilation and `generateJooq` succeeded, `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2; the PostgreSQL integration test compiled, but PostgreSQL execution remains unproved because Docker was unavailable. -Migration V30 adds immutable, namespace-scoped Game Design receipts for explicitly signed retained Game Session tenant associations. The owner repository verifies the closed v1 manifest and purpose-specific trusted public-key map, locks and rereads the exact canonical-UUID `game` source row, then makes one-to-one operation, tenant, and retained-key claims with exact retry/readback. `TenantIdentityService.ResolveLegacyGameSessionTenantAssociation` is a separate same-namespace Game Session mTLS read; this does not add a public approval route, generate signing keys, or enable runtime catalog/admission use. Focused signature, repository, owner-read and auth-wiring unit proof, code generation, integration compilation, formatting and documentation checks passed. PostgreSQL retained-row execution remains unproved locally while Docker is disabled. +Migration V30 added immutable namespace-scoped Game Design association claims; forward migration V32 separates signed approval labels, signature, and source-linked digests into an erasable owner-local payload table. Closed evidence schema 2 binds the exact Game Session source capture time, projection digest, and full snapshot digest. New applies reject source captures at or beyond 30 days using database time; retries do not renew expiry. A bounded owner scheduler deletes up to 100 expired terminal approval payloads per pass; no asynchronous approval-payload consumer or second derived copy exists in this inactive path, while immutable namespace/UUID/private-key/provenance claims remain to prevent reassignment. `TenantIdentityService.ResolveLegacyGameSessionTenantAssociation` remains a same-namespace Game Session mTLS receipt read; after raw expiry it fails closed and is not a public approval route, key generator, or runtime catalog/admission authority. The exact-scope hold audit row references the immutable operation claim rather than the erasable payload, so payload expiry cannot cascade away hold/release evidence. This is separate purpose-bound safety evidence, not an extension of RAW payload retention; ADR 0050 and ADR 0163 require its own finite retention, export/erasure treatment, and access policy. That schedule and a trusted authenticated owner authorization policy are not yet implemented, so hold create/release remain non-operational; supplied principal text or generic DB write access is not accepted. PostgreSQL fixtures seed hold state only to prove owner cleanup/reference behavior, not to prove authorization. Restore must apply owner erasure/cleanup before raw reads; no backup in-place edit or restore traffic-gate proof is claimed. PostgreSQL migration/readback execution remains unproved locally while Docker is disabled. The following implementation and proof gaps remain in these live paths: @@ -133,7 +133,7 @@ The complete-set read is the only policy surface that can prove the authored set ### Audited retained Game Session tenant association -The distinct `game-design/game-session-retained-tenant-association/v1` approval binds the exact positive Game Session tenant key, Game Design canonical tenant UUID, source row/key/provenance, namespace, approval labels and timestamp, and Game Session snapshot digest. Its fixed-order UTF-8 length-framed manifest digest and Ed25519 signature are verified by the V30 owner repository against a purpose-specific trusted public-key map before an immutable association claim. Game Design source provenance accepts only `NEW_GAME_ROW` or the current `RETAINED_GAME_V29`; a Game Design row ID or legacy-key string is never substituted for the approved Game Session key. +The `game-design/game-session-retained-tenant-association/v2` approval binds the exact positive Game Session tenant key, Game Design canonical tenant UUID, source row/key/provenance, namespace, approval labels and timestamp, authoritative source capture time, projection digest, and complete Game Session snapshot digest. Its fixed-order UTF-8 length-framed manifest digest and Ed25519 signature are verified by the owner repository against a purpose-specific trusted public-key map before an immutable association claim. Game Design source provenance accepts only `NEW_GAME_ROW` or the current `RETAINED_GAME_V29`; a Game Design row ID or legacy-key string is never substituted for the approved Game Session key. Payload expiry is measured from the signed source capture time and is not reset by apply/read retry. The read request carries a separate canonical non-nil `requestId`, approval `operationId`, canonical tenant UUID and canonical positive-decimal retained Game Session tenant key. The response echoes that read request separately and returns the complete approval manifest, recomputed manifest digest, and stored signature. Only the verified same-namespace Game Session workload may read it. Unknown fields and malformed or contradictory exact bindings fail closed; a digest or JWT claim is not workload authentication. The repository's immutable signed-manifest application is an owner maintenance boundary, not a public creator route or runtime activation path; signing-key custody and operational approval materialization remain outside this code slice. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index fc5fc9a02d..58d88b92cd 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -12,7 +12,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat Realm-catalog identity status: Game Session pointer and audit rows persist a separately advancing positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; player-facing catalog and runtime pointer projections fail closed when identity is incomplete or a tenant catalog is ambiguous. The control-plane `SetAdmissionPointer` and `ExecutePreparedVersionCutover` paths remain closed pending catalog-revision and durable-identity preconditions. The configuration-driven pointer initializer validates seed shape but does not write authority rows while World-owned lifecycle proof is unavailable; raw seed inputs do not establish that proof or an owner-validated initial bind. Current implementation and proof gaps are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md). -V12 adds the retained tenant-association receiver and a closed schema-3 snapshot codec for the current Game Session database shape. The candidate service performs the authenticated Game Design read before opening its short owner transaction, fences and re-captures the retained identity projection, and stores exact signed approval plus snapshot evidence under immutable one-to-one constraints. `owner_account_id` is included as the actual required numeric current field; no canonical Account UUID is inferred. This receipt is audited retained identity only: it is not a pointer seed, admission result, membership, actor promotion, or `PLAY` authorization. The service remains explicitly unwired; focused snapshot and service unit proof, integration compilation, formatting and documentation checks passed, while PostgreSQL execution and operational approval custody remain outstanding. +V12 retains the immutable tenant-association claim; V13 separates its account-linked approval and raw-snapshot payload into an owner-local erasable table. The candidate remains explicitly unwired. Snapshot schema 4 binds the authoritative database capture time; signed approval schema 2 binds that same capture time, the canonical projection digest, and the complete snapshot digest. Registration recaptures under the owner fence, compares the current projection, and verifies the signed full digest after rebinding only the unchanged rows to the original source capture time. Missing/ambiguous legacy capture evidence fails closed and requires new capture; approval, consume, and retry do not renew the 30-day lifetime. `owner_account_id` remains the actual required numeric field; no canonical Account UUID is inferred. The mapping is identity evidence only, not a pointer seed, admission result, membership, actor promotion, or `PLAY` authorization. Focused proof and PostgreSQL limits are recorded below; raw backup edits and restore-gate proof are not claimed. Published realm-policy receiving foundation: the standalone `GameDesignPublishedRealmPolicyClient` reads the complete same-namespace owner set and returns validated typed set evidence, rejecting incomplete or contradictory owner, child, digest, selector, and cardinality evidence. Its [focused test](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) passes 8/8. The client is unwired; no Game Session catalog or playable-state namespace materialization, World-held pointer binding, actor validation, or `PLAY` admission proof is established. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and [test](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java). @@ -40,9 +40,11 @@ It also communicates game lifecycle changes to other microservices over gRPC so ### Audited retained-tenant association (nonactivating) -For one explicitly approved retained Game Session tenant key, the candidate service first reads Game Design's exact signed approval over the authenticated owner client with no Game Session transaction open. It then starts a short read-write `READ COMMITTED` owner transaction, locks the captured tenant's retained identity table families with `SHARE MODE NOWAIT`, captures one deterministic projection, verifies its digest equals the signed approval's `gameSessionEvidenceDigest`, and inserts/readbacks one immutable namespace-qualified local association. Missing, unreadable, contradictory or concurrently changing evidence fails closed; exact stable request retries return the original persisted receipt without recapturing or changing it. +For one explicitly approved retained Game Session tenant key, the candidate service first reads Game Design's exact signed approval over the authenticated owner client with no Game Session transaction open. It then starts a short read-write `READ COMMITTED` owner transaction, locks the captured tenant's retained identity table families with `SHARE MODE NOWAIT`, captures one deterministic projection, compares its projection digest with the signed approval, rebinds that unchanged projection to the signed source capture time, and checks the resulting full digest before recording the mapping and raw payload in one transaction. Missing, unreadable, contradictory, expired, or concurrently changing evidence fails closed; exact retries never recapture or refresh expiry, and an expired or erased raw receipt fails closed without reconstructing it. -The current-tree snapshot uses `schemaVersion=3` and digest domain `game-session/retained-tenant-identity-snapshot/v3`; its SHA-256 preimage is the UTF-8 byte-length-framed pair `(domain, RFC 8785 canonical JSON)`. The JSON contains the exact projection envelope and ordered rows for `instances`, `pointers`, `sharedNamespaces`, empty `backfillIssues`, `pointerEvents`, and `preparedUpgrades`; each row has a closed current-schema fieldset. `instances.owner_account_id` is retained as its actual required numeric value. There is no `owner_account_uuid` field, numeric Game Session tenant keys are never derived from Game Design row IDs, and schema-v2 receipts are incompatible and rejected. This local association is an audited identity bridge only: it does not create or seed a runtime pointer, activate `PLAY`, promote an actor, or grant membership or entitlement. The service is not wired into startup or an activation path; approval materialization/key custody and PostgreSQL execution remain pending. Focused unit proof, code generation, integration compilation, formatting and documentation checks passed. +The current-tree snapshot uses `schemaVersion=4` and digest domain `game-session/retained-tenant-identity-snapshot/v4`; its canonical JSON includes `capturedAt`, and a separate projection digest omits only that timestamp so a later fenced read can prove the same source rows. Signed approval schema 2 covers the exact capture time plus both digests. Snapshot schema 3 and signed evidence schema 1 are rejected for new operations; previously ambiguous rows retain their namespace/tenant/provenance anti-reassignment claim but their payload is immediately cleanup-eligible and cannot be replayed. `instances.owner_account_id` remains the numeric owner value, with no invented `owner_account_uuid` or Game Design-row-derived Game Session key. + +Raw snapshot, approval labels/signature, receipt/request digests and subject-linked fingerprints live in `game_session_retained_tenant_association_payload` and expire at `captured_at + 30 days` using database time. The payload is owner-local and omitted from current tenant exports; no asynchronous raw-payload consumer or second derived copy exists in this inactive path. An owner-local scheduler deletes at most 100 expired `ASSOCIATED` terminal payloads per pass with `SKIP LOCKED`; the immutable mapping and exact active-hold relation are its only owner-table references. Delete guards preserve unexpired payloads and exact mapping rows remain immutable after cleanup. `readMinimalAssociation(exactNamespace, canonicalTenantId)` returns only the canonical UUID, private Game Session tenant key, and immutable Game Design source row/key/provenance; it reads only the mapping table and remains independent of erased approval/raw content. Full receipt reads and retries fail closed after expiry or cleanup. Legal-hold storage records exact raw-payload scope, reason, case reference, authorization, principal, review, and release metadata, but creation and release are currently rejected until an authenticated owner authorization policy boundary exists; caller-supplied labels or database write access are not proof. No hold exemption is operational in this build. Restore must apply the service's erasure overlay/cleanup before any raw reader is opened; stale restored payload reads fail expiry checks, but there is no implemented restore traffic gate or proof that backup artifacts were edited in place. These controls do not wire identity materialization, pointers, `PLAY`, actors, rosters, or public endpoints. ## World Lifecycle and Admission Boundary 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 7603e3ee4e..827489f32c 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -11,7 +11,7 @@ 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: - 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). -- Game Session V12 adds an immutable local receipt for an approved retained-tenant association. Before its short read-write `READ COMMITTED` transaction, the unwired service reads the exact Game Design approval over the authenticated owner channel; within the transaction it captures the closed retained-row projection behind `SHARE MODE NOWAIT`, compares its digest with the signed approval, then inserts and reads back the one-to-one local association. Snapshot schema 3 binds the current schema's required numeric `game_instances.owner_account_id` without inventing `owner_account_uuid`; its digest domain is `game-session/retained-tenant-identity-snapshot/v3`, so schema-v2 receipts are rejected. This audit prerequisite does not seed a runtime pointer, promote an actor, enable `PLAY`, or activate gameplay. Focused snapshot and service unit proof, code generation, integration compilation, formatting and documentation checks passed; PostgreSQL retained-row execution and approval custody remain pending. +- Game Session V13 keeps the V12 namespace/canonical/private-tenant anti-reassignment row immutable while moving approval/audit payload and account-linked raw snapshot to an owner-local erasable table. Snapshot schema 4 carries database capture time; signed approval schema 2 binds that time, projection digest, and full snapshot digest. Expiry is computed from that unchanged source capture timestamp (30 days), never approval, receipt, retry, or consume time. A bounded owner scheduler removes expired terminal payloads; expired or restored stale payloads fail closed in full reads, while `readMinimalAssociation(exactNamespace, canonicalTenantId)` reads only the immutable mapping/provenance row. Old capture-ambiguous payload is rejected and cleanup-eligible but its association claim is retained. Hold audit references that immutable mapping, not erasable payload, so raw expiry preserves exact hold/release evidence. This audit is separate purpose-bound safety evidence under ADR 0050/0163 and requires finite owner retention plus export/erasure treatment; no post-release schedule or authenticated owner policy is implemented, so hold create/release remain non-operational and arbitrary principal strings are not accepted as proof. PostgreSQL fixtures seed held/released rows only to prove blocker and cleanup behavior, not authorization. Restore cleanup must precede raw reader exposure; no in-place backup edit or restore traffic-gate proof is claimed. The service remains unwired and this audit prerequisite does not seed pointers, actors, rosters, admission, `PLAY`, or public endpoints. Focused validation and PostgreSQL availability are reported in the tracker. - 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. - **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control. 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 8612ae89ad..8e34d6c70e 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 @@ -10,6 +10,8 @@ This tracker consolidates Game Design authoring, settings, publication, release Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; the issuance and source provenance are immutable. Reported focused V29 proof remains `TenantIdentityGrpcServiceTest` 6/6, `TenantIdentityGrpcAuthWiringTest` 3/3, and `RuntimeTenantIdentityEvidenceTest` 2/2; the PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. The current bounded owner-producer slice adds a closed-v1 `REALM_ENTRY_POLICY` revision path, transactionally frozen immutable policy rows at full-version release-bundle creation, a same-namespace authenticated exact-row read, and a complete-set read capped at 128 rows with owner-bound set identity/count. The latest locked validation passed the focused common evidence tests (4/4), Game Design `RevisionServiceImplTest` (15/15), `PublishedReleaseBundleServiceImplTest` (15/15), `TenantIdentityGrpcServiceTest` (12/12), and `TenantIdentityGrpcAuthWiringTest` (8/8), plus `generateJooq`, `compileIntegrationTestJava`, Java formatting checks, `linkCheck`, and Markdown lint. The migration/readback integration test was compiled but not executed; no Docker or PostgreSQL runtime validation was performed. Only complete-set evidence can establish the authored set's exactly-one-visible-publicProduction cardinality; neither it nor the selector read proves current Game Session catalog validity, pointer/namespace/scope composition, descriptor/template identity, Entity actor admission, or actor creation/activation. Target semantics remain in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), and actor-entry target behavior remains [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +The separate retained Game Session tenant-association prerequisite keeps immutable source-row/key/provenance and namespace/canonical/private-key claims while V32 moves signed approval labels, signature, and source-linked digests into an owner-local 30-day capture-expiring payload. V2 evidence binds the exact GS source capture time and both snapshot digests; retries do not renew expiry. Automatic bounded cleanup preserves terminal anti-reassignment rows. Hold audit references the immutable association claim, not erasable raw payload, and therefore survives payload cleanup. Under ADR 0050/0163 it is separate purpose-bound safety evidence requiring finite post-release retention/export/erasure policy; that schedule and a trusted authenticated owner policy are not implemented, so hold create/release remain fail-closed with no generic audit exemption. Test fixtures prove cleanup/reference behavior only, not authorization. Game Session's mapping-only internal read remains independent of expired/erased raw evidence. This prerequisite is not runtime catalog/admission authority and does not enable activation or public endpoints. Its focused validation and PostgreSQL/restore-proof limits are recorded in the owning service docs and [Player Access and Session](./player-access-and-session.md#current-status). + 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. 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 1ab92606e1..bd2a778096 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ This candidate now carries Account UUID through Account authentication, bootstra The Game Design canonical tenant UUID/provenance producer and its Game Session receiver are prepared in a separate retained-tenant association prerequisite, not this Account UUID carrier slice. That prerequisite must prove source identity and exact retained-row association without establishing the current Game Session pointer, playable-state namespace/scope, published actor-entry policy, Entity selection, or actor creation. `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). -The retained-tenant association candidate now has a signed Game Design owner receipt/read (V30) and a Game Session local immutable association/snapshot receiver (V12). Its schema-3 snapshot binds the current required numeric `owner_account_id` and rejects older schema-2 receipts rather than implying a canonical owner UUID. This audited mapping is not wired into runtime pointer creation, actor selection, membership, or `PLAY`; focused canonical JSON, signature, owner-read/auth-wiring, snapshot and receipt unit proof, code generation, integration compilation, formatting and documentation checks passed. Approval signing-key custody/materialization, PostgreSQL readback proof, and any later explicit activation decision remain dependencies. `AA-2.1` status is unchanged. +The retained-tenant association prerequisite now has a signed Game Design owner receipt/read (V30 + forward V32 payload-retention migration) and a Game Session local immutable association/snapshot receiver (V12 + forward V13 payload-retention migration). Schema-4 snapshot and signed-evidence-v2 bind one authoritative source capture time; account-linked raw snapshot, approval and digests have a 30-day capture-based lifetime with bounded owner cleanup, while minimal immutable namespace/UUID/private-key/provenance claims remain for anti-reassignment. The internal Game Session proof read is `readMinimalAssociation(exactNamespace, canonicalTenantId)` and returns only that mapping/provenance. Expired or restored stale raw evidence fails closed and old ambiguous evidence requires recapture. Hold audit now references the immutable mapping so raw cleanup cannot cascade away create/release evidence; it is separate purpose-bound safety evidence, not retained RAW payload. Its finite post-release retention/export/erasure schedule and authenticated owner policy are not implemented, so create/release remain fail-closed and no hold extension is operational. PostgreSQL fixtures exercise blocker/release cleanup only by seeding owner rows with the guard trigger temporarily disabled; this is not authorization proof. Restore cleanup gating and backup artifact rewriting are not proved. This audited mapping remains unwired and does not create pointers, rosters, actor selection, membership, `PLAY`, or public endpoints. PostgreSQL migration/readback execution remains unproved when Docker is unavailable; this does not change `AA-2.1` status. Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index a19f1c7129..3e4f6a8dad 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -51,12 +51,15 @@ message GameSessionTenantAssociationManifestEvidence { string approved_by = 5; string approval_reference = 6; string signed_at = 7; + // Database-generated time of the closed Game Session source snapshot. + string source_captured_at = 14; string legacy_game_session_tenant_id = 8; string canonical_tenant_id = 9; string source_game_row_id = 10; string source_game_tenant_key = 11; string provenance_kind = 12; string game_session_evidence_digest = 13; + string game_session_projection_digest = 15; } message ResolveLegacyGameSessionTenantAssociationResponse { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java index dbdc07791d..a1a86bee31 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java @@ -4,6 +4,7 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.HexFormat; @@ -21,16 +22,19 @@ public record GameSessionTenantAssociationEvidence( String approvedBy, String approvalReference, String signedAt, + String sourceCapturedAt, String legacyGameSessionTenantId, UUID canonicalTenantId, String sourceGameRowId, String sourceGameTenantKey, String provenanceKind, + String gameSessionProjectionDigest, String gameSessionEvidenceDigest) { - private static final String DOMAIN = "game-design/game-session-retained-tenant-association/v1"; - private static final int SCHEMA_VERSION = 1; + private static final String DOMAIN = "game-design/game-session-retained-tenant-association/v2"; + private static final int SCHEMA_VERSION = 2; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + public static final Duration RAW_RETENTION = Duration.ofDays(30); public GameSessionTenantAssociationEvidence { if (schemaVersion != SCHEMA_VERSION) { @@ -43,6 +47,10 @@ public record GameSessionTenantAssociationEvidence( requireLabel(approvedBy, 256, "approvedBy"); requireLabel(approvalReference, 512, "approvalReference"); requireCanonicalInstant(signedAt); + requireCanonicalInstant(sourceCapturedAt); + if (Instant.parse(sourceCapturedAt).isAfter(Instant.parse(signedAt))) { + throw new IllegalArgumentException("sourceCapturedAt may not follow signedAt"); + } requirePositiveBigintText(legacyGameSessionTenantId, "legacyGameSessionTenantId"); requireNonNil(canonicalTenantId, "canonicalTenantId"); requirePositiveBigintText(sourceGameRowId, "sourceGameRowId"); @@ -50,9 +58,9 @@ public record GameSessionTenantAssociationEvidence( if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { throw new IllegalArgumentException("Game Design tenant provenance kind is not recognized"); } - if (!isDigest(gameSessionEvidenceDigest)) { + if (!isDigest(gameSessionProjectionDigest) || !isDigest(gameSessionEvidenceDigest)) { throw new IllegalArgumentException( - "gameSessionEvidenceDigest must be a lowercase SHA-256 digest"); + "Game Session evidence digests must be lowercase SHA-256 digests"); } } @@ -67,11 +75,13 @@ public byte[] preimage() { writeSegment(output, approvedBy); writeSegment(output, approvalReference); writeSegment(output, signedAt); + writeSegment(output, sourceCapturedAt); writeSegment(output, legacyGameSessionTenantId); writeSegment(output, canonicalTenantId.toString()); writeSegment(output, sourceGameRowId); writeSegment(output, sourceGameTenantKey); writeSegment(output, provenanceKind); + writeSegment(output, gameSessionProjectionDigest); writeSegment(output, gameSessionEvidenceDigest); return output.toByteArray(); } @@ -96,6 +106,15 @@ public long sourceGameRowIdValue() { return Long.parseLong(sourceGameRowId); } + /** The immutable expiry boundary is always measured from the original owner capture. */ + public Instant rawExpiresAt() { + return Instant.parse(sourceCapturedAt).plus(RAW_RETENTION); + } + + public boolean rawExpiredAt(Instant now) { + return !Objects.requireNonNull(now, "now").isBefore(rawExpiresAt()); + } + private static void writeSegment(ByteArrayOutputStream output, String value) { int byteLength = utf8ByteLength(value); byte[] encoded = value.getBytes(StandardCharsets.UTF_8); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java index 178b6a9674..73b98c0bf5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java @@ -18,22 +18,24 @@ void emitsFixedCompleteUtf8FramingAndManifestDigestVector() { assertThat(new String(evidence.preimage(), java.nio.charset.StandardCharsets.UTF_8)) .isEqualTo( - "55:game-design/game-session-retained-tenant-association/v1" - + "1:1" + "55:game-design/game-session-retained-tenant-association/v2" + + "1:2" + "36:11111111-1111-4111-8111-111111111111" + "7:firemud" + "14:owner-key-2026" + "10:owner 🧙" + "17:review café-🐉" + "20:2026-10-01T00:00:00Z" + + "20:2026-09-30T00:00:00Z" + "16:9007199254740993" + "36:22222222-2222-4222-8222-222222222222" + "2:42" + "18:legacy-game-key-42" + "17:RETAINED_GAME_V29" + + "71:sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + "71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); assertThat(evidence.manifestDigest()) - .isEqualTo("sha256:8dbc7e33a24d4e6d577a381276df0a9b0168b78363749a37f05cc76f0e9c152c"); + .isEqualTo("sha256:1d9feea3a8f6daefd7ff1a3789989a9d5f4d0794e9bc9dbefe2f4d9e61788c46"); } @Test @@ -55,7 +57,7 @@ void changedValidFieldChangesSharedPreimageAndDigest() { assertThat(changed.preimage()).isNotEqualTo(source.preimage()); assertThat(changed.manifestDigest()).isNotEqualTo(source.manifestDigest()); } - assertThatThrownBy(() -> copyWithSchemaVersion(source, 2)) + assertThatThrownBy(() -> copyWithSchemaVersion(source, 1)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("schema version"); } @@ -64,18 +66,20 @@ void changedValidFieldChangesSharedPreimageAndDigest() { void preservesApprovalTextExactlyAndRequiresCanonicalUtcInstant() { GameSessionTenantAssociationEvidence spaced = new GameSessionTenantAssociationEvidence( - 1, + 2, OPERATION_ID, "firemud", "owner-key-2026", " owner ", " reference ", "2026-10-01T00:00:00Z", + "2026-09-30T00:00:00Z", "41", TENANT_ID, "42", " legacy-game-key ", "RETAINED_GAME_V29", + "sha256:" + "b".repeat(64), GAME_SESSION_DIGEST); assertThat(spaced.approvedBy()).isEqualTo(" owner "); assertThat(spaced.approvalReference()).isEqualTo(" reference "); @@ -84,6 +88,17 @@ void preservesApprovalTextExactlyAndRequiresCanonicalUtcInstant() { assertInvalid(() -> copySignedAt(evidence(), "2026-10-01T00:00:00+00:00")); assertInvalid(() -> copySignedAt(evidence(), "2026-10-01T00:00:00.000Z")); assertInvalid(() -> copySignedAt(evidence(), "not-an-instant")); + assertInvalid(() -> copySourceCapturedAt(evidence(), "2026-10-01T00:00:00.000000001Z")); + assertInvalid(() -> copySourceCapturedAt(evidence(), "2026-09-30T00:00:00+00:00")); + } + + @Test + void expiresRawEvidenceAtTheExactThirtyDayCaptureBoundary() { + GameSessionTenantAssociationEvidence source = evidence(); + + assertThat(source.rawExpiredAt(Instant.parse("2026-10-29T23:59:59.999999999Z"))).isFalse(); + assertThat(source.rawExpiredAt(Instant.parse("2026-10-30T00:00:00Z"))).isTrue(); + assertThat(source.rawExpiresAt()).isEqualTo(Instant.parse("2026-10-30T00:00:00Z")); } @Test @@ -135,18 +150,20 @@ void rejectsMalformedIdentifiersBoundsUnicodeAndClosedEnums() { private static GameSessionTenantAssociationEvidence evidence() { return new GameSessionTenantAssociationEvidence( - 1, + 2, OPERATION_ID, "firemud", "owner-key-2026", "owner 🧙", "review café-🐉", Instant.parse("2026-10-01T00:00:00Z").toString(), + Instant.parse("2026-09-30T00:00:00Z").toString(), "9007199254740993", TENANT_ID, "42", "legacy-game-key-42", "RETAINED_GAME_V29", + "sha256:" + "b".repeat(64), GAME_SESSION_DIGEST); } @@ -209,6 +226,26 @@ private static GameSessionTenantAssociationEvidence copyWithSchemaVersion( source.gameSessionEvidenceDigest()); } + private static GameSessionTenantAssociationEvidence copySourceCapturedAt( + GameSessionTenantAssociationEvidence source, String sourceCapturedAt) { + return new GameSessionTenantAssociationEvidence( + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + sourceCapturedAt, + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionProjectionDigest(), + source.gameSessionEvidenceDigest()); + } + private static GameSessionTenantAssociationEvidence copyWithNamespace( GameSessionTenantAssociationEvidence source, String namespace) { return copy( @@ -356,11 +393,13 @@ private static GameSessionTenantAssociationEvidence copy( approvedBy, approvalReference, signedAt, + source.sourceCapturedAt(), legacyGameSessionTenantId, canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind, + source.gameSessionProjectionDigest(), gameSessionEvidenceDigest); } @@ -383,6 +422,7 @@ private static java.util.List changedField source, source.operationId(), UUID.fromString("33333333-3333-4333-8333-333333333333")), copyIds(source, source.legacyGameSessionTenantId(), "43"), copyWithSourceKey(source, "another-source-key"), + copySourceCapturedAt(source, "2026-09-29T00:00:00Z"), copyWithProvenance(source, "NEW_GAME_ROW"), copyWithEvidenceDigest(source, "sha256:" + "b".repeat(64))); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java index d63df1e4df..df0bc4939f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java @@ -5,9 +5,11 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; import org.springframework.context.annotation.Import; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @ConfigurationPropertiesScan +@EnableScheduling @Import(GlobalExceptionHandler.class) public class GameDesignServiceApplication { public static void main(String[] args) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java new file mode 100644 index 0000000000..20eda90f55 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +/** + * Gradually erases expired approval payloads while preserving association anti-reassignment rows. + */ +@Component +@ConditionalOnProperty( + name = "firemud.retained-tenant.payload-retention.enabled", + havingValue = "true", + matchIfMissing = true) +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repository is an owner-local Spring-managed collaborator.") +public class GameSessionTenantAssociationPayloadRetentionJob { + private static final Logger LOG = + LoggerFactory.getLogger(GameSessionTenantAssociationPayloadRetentionJob.class); + + private final GameSessionTenantAssociationRepository repository; + + public GameSessionTenantAssociationPayloadRetentionJob( + GameSessionTenantAssociationRepository repository) { + this.repository = repository; + } + + @Scheduled(fixedDelayString = "${firemud.retained-tenant.payload-retention.sweep-ms:60000}") + @Transactional + public void purgeExpiredPayloadBatch() { + int deleted = repository.purgeExpiredRawPayloads(); + if (deleted > 0) { + LOG.info("Purged {} expired Game Session tenant approval payload(s)", deleted); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java index 85e859dc05..07abe777e3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java @@ -1,6 +1,9 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.Base64; import java.util.Map; import java.util.Objects; @@ -13,6 +16,7 @@ import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; +import org.jooq.SelectJoinStep; import org.jooq.Table; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @@ -33,17 +37,20 @@ public class GameSessionTenantAssociationRepository { private static final Table ASSOCIATION = DSL.table(DSL.name("game_design_game_session_tenant_association_operations")); + private static final Table ASSOCIATION_PAYLOAD = + DSL.table(DSL.name("game_design_game_session_tenant_association_payload")); private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); private static final Field SCHEMA_VERSION = - DSL.field(DSL.name("schema_version"), Integer.class); + DSL.field( + DSL.name("game_design_game_session_tenant_association_payload", "schema_version"), + Integer.class); private static final Field TARGET_NAMESPACE = DSL.field(DSL.name("target_namespace"), String.class); - private static final Field SIGNER_KEY_ID = - DSL.field(DSL.name("signer_key_id"), String.class); - private static final Field APPROVED_BY = DSL.field(DSL.name("approved_by"), String.class); + private static final Field SIGNER_KEY_ID = payloadField("signer_key_id", String.class); + private static final Field APPROVED_BY = payloadField("approved_by", String.class); private static final Field APPROVAL_REFERENCE = - DSL.field(DSL.name("approval_reference"), String.class); - private static final Field SIGNED_AT = DSL.field(DSL.name("signed_at"), String.class); + payloadField("approval_reference", String.class); + private static final Field SIGNED_AT = payloadField("signed_at", String.class); private static final Field LEGACY_GAME_SESSION_TENANT_ID = DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class); private static final Field CANONICAL_TENANT_ID = @@ -55,10 +62,21 @@ public class GameSessionTenantAssociationRepository { private static final Field PROVENANCE_KIND = DSL.field(DSL.name("provenance_kind"), String.class); private static final Field GAME_SESSION_EVIDENCE_DIGEST = - DSL.field(DSL.name("game_session_evidence_digest"), String.class); + payloadField("game_session_evidence_digest", String.class); + private static final Field GAME_SESSION_PROJECTION_DIGEST = + payloadField("game_session_projection_digest", String.class); private static final Field MANIFEST_DIGEST = - DSL.field(DSL.name("manifest_digest"), String.class); - private static final Field SIGNATURE = DSL.field(DSL.name("signature"), String.class); + payloadField("manifest_digest", String.class); + private static final Field SIGNATURE = payloadField("signature", String.class); + private static final Field CAPTURED_AT = + DSL.field(DSL.name("captured_at"), OffsetDateTime.class); + private static final Field TERMINAL_OUTCOME = + DSL.field(DSL.name("terminal_outcome"), String.class); + private static final Field ASSOCIATION_OPERATION_ID = + DSL.field( + DSL.name("game_design_game_session_tenant_association_operations", "operation_id"), + UUID.class); + private static final Field PAYLOAD_OPERATION_ID = payloadField("operation_id", UUID.class); private final DSLContext dsl; private final GameRepository gameRepository; @@ -85,6 +103,7 @@ public AssociationReceipt apply( throw new IllegalArgumentException("manifest targets a different namespace"); } requireActiveOwnerTransaction(); + requireCaptureStillUsable(manifest.sourceCapturedAt()); GameTenantIdentity source = lockAndReadSource(manifest.canonicalTenantId()); requireManifestSource(manifest, source); @@ -92,23 +111,38 @@ public AssociationReceipt apply( int inserted = dsl.insertInto(ASSOCIATION) .set(OPERATION_ID, manifest.operationId()) - .set(SCHEMA_VERSION, manifest.schemaVersion()) .set(TARGET_NAMESPACE, manifest.targetNamespace()) - .set(SIGNER_KEY_ID, manifest.signerKeyId()) - .set(APPROVED_BY, manifest.approvedBy()) - .set(APPROVAL_REFERENCE, manifest.approvalReference()) - .set(SIGNED_AT, manifest.signedAt()) .set(LEGACY_GAME_SESSION_TENANT_ID, manifest.legacyGameSessionTenantIdValue()) .set(CANONICAL_TENANT_ID, manifest.canonicalTenantId()) .set(SOURCE_GAME_ROW_ID, manifest.sourceGameRowIdValue()) .set(SOURCE_GAME_TENANT_KEY, manifest.sourceGameTenantKey()) .set(PROVENANCE_KIND, manifest.provenanceKind()) - .set(GAME_SESSION_EVIDENCE_DIGEST, manifest.gameSessionEvidenceDigest()) - .set(MANIFEST_DIGEST, verified.manifestDigest()) - .set(SIGNATURE, signed.ed25519Signature()) + .set( + CAPTURED_AT, + OffsetDateTime.ofInstant( + Instant.parse(manifest.sourceCapturedAt()), ZoneOffset.UTC)) + .set(TERMINAL_OUTCOME, "ASSOCIATED") .onConflictDoNothing() .execute(); + if (inserted == 1) { + dsl.execute( + "INSERT INTO game_design_game_session_tenant_association_payload (" + + "operation_id, schema_version, signer_key_id, approved_by, approval_reference, " + + "signed_at, game_session_projection_digest, game_session_evidence_digest, " + + "manifest_digest, signature) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + manifest.operationId(), + manifest.schemaVersion(), + manifest.signerKeyId(), + manifest.approvedBy(), + manifest.approvalReference(), + manifest.signedAt(), + manifest.gameSessionProjectionDigest(), + manifest.gameSessionEvidenceDigest(), + verified.manifestDigest(), + signed.ed25519Signature()); + } + Record persisted = findByOperationId(manifest.operationId()); if (persisted == null) { if (inserted == 0) { @@ -152,9 +186,9 @@ public Optional read( } Record row = - dsl.selectFrom(ASSOCIATION) + selectCompleteAssociation() .where( - OPERATION_ID + ASSOCIATION_OPERATION_ID .eq(operationId) .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) .and(LEGACY_GAME_SESSION_TENANT_ID.eq(legacyGameSessionTenantId)) @@ -176,6 +210,27 @@ public Optional read( return Optional.of(receipt); } + /** Deletes one bounded batch of expired Game Session approval payloads. */ + @Transactional(propagation = Propagation.REQUIRED) + public int purgeExpiredRawPayloads() { + return dsl.execute( + "WITH expired AS (" + + " SELECT payload.operation_id" + + " FROM game_design_game_session_tenant_association_payload payload" + + " JOIN game_design_game_session_tenant_association_operations association" + + " ON association.operation_id = payload.operation_id" + + " WHERE association.terminal_outcome = 'ASSOCIATED'" + + " AND (association.captured_at IS NULL" + + " OR association.captured_at <= clock_timestamp() - INTERVAL '30 days')" + + " AND NOT EXISTS (SELECT 1" + + " FROM game_design_game_session_tenant_association_legal_hold hold" + + " WHERE hold.operation_id = payload.operation_id AND hold.released_at IS NULL)" + + " ORDER BY association.captured_at NULLS FIRST, payload.operation_id" + + " LIMIT 100 FOR UPDATE OF payload SKIP LOCKED" + + ") DELETE FROM game_design_game_session_tenant_association_payload payload" + + " USING expired WHERE payload.operation_id = expired.operation_id"); + } + private GameTenantIdentity lockAndReadSource(UUID canonicalTenantId) { Long lockedGameId = dsl.select(GAME_ID) @@ -201,7 +256,38 @@ private GameTenantIdentity lockAndReadSource(UUID canonicalTenantId) { } private Record findByOperationId(UUID operationId) { - return dsl.selectFrom(ASSOCIATION).where(OPERATION_ID.eq(operationId)).fetchOne(); + return selectCompleteAssociation().where(ASSOCIATION_OPERATION_ID.eq(operationId)).fetchOne(); + } + + private SelectJoinStep selectCompleteAssociation() { + return dsl.select(ASSOCIATION.asterisk(), ASSOCIATION_PAYLOAD.asterisk()) + .from(ASSOCIATION) + .leftJoin(ASSOCIATION_PAYLOAD) + .on(ASSOCIATION_OPERATION_ID.eq(PAYLOAD_OPERATION_ID)); + } + + private void requireCaptureStillUsable(String capturedAt) { + Record expiry = + dsl.fetchOne( + "SELECT clock_timestamp() >= (?::timestamptz + INTERVAL '30 days') AS expired", + capturedAt); + if (expiry == null || Boolean.TRUE.equals(expiry.get("expired", Boolean.class))) { + throw new InvalidAssociationEvidenceException( + "Game Session tenant approval is expired and requires a new source capture"); + } + } + + private static String captureInstant(Record row) { + OffsetDateTime capturedAt = row.get(CAPTURED_AT); + if (capturedAt == null) { + throw new InvalidAssociationEvidenceException( + "Game Session tenant association has no authoritative source capture time"); + } + return capturedAt.toInstant().toString(); + } + + private static Field payloadField(String name, Class type) { + return DSL.field(DSL.name("game_design_game_session_tenant_association_payload", name), type); } private AssociationReceipt toValidatedReceipt(Record row) { @@ -209,19 +295,22 @@ private AssociationReceipt toValidatedReceipt(Record row) { GameSessionTenantAssociationEvidence manifest = new GameSessionTenantAssociationEvidence( row.get(SCHEMA_VERSION), - row.get(OPERATION_ID), + row.get(ASSOCIATION_OPERATION_ID), row.get(TARGET_NAMESPACE), row.get(SIGNER_KEY_ID), row.get(APPROVED_BY), row.get(APPROVAL_REFERENCE), row.get(SIGNED_AT), + captureInstant(row), Long.toString(row.get(LEGACY_GAME_SESSION_TENANT_ID)), row.get(CANONICAL_TENANT_ID), Long.toString(row.get(SOURCE_GAME_ROW_ID)), row.get(SOURCE_GAME_TENANT_KEY), row.get(PROVENANCE_KIND), + row.get(GAME_SESSION_PROJECTION_DIGEST), row.get(GAME_SESSION_EVIDENCE_DIGEST)); String signature = row.get(SIGNATURE); + requireCaptureStillUsable(manifest.sourceCapturedAt()); requireCanonicalSignatureShape(signature); String persistedDigest = row.get(MANIFEST_DIGEST); if (!manifest.manifestDigest().equals(persistedDigest)) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index 416dd454f2..a540b7d4d8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -245,12 +245,14 @@ public void resolveLegacyGameSessionTenantAssociation( .setApprovedBy(evidence.approvedBy()) .setApprovalReference(evidence.approvalReference()) .setSignedAt(evidence.signedAt()) + .setSourceCapturedAt(evidence.sourceCapturedAt()) .setLegacyGameSessionTenantId(evidence.legacyGameSessionTenantId()) .setCanonicalTenantId(evidence.canonicalTenantId().toString()) .setSourceGameRowId(evidence.sourceGameRowId()) .setSourceGameTenantKey(evidence.sourceGameTenantKey()) .setProvenanceKind(evidence.provenanceKind()) - .setGameSessionEvidenceDigest(evidence.gameSessionEvidenceDigest())) + .setGameSessionEvidenceDigest(evidence.gameSessionEvidenceDigest()) + .setGameSessionProjectionDigest(evidence.gameSessionProjectionDigest())) .setManifestDigest(receipt.manifestDigest()) .setEd25519Signature(receipt.ed25519Signature()) .build()); diff --git a/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql b/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql new file mode 100644 index 0000000000..4ffdf38855 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql @@ -0,0 +1,226 @@ +ALTER TABLE game_design_game_session_tenant_association_operations + DROP CONSTRAINT chk_gd_game_session_association_schema; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP CONSTRAINT chk_gd_game_session_association_approval_labels; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP CONSTRAINT chk_gd_game_session_association_signed_at; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP CONSTRAINT chk_gd_game_session_association_digests; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP CONSTRAINT chk_gd_game_session_association_signature; + +ALTER TABLE game_design_game_session_tenant_association_operations + ADD COLUMN captured_at TIMESTAMPTZ; +ALTER TABLE game_design_game_session_tenant_association_operations + ADD COLUMN terminal_outcome VARCHAR(32) NOT NULL DEFAULT 'ASSOCIATED'; + +CREATE TABLE game_design_game_session_tenant_association_payload ( + operation_id UUID PRIMARY KEY + REFERENCES game_design_game_session_tenant_association_operations(operation_id) + ON DELETE RESTRICT, + schema_version INTEGER NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + game_session_projection_digest VARCHAR(71), + game_session_evidence_digest VARCHAR(71) NOT NULL, + manifest_digest VARCHAR(71) NOT NULL, + signature VARCHAR(88) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chk_gd_game_session_association_payload_schema CHECK (schema_version IN (1, 2)), + CONSTRAINT chk_gd_game_session_association_payload_capture CHECK ( + (schema_version = 1 AND game_session_projection_digest IS NULL) + OR (schema_version = 2 + AND game_session_projection_digest ~ '^sha256:[0-9a-f]{64}$') + ), + CONSTRAINT chk_gd_game_session_association_payload_labels CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND char_length(signed_at) BETWEEN 1 AND 64 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_game_session_association_payload_digests CHECK ( + game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND manifest_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_game_session_association_payload_signature CHECK ( + signature ~ '^[A-Za-z0-9+/]{86}==$' + ) +); + +INSERT INTO game_design_game_session_tenant_association_payload ( + operation_id, + schema_version, + signer_key_id, + approved_by, + approval_reference, + signed_at, + game_session_evidence_digest, + manifest_digest, + signature +) +SELECT + operation_id, + schema_version, + signer_key_id, + approved_by, + approval_reference, + signed_at, + game_session_evidence_digest, + manifest_digest, + signature +FROM game_design_game_session_tenant_association_operations; + +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN schema_version; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN signer_key_id; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN approved_by; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN approval_reference; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN signed_at; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN game_session_evidence_digest; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN manifest_digest; +ALTER TABLE game_design_game_session_tenant_association_operations + DROP COLUMN signature; + +ALTER TABLE game_design_game_session_tenant_association_operations + ADD CONSTRAINT chk_gd_game_session_association_capture_time CHECK ( + captured_at IS NULL OR captured_at <= created_at + ); +ALTER TABLE game_design_game_session_tenant_association_operations + ADD CONSTRAINT chk_gd_game_session_association_terminal_outcome CHECK ( + terminal_outcome IN ('ASSOCIATED') + ); + +CREATE TABLE game_design_game_session_tenant_association_legal_hold ( + hold_id UUID PRIMARY KEY, + operation_id UUID NOT NULL + REFERENCES game_design_game_session_tenant_association_operations(operation_id) + ON DELETE RESTRICT, + hold_scope VARCHAR(32) NOT NULL, + reason_code VARCHAR(32) NOT NULL, + case_reference VARCHAR(256) NOT NULL, + authorization_id UUID NOT NULL, + authorized_principal VARCHAR(256) NOT NULL, + authorized_at TIMESTAMPTZ NOT NULL, + review_at TIMESTAMPTZ NOT NULL, + released_at TIMESTAMPTZ, + released_by VARCHAR(256), + release_reference VARCHAR(256), + CONSTRAINT chk_gd_game_session_tenant_hold_scope CHECK (hold_scope = 'RAW_PAYLOAD'), + CONSTRAINT chk_gd_game_session_tenant_hold_reason CHECK ( + reason_code IN ('LITIGATION', 'REGULATORY', 'SECURITY_CASE') + ), + CONSTRAINT chk_gd_game_session_tenant_hold_authorization CHECK ( + hold_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND char_length(case_reference) BETWEEN 1 AND 256 + AND char_length(authorized_principal) BETWEEN 1 AND 256 + AND review_at > authorized_at + ), + CONSTRAINT chk_gd_game_session_tenant_hold_release CHECK ( + (released_at IS NULL AND released_by IS NULL AND release_reference IS NULL) + OR (released_at IS NOT NULL + AND released_by IS NOT NULL + AND release_reference IS NOT NULL + AND char_length(released_by) BETWEEN 1 AND 256 + AND char_length(release_reference) BETWEEN 1 AND 256) + ) +); + +CREATE UNIQUE INDEX uq_gd_game_session_association_active_hold + ON game_design_game_session_tenant_association_legal_hold (operation_id) + WHERE released_at IS NULL; + +CREATE INDEX ix_gd_game_session_association_payload_expiry + ON game_design_game_session_tenant_association_operations (captured_at, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION reject_unverified_gd_game_session_tenant_hold() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design retained-tenant legal holds require an authenticated owner authorization boundary' + USING ERRCODE = 'insufficient_privilege'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_hold_authentication_required + BEFORE INSERT ON game_design_game_session_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION reject_unverified_gd_game_session_tenant_hold(); + +CREATE FUNCTION guard_gd_game_session_tenant_payload_update() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design retained tenant approval payload is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_payload_immutable + BEFORE UPDATE ON game_design_game_session_tenant_association_payload + FOR EACH ROW EXECUTE FUNCTION guard_gd_game_session_tenant_payload_update(); + +CREATE FUNCTION guard_gd_game_session_tenant_payload_delete() RETURNS trigger AS $$ +BEGIN + IF OLD.operation_id IN ( + SELECT operation_id + FROM game_design_game_session_tenant_association_legal_hold + WHERE released_at IS NULL + ) THEN + RAISE EXCEPTION 'Game Design tenant approval payload is protected by an active legal hold' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM game_design_game_session_tenant_association_operations association + WHERE association.operation_id = OLD.operation_id + AND association.captured_at IS NOT NULL + AND association.captured_at > clock_timestamp() - INTERVAL '30 days' + ) THEN + RAISE EXCEPTION 'Game Design tenant approval payload has not reached its capture-based expiry' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_payload_expiry_guard + BEFORE DELETE ON game_design_game_session_tenant_association_payload + FOR EACH ROW EXECUTE FUNCTION guard_gd_game_session_tenant_payload_delete(); + +CREATE FUNCTION guard_gd_game_session_tenant_hold_update() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design tenant legal hold release requires an authenticated owner authorization boundary' + USING ERRCODE = 'insufficient_privilege'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_hold_release_only + BEFORE UPDATE ON game_design_game_session_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION guard_gd_game_session_tenant_hold_update(); + +CREATE FUNCTION guard_gd_game_session_tenant_hold_delete() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design tenant legal hold audit records require a finite policy-controlled expiry' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_hold_audit_no_delete + BEFORE DELETE ON game_design_game_session_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION guard_gd_game_session_tenant_hold_delete(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index 8d0ceb9b8a..771e1ecf28 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -101,6 +101,103 @@ void exactRetryReturnsSameSignedEvidenceWithoutMutatingSourceOrAssociation() thr assertThat(fixture.read(first)).contains(first); } + @Test + void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesImmutableAssociationClaim() + throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + UUID operationId = uuid(915); + long legacyTenantId = 915L; + GameTenantIdentity source = fixture.freshSource(); + fixture.insertExpiredAssociation(operationId, legacyTenantId, source); + fixture.insertRawPayload(operationId); + + assertThatThrownBy(() -> fixture.insertLegalHold(operationId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authenticated owner authorization boundary"); + + assertThatThrownBy(() -> fixture.insertInvalidScopeLegalHold(operationId)) + .isInstanceOf(DataAccessException.class); + UUID holdId = fixture.insertActiveLegalHold(operationId); + assertThat(fixture.repository().purgeExpiredRawPayloads()).isZero(); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM game_design_game_session_tenant_association_payload " + + "WHERE operation_id = ?", + operationId) + != null) + .isTrue(); + assertThatThrownBy(() -> fixture.releaseLegalHold(holdId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authenticated owner authorization boundary"); + fixture.releaseLegalHoldForRetentionTest(holdId); + assertThatThrownBy(() -> fixture.deleteLegalHold(holdId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("finite policy-controlled expiry"); + assertThat(fixture.repository().purgeExpiredRawPayloads()).isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM game_design_game_session_tenant_association_payload " + + "WHERE operation_id = ?", + operationId) + != null) + .isFalse(); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM game_design_game_session_tenant_association_operations " + + "WHERE operation_id = ? AND captured_at IS NOT NULL", + operationId) + != null) + .isTrue(); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM game_design_game_session_tenant_association_legal_hold " + + "WHERE hold_id = ? AND operation_id = ? AND hold_scope = 'RAW_PAYLOAD' " + + "AND reason_code = 'REGULATORY' AND released_at IS NOT NULL " + + "AND released_by = 'fixture-authenticated-owner' " + + "AND release_reference = 'release-case-915'", + holdId, + operationId) + != null) + .isTrue(); + assertThatThrownBy( + () -> + fixture + .repository() + .read(operationId, source.canonicalTenantId(), legacyTenantId, NAMESPACE)) + .isInstanceOf( + GameSessionTenantAssociationRepository.InvalidAssociationEvidenceException.class); + fixture.insertRawPayload(operationId); + assertThatThrownBy( + () -> + fixture + .repository() + .read(operationId, source.canonicalTenantId(), legacyTenantId, NAMESPACE)) + .isInstanceOf( + GameSessionTenantAssociationRepository.InvalidAssociationEvidenceException.class) + .hasMessageContaining("expired"); + assertThat(fixture.repository().purgeExpiredRawPayloads()).isEqualTo(1); + assertThatThrownBy(() -> fixture.insertLegalHold(operationId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authenticated owner authorization boundary"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_game_session_tenant_association_operations " + + "WHERE operation_id = ?", + operationId)) + .isInstanceOf(DataAccessException.class); + } + @Test void changedSignedFieldUnderSameOperationConflictsWithoutReplacingReceipt() throws Exception { Fixture fixture = fixtureWithFreshAndRetainedSources(); @@ -469,11 +566,13 @@ private GameSessionTenantAssociationEvidence withApprovalReference( original.approvedBy(), approvalReference, original.signedAt(), + original.sourceCapturedAt(), original.legacyGameSessionTenantId(), original.canonicalTenantId(), original.sourceGameRowId(), original.sourceGameTenantKey(), original.provenanceKind(), + original.gameSessionProjectionDigest(), original.gameSessionEvidenceDigest()); } @@ -501,6 +600,134 @@ private record Fixture( Map trustedKeys, GameTenantIdentity retainedSource, GameTenantIdentity freshSource) { + void insertExpiredAssociation( + UUID operationId, long legacyTenantId, GameTenantIdentity source) { + dsl() + .execute( + "INSERT INTO game_design_game_session_tenant_association_operations (" + + "operation_id, target_namespace, legacy_game_session_tenant_id, " + + "canonical_tenant_id, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, captured_at, terminal_outcome) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, clock_timestamp() - INTERVAL '31 days', 'ASSOCIATED')", + operationId, + NAMESPACE, + legacyTenantId, + source.canonicalTenantId(), + source.sourceGameId(), + source.sourceLegacyTenantId(), + source.provenanceKind().name()); + } + + void insertRawPayload(UUID operationId) { + dsl() + .execute( + "INSERT INTO game_design_game_session_tenant_association_payload (" + + "operation_id, schema_version, signer_key_id, approved_by, approval_reference, " + + "signed_at, game_session_projection_digest, game_session_evidence_digest, " + + "manifest_digest, signature) VALUES (?, 2, 'owner-key', 'owner', 'case', ?, ?, ?, ?, ?)", + operationId, + java.time.Instant.now().toString(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + Base64.getEncoder().encodeToString(new byte[64])); + } + + void insertLegalHold(UUID operationId) { + dsl() + .execute( + "INSERT INTO game_design_game_session_tenant_association_legal_hold (" + + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + + "authorization_id, authorized_principal, authorized_at, review_at) " + + "VALUES (?, ?, 'RAW_PAYLOAD', 'REGULATORY', 'case-2026-002', ?, " + + "'owner-admin', clock_timestamp(), clock_timestamp() + INTERVAL '30 days')", + UUID.randomUUID(), + operationId, + UUID.randomUUID()); + } + + UUID insertActiveLegalHold(UUID operationId) { + UUID holdId = UUID.randomUUID(); + // Seed governed state only to prove expiry blockers; application writes remain denied. + withHoldInsertTriggerDisabled( + () -> + dsl() + .execute( + "INSERT INTO game_design_game_session_tenant_association_legal_hold (" + + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + + "authorization_id, authorized_principal, authorized_at, review_at) " + + "VALUES (?, ?, 'RAW_PAYLOAD', 'REGULATORY', 'test-case-915', ?, " + + "'fixture-authenticated-owner', clock_timestamp() - INTERVAL '2 days', " + + "clock_timestamp() + INTERVAL '30 days')", + holdId, + operationId, + UUID.randomUUID())); + return holdId; + } + + void insertInvalidScopeLegalHold(UUID operationId) { + withHoldInsertTriggerDisabled( + () -> + dsl() + .execute( + "INSERT INTO game_design_game_session_tenant_association_legal_hold (" + + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + + "authorization_id, authorized_principal, authorized_at, review_at) " + + "VALUES (?, ?, 'ACCOUNT_MAPPING', 'REGULATORY', 'bad-scope', ?, " + + "'fixture-authenticated-owner', clock_timestamp(), " + + "clock_timestamp() + INTERVAL '30 days')", + UUID.randomUUID(), + operationId, + UUID.randomUUID())); + } + + void releaseLegalHold(UUID holdId) { + dsl() + .execute( + "UPDATE game_design_game_session_tenant_association_legal_hold " + + "SET released_at = clock_timestamp(), released_by = 'fixture-authenticated-owner', " + + "release_reference = 'release-case-915' WHERE hold_id = ?", + holdId); + } + + void deleteLegalHold(UUID holdId) { + dsl() + .execute( + "DELETE FROM game_design_game_session_tenant_association_legal_hold WHERE hold_id = ?", + holdId); + } + + void releaseLegalHoldForRetentionTest(UUID holdId) { + // This fixture bypasses auth solely to prove release-triggered raw erasure. + dsl() + .execute( + "ALTER TABLE game_design_game_session_tenant_association_legal_hold " + + "DISABLE TRIGGER gd_game_session_tenant_hold_release_only"); + try { + releaseLegalHold(holdId); + } finally { + dsl() + .execute( + "ALTER TABLE game_design_game_session_tenant_association_legal_hold " + + "ENABLE TRIGGER gd_game_session_tenant_hold_release_only"); + } + } + + private void withHoldInsertTriggerDisabled(Runnable insert) { + dsl() + .execute( + "ALTER TABLE game_design_game_session_tenant_association_legal_hold " + + "DISABLE TRIGGER gd_game_session_tenant_hold_authentication_required"); + try { + insert.run(); + } finally { + dsl() + .execute( + "ALTER TABLE game_design_game_session_tenant_association_legal_hold " + + "ENABLE TRIGGER gd_game_session_tenant_hold_authentication_required"); + } + } + Signed signed(GameTenantIdentity source, long retainedGameSessionTenantId, UUID operationId) throws Exception { return sign( @@ -520,19 +747,22 @@ GameSessionTenantAssociationEvidence evidence( long sourceGameRowId, String sourceGameTenantKey, String provenanceKind) { + java.time.Instant sourceCapturedAt = java.time.Instant.now().minusSeconds(2); return new GameSessionTenantAssociationEvidence( - 1, + 2, operationId, NAMESPACE, SIGNER_KEY_ID, "approved-owner@example.test", "retained-session-audit-" + operationId, - "2026-10-01T00:00:00Z", + sourceCapturedAt.plusSeconds(1).toString(), + sourceCapturedAt.toString(), Long.toString(retainedGameSessionTenantId), canonicalTenantId, Long.toString(sourceGameRowId), sourceGameTenantKey, provenanceKind, + "sha256:" + "b".repeat(64), GAME_SESSION_EVIDENCE_DIGEST); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java index 4bf2023132..e9a9237b9c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java @@ -51,7 +51,7 @@ void everyMutableManifestFieldIsSignatureBound() throws Exception { .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("signature is invalid"); } - assertThatThrownBy(() -> copyWithSchemaVersion(manifest, 2)) + assertThatThrownBy(() -> copyWithSchemaVersion(manifest, 1)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("schema version"); } @@ -181,18 +181,20 @@ private static byte[] bytesAfterFirstLengthFramedSegment(byte[] source) { private static GameSessionTenantAssociationEvidence evidence() { return new GameSessionTenantAssociationEvidence( - 1, + 2, UUID.fromString("11111111-1111-4111-8111-111111111111"), "firemud", "owner-key-2026", "owner 🧙", "review café-🐉", Instant.parse("2026-10-01T00:00:00Z").toString(), + Instant.parse("2026-09-30T00:00:00Z").toString(), "9007199254740993", UUID.fromString("22222222-2222-4222-8222-222222222222"), "42", "legacy-game-key-42", "RETAINED_GAME_V29", + "sha256:" + "b".repeat(64), "sha256:" + "a".repeat(64)); } @@ -205,6 +207,7 @@ private static java.util.List changedField copyWithApproval(source, "another owner", source.approvalReference()), copyWithApproval(source, source.approvedBy(), "another-review-reference"), copyWithSignedAt(source, "2026-10-01T00:00:01Z"), + copyWithSourceCapturedAt(source, "2026-09-29T00:00:00Z"), copyWithOperationId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), copyWithTenantId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), copy(source, source.legacyGameSessionTenantId(), "43"), @@ -459,14 +462,36 @@ private static GameSessionTenantAssociationEvidence make( approvedBy, approvalReference, signedAt, + source.sourceCapturedAt(), legacyGameSessionTenantId, canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind, + source.gameSessionProjectionDigest(), gameSessionEvidenceDigest); } + private static GameSessionTenantAssociationEvidence copyWithSourceCapturedAt( + GameSessionTenantAssociationEvidence source, String sourceCapturedAt) { + return new GameSessionTenantAssociationEvidence( + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + sourceCapturedAt, + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionProjectionDigest(), + source.gameSessionEvidenceDigest()); + } + private static GameSessionTenantAssociationEvidence copyWithProvenance( GameSessionTenantAssociationEvidence source, String provenanceKind) { return copyWithProvenanceKind(source, provenanceKind); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJobTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJobTest.java new file mode 100644 index 0000000000..a01d83afc5 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJobTest.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class GameSessionTenantAssociationPayloadRetentionJobTest { + private final GameSessionTenantAssociationRepository repository = + Mockito.mock(GameSessionTenantAssociationRepository.class); + private final GameSessionTenantAssociationPayloadRetentionJob job = + new GameSessionTenantAssociationPayloadRetentionJob(repository); + + @Test + void failedCleanupBatchIsRetriedOnTheNextScheduledInvocation() { + when(repository.purgeExpiredRawPayloads()) + .thenThrow(new IllegalStateException("temporary cleanup failure")) + .thenReturn(1); + + assertThatThrownBy(job::purgeExpiredPayloadBatch) + .isInstanceOf(IllegalStateException.class) + .hasMessage("temporary cleanup failure"); + job.purgeExpiredPayloadBatch(); + + verify(repository, times(2)).purgeExpiredRawPayloads(); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java index 2188800ad1..46a24f8ea7 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java @@ -110,13 +110,14 @@ void exactReadCarriesCompleteImmutableManifestAndSeparateReadEcho() { assertThat(observer.completed).isTrue(); assertThat(observer.value.getRequestId()).isEqualTo(READ_REQUEST); var manifest = observer.value.getManifest(); - assertThat(manifest.getSchemaVersion()).isEqualTo(1); + assertThat(manifest.getSchemaVersion()).isEqualTo(2); assertThat(manifest.getOperationId()).isEqualTo(OPERATION.toString()); assertThat(manifest.getTargetNamespace()).isEqualTo("test"); assertThat(manifest.getSignerKeyId()).isEqualTo(evidence.signerKeyId()); assertThat(manifest.getApprovedBy()).isEqualTo(evidence.approvedBy()); assertThat(manifest.getApprovalReference()).isEqualTo(evidence.approvalReference()); assertThat(manifest.getSignedAt()).isEqualTo(evidence.signedAt()); + assertThat(manifest.getSourceCapturedAt()).isEqualTo(evidence.sourceCapturedAt()); assertThat(manifest.getLegacyGameSessionTenantId()).isEqualTo("41"); assertThat(manifest.getCanonicalTenantId()).isEqualTo(TENANT.toString()); assertThat(manifest.getSourceGameRowId()).isEqualTo(evidence.sourceGameRowId()); @@ -124,6 +125,8 @@ void exactReadCarriesCompleteImmutableManifestAndSeparateReadEcho() { assertThat(manifest.getProvenanceKind()).isEqualTo(evidence.provenanceKind()); assertThat(manifest.getGameSessionEvidenceDigest()) .isEqualTo(evidence.gameSessionEvidenceDigest()); + assertThat(manifest.getGameSessionProjectionDigest()) + .isEqualTo(evidence.gameSessionProjectionDigest()); assertThat(observer.value.getManifestDigest()).isEqualTo(evidence.manifestDigest()); assertThat(observer.value.getEd25519Signature()).isEqualTo(signature); } @@ -196,18 +199,20 @@ private ResolveLegacyGameSessionTenantAssociationRequest request() { private GameSessionTenantAssociationEvidence evidence() { return new GameSessionTenantAssociationEvidence( - 1, + 2, OPERATION, "test", "owner-key", "owner", "approval-41", "2026-10-01T00:00:00Z", + "2026-09-30T00:00:00Z", "41", TENANT, "7", "source-key", "RETAINED_GAME_V29", + "sha256:" + "b".repeat(64), "sha256:" + "a".repeat(64)); } @@ -222,11 +227,13 @@ private GameSessionTenantAssociationEvidence withScope( source.approvedBy(), source.approvalReference(), source.signedAt(), + source.sourceCapturedAt(), legacyKey, tenant, source.sourceGameRowId(), source.sourceGameTenantKey(), source.provenanceKind(), + source.gameSessionProjectionDigest(), source.gameSessionEvidenceDigest()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java index 6e76306598..0fcfddcdbd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java @@ -200,12 +200,14 @@ public LegacyGameSessionTenantAssociationReceipt resolveLegacyGameSessionTenantA manifest.getApprovedBy(), manifest.getApprovalReference(), manifest.getSignedAt(), + manifest.getSourceCapturedAt(), manifest.getLegacyGameSessionTenantId(), parseCanonicalNonNilUuid( manifest.getCanonicalTenantId(), "manifest canonical tenant ID"), manifest.getSourceGameRowId(), manifest.getSourceGameTenantKey(), manifest.getProvenanceKind(), + manifest.getGameSessionProjectionDigest(), manifest.getGameSessionEvidenceDigest()); } catch (IllegalArgumentException exception) { throw new IllegalStateException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java index c68a76c97e..75b4cc0129 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java @@ -5,6 +5,9 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.Base64; import java.util.HexFormat; import java.util.Objects; @@ -16,6 +19,7 @@ import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; +import org.jooq.SelectJoinStep; import org.jooq.Table; import org.jooq.impl.DSL; import org.springframework.transaction.annotation.Propagation; @@ -35,7 +39,7 @@ "Owner collaborators and namespace are validated before use; construction performs no" + " database or network I/O and the caller explicitly owns local activation.") public class GameSessionRetainedTenantAssociationRepository { - private static final int SCHEMA_VERSION = 1; + private static final int SCHEMA_VERSION = 2; private static final int SIGNATURE_BYTES = 64; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String REQUEST_DOMAIN = @@ -45,23 +49,26 @@ public class GameSessionRetainedTenantAssociationRepository { private static final Table ASSOCIATION = DSL.table(DSL.name("game_session_retained_tenant_association")); + private static final Table ASSOCIATION_PAYLOAD = + DSL.table(DSL.name("game_session_retained_tenant_association_payload")); private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field ASSOCIATION_OPERATION_ID = + DSL.field(DSL.name("game_session_retained_tenant_association", "operation_id"), UUID.class); + private static final Field PAYLOAD_OPERATION_ID = payloadField("operation_id", UUID.class); private static final Field APPROVAL_SCHEMA_VERSION = - DSL.field(DSL.name("approval_schema_version"), Integer.class); + payloadField("approval_schema_version", Integer.class); private static final Field TARGET_NAMESPACE = DSL.field(DSL.name("target_namespace"), String.class); private static final Field ASSOCIATION_REQUEST_ID = DSL.field(DSL.name("association_request_id"), UUID.class); - private static final Field REQUEST_DIGEST = - DSL.field(DSL.name("request_digest"), String.class); + private static final Field REQUEST_DIGEST = payloadField("request_digest", String.class); private static final Field APPROVAL_OPERATION_ID = - DSL.field(DSL.name("approval_operation_id"), UUID.class); - private static final Field SIGNER_KEY_ID = - DSL.field(DSL.name("signer_key_id"), String.class); - private static final Field APPROVED_BY = DSL.field(DSL.name("approved_by"), String.class); + payloadField("approval_operation_id", UUID.class); + private static final Field SIGNER_KEY_ID = payloadField("signer_key_id", String.class); + private static final Field APPROVED_BY = payloadField("approved_by", String.class); private static final Field APPROVAL_REFERENCE = - DSL.field(DSL.name("approval_reference"), String.class); - private static final Field SIGNED_AT = DSL.field(DSL.name("signed_at"), String.class); + payloadField("approval_reference", String.class); + private static final Field SIGNED_AT = payloadField("signed_at", String.class); private static final Field LEGACY_GAME_SESSION_TENANT_ID = DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class); private static final Field CANONICAL_TENANT_ID = @@ -72,18 +79,23 @@ public class GameSessionRetainedTenantAssociationRepository { DSL.field(DSL.name("source_game_tenant_key"), String.class); private static final Field PROVENANCE_KIND = DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field CAPTURED_AT = + DSL.field(DSL.name("captured_at"), OffsetDateTime.class); + private static final Field TERMINAL_OUTCOME = + DSL.field(DSL.name("terminal_outcome"), String.class); private static final Field GAME_SESSION_EVIDENCE_DIGEST = - DSL.field(DSL.name("game_session_evidence_digest"), String.class); + payloadField("game_session_evidence_digest", String.class); + private static final Field GAME_SESSION_PROJECTION_DIGEST = + payloadField("game_session_projection_digest", String.class); private static final Field APPROVAL_MANIFEST_DIGEST = - DSL.field(DSL.name("approval_manifest_digest"), String.class); + payloadField("approval_manifest_digest", String.class); private static final Field APPROVAL_SIGNATURE = - DSL.field(DSL.name("approval_signature"), String.class); + payloadField("approval_signature", String.class); private static final Field SNAPSHOT_CANONICAL_JSON = - DSL.field(DSL.name("snapshot_canonical_json"), String.class); + payloadField("snapshot_canonical_json", String.class); private static final Field SNAPSHOT_EVIDENCE_DIGEST = - DSL.field(DSL.name("snapshot_evidence_digest"), String.class); - private static final Field RECEIPT_DIGEST = - DSL.field(DSL.name("receipt_digest"), String.class); + payloadField("snapshot_evidence_digest", String.class); + private static final Field RECEIPT_DIGEST = payloadField("receipt_digest", String.class); private final DSLContext dsl; private final GameSessionRetainedTenantSnapshotRepository snapshotRepository; @@ -131,42 +143,68 @@ public AssociationReceipt register( GameSessionRetainedTenantSnapshot snapshot = snapshotRepository.capture(workloadNamespace, evidence.legacyGameSessionTenantId()); - requireSnapshotMatchesApproval(snapshot, evidence); + requireCaptureStillUsable(evidence.sourceCapturedAt()); + GameSessionRetainedTenantSnapshot sourceBoundSnapshot = + snapshot.withCapturedAt(evidence.sourceCapturedAt()); + requireSnapshotMatchesApproval(snapshot, sourceBoundSnapshot, evidence); UUID localOperationId = UUID.randomUUID(); String receiptDigest = receiptDigest( - localOperationId, requestDigest, approval.manifestDigest(), snapshot.evidenceDigest()); + localOperationId, + requestDigest, + approval.manifestDigest(), + sourceBoundSnapshot.evidenceDigest()); int inserted = dsl.insertInto(ASSOCIATION) .set(OPERATION_ID, localOperationId) - .set(APPROVAL_SCHEMA_VERSION, evidence.schemaVersion()) .set(TARGET_NAMESPACE, workloadNamespace) .set(ASSOCIATION_REQUEST_ID, associationRequestId) - .set(REQUEST_DIGEST, requestDigest) - .set(APPROVAL_OPERATION_ID, evidence.operationId()) - .set(SIGNER_KEY_ID, evidence.signerKeyId()) - .set(APPROVED_BY, evidence.approvedBy()) - .set(APPROVAL_REFERENCE, evidence.approvalReference()) - .set(SIGNED_AT, evidence.signedAt()) .set(LEGACY_GAME_SESSION_TENANT_ID, evidence.legacyGameSessionTenantIdValue()) .set(CANONICAL_TENANT_ID, evidence.canonicalTenantId()) .set(SOURCE_GAME_ROW_ID, evidence.sourceGameRowIdValue()) .set(SOURCE_GAME_TENANT_KEY, evidence.sourceGameTenantKey()) .set(PROVENANCE_KIND, evidence.provenanceKind()) - .set(GAME_SESSION_EVIDENCE_DIGEST, evidence.gameSessionEvidenceDigest()) - .set(APPROVAL_MANIFEST_DIGEST, approval.manifestDigest()) - .set(APPROVAL_SIGNATURE, approval.signature()) - .set(SNAPSHOT_CANONICAL_JSON, snapshot.canonicalJson()) - .set(SNAPSHOT_EVIDENCE_DIGEST, snapshot.evidenceDigest()) - .set(RECEIPT_DIGEST, receiptDigest) + .set( + CAPTURED_AT, + OffsetDateTime.ofInstant( + Instant.parse(evidence.sourceCapturedAt()), ZoneOffset.UTC)) + .set(TERMINAL_OUTCOME, "ASSOCIATED") .onConflictDoNothing() .execute(); + Record claimed = findByOperationId(localOperationId); + if (claimed != null) { + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_payload (" + + "operation_id, request_digest, approval_operation_id, approval_schema_version, " + + "signer_key_id, approved_by, approval_reference, signed_at, " + + "game_session_projection_digest, game_session_evidence_digest, " + + "approval_manifest_digest, approval_signature, snapshot_canonical_json, " + + "snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + localOperationId, + requestDigest, + evidence.operationId(), + evidence.schemaVersion(), + evidence.signerKeyId(), + evidence.approvedBy(), + evidence.approvalReference(), + evidence.signedAt(), + evidence.gameSessionProjectionDigest(), + evidence.gameSessionEvidenceDigest(), + approval.manifestDigest(), + approval.signature(), + sourceBoundSnapshot.canonicalJson(), + sourceBoundSnapshot.evidenceDigest(), + receiptDigest); + } + Record byLocalOperation = findByOperationId(localOperationId); if (byLocalOperation != null) { AssociationReceipt stored = toValidatedReceipt(byLocalOperation); - requireExactInsertedReceipt(stored, associationRequestId, requestDigest, approval, snapshot); + requireExactInsertedReceipt( + stored, associationRequestId, requestDigest, approval, sourceBoundSnapshot); return stored; } @@ -227,6 +265,69 @@ public Optional read( return Optional.empty(); } + /** + * Reads only the immutable canonical-to-retained tenant mapping and its source provenance. This + * proof remains available after the purpose-bound snapshot and approval payload expire. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readMinimalAssociation( + String exactNamespace, UUID canonicalTenantId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained tenant identity read requires a committed owner read"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNamespace(exactNamespace); + if (!workloadNamespace.equals(exactNamespace)) { + throw new IllegalArgumentException( + "exactNamespace must match the configured Game Session workload namespace"); + } + + Record row = findByCanonicalTenant(exactNamespace, canonicalTenantId); + if (row == null) { + return Optional.empty(); + } + try { + return Optional.of( + new RetainedTenantAssociationIdentity( + exactNamespace, + canonicalTenantId, + Objects.requireNonNull(row.get(LEGACY_GAME_SESSION_TENANT_ID)), + Objects.requireNonNull(row.get(SOURCE_GAME_ROW_ID)), + Objects.requireNonNull(row.get(SOURCE_GAME_TENANT_KEY)), + Objects.requireNonNull(row.get(PROVENANCE_KIND)))); + } catch (RuntimeException exception) { + throw new InvalidAssociationEvidenceException( + "Persisted retained tenant identity is invalid", exception); + } + } + + /** Deletes one bounded batch of expired raw snapshots and approval payloads. */ + public int purgeExpiredRawPayloads() { + return purgeExpiredRawPayloads(dsl); + } + + /** Executes one bounded payload purge using the caller's owner transaction. */ + public static int purgeExpiredRawPayloads(DSLContext dsl) { + Objects.requireNonNull(dsl, "dsl must not be null"); + return dsl.execute( + "WITH expired AS (" + + " SELECT payload.operation_id" + + " FROM game_session_retained_tenant_association_payload payload" + + " JOIN game_session_retained_tenant_association association" + + " ON association.operation_id = payload.operation_id" + + " WHERE association.terminal_outcome = 'ASSOCIATED'" + + " AND (association.captured_at IS NULL" + + " OR association.captured_at <= clock_timestamp() - INTERVAL '30 days')" + + " AND NOT EXISTS (SELECT 1" + + " FROM game_session_retained_tenant_association_legal_hold hold" + + " WHERE hold.operation_id = payload.operation_id AND hold.released_at IS NULL)" + + " ORDER BY association.captured_at NULLS FIRST, payload.operation_id" + + " LIMIT 100 FOR UPDATE OF payload SKIP LOCKED" + + ") DELETE FROM game_session_retained_tenant_association_payload payload" + + " USING expired WHERE payload.operation_id = expired.operation_id"); + } + private AssociationReceipt requireExactRetry( Record row, UUID associationRequestId, @@ -263,7 +364,7 @@ private void requireExactInsertedReceipt( private AssociationReceipt toValidatedReceipt(Record row) { try { - UUID localOperationId = Objects.requireNonNull(row.get(OPERATION_ID)); + UUID localOperationId = Objects.requireNonNull(row.get(ASSOCIATION_OPERATION_ID)); UUID associationRequestId = Objects.requireNonNull(row.get(ASSOCIATION_REQUEST_ID)); String namespace = Objects.requireNonNull(row.get(TARGET_NAMESPACE)); if (!Integer.valueOf(SCHEMA_VERSION).equals(row.get(APPROVAL_SCHEMA_VERSION))) { @@ -279,12 +380,15 @@ private AssociationReceipt toValidatedReceipt(Record row) { Objects.requireNonNull(row.get(APPROVED_BY)), Objects.requireNonNull(row.get(APPROVAL_REFERENCE)), Objects.requireNonNull(row.get(SIGNED_AT)), + captureInstant(row), Long.toString(Objects.requireNonNull(row.get(LEGACY_GAME_SESSION_TENANT_ID))), Objects.requireNonNull(row.get(CANONICAL_TENANT_ID)), Long.toString(Objects.requireNonNull(row.get(SOURCE_GAME_ROW_ID))), Objects.requireNonNull(row.get(SOURCE_GAME_TENANT_KEY)), Objects.requireNonNull(row.get(PROVENANCE_KIND)), + Objects.requireNonNull(row.get(GAME_SESSION_PROJECTION_DIGEST)), Objects.requireNonNull(row.get(GAME_SESSION_EVIDENCE_DIGEST))); + requireCaptureStillUsable(evidence.sourceCapturedAt()); String manifestDigest = Objects.requireNonNull(row.get(APPROVAL_MANIFEST_DIGEST)); String signature = Objects.requireNonNull(row.get(APPROVAL_SIGNATURE)); requireSignatureShape(signature); @@ -297,9 +401,11 @@ private AssociationReceipt toValidatedReceipt(Record row) { new GameSessionRetainedTenantSnapshot( namespace, evidence.legacyGameSessionTenantId(), + evidence.sourceCapturedAt(), Objects.requireNonNull(row.get(SNAPSHOT_CANONICAL_JSON)), - Objects.requireNonNull(row.get(SNAPSHOT_EVIDENCE_DIGEST))); - requireSnapshotMatchesApproval(snapshot, evidence); + Objects.requireNonNull(row.get(SNAPSHOT_EVIDENCE_DIGEST)), + evidence.gameSessionProjectionDigest()); + requireSnapshotMatchesApproval(snapshot, snapshot, evidence); String requestDigest = Objects.requireNonNull(row.get(REQUEST_DIGEST)); if (!requestDigest.equals( @@ -350,11 +456,13 @@ private ValidatedApproval validateApproval( source.approvedBy(), source.approvalReference(), source.signedAt(), + source.sourceCapturedAt(), source.legacyGameSessionTenantId(), source.canonicalTenantId(), source.sourceGameRowId(), source.sourceGameTenantKey(), source.provenanceKind(), + source.gameSessionProjectionDigest(), source.gameSessionEvidenceDigest()); } catch (RuntimeException exception) { throw new InvalidAssociationEvidenceException( @@ -371,16 +479,32 @@ private ValidatedApproval validateApproval( } private void requireSnapshotMatchesApproval( - GameSessionRetainedTenantSnapshot snapshot, GameSessionTenantAssociationEvidence evidence) { - if (snapshot == null - || !workloadNamespace.equals(snapshot.targetNamespace()) - || !evidence.legacyGameSessionTenantId().equals(snapshot.legacyGameSessionTenantId()) - || !evidence.gameSessionEvidenceDigest().equals(snapshot.evidenceDigest())) { + GameSessionRetainedTenantSnapshot currentSnapshot, + GameSessionRetainedTenantSnapshot sourceBoundSnapshot, + GameSessionTenantAssociationEvidence evidence) { + if (currentSnapshot == null + || sourceBoundSnapshot == null + || !workloadNamespace.equals(currentSnapshot.targetNamespace()) + || !evidence.legacyGameSessionTenantId().equals(currentSnapshot.legacyGameSessionTenantId()) + || !evidence.gameSessionProjectionDigest().equals(currentSnapshot.projectionDigest()) + || !evidence.sourceCapturedAt().equals(sourceBoundSnapshot.capturedAt()) + || !evidence.gameSessionEvidenceDigest().equals(sourceBoundSnapshot.evidenceDigest())) { throw new InvalidAssociationEvidenceException( "Retained Game Session snapshot does not match the approved owner evidence"); } } + private void requireCaptureStillUsable(String capturedAt) { + Record expiry = + dsl.fetchOne( + "SELECT clock_timestamp() >= (?::timestamptz + INTERVAL '30 days') AS expired", + capturedAt); + if (expiry == null || Boolean.TRUE.equals(expiry.get("expired", Boolean.class))) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant approval payload is expired and must be recaptured"); + } + } + private void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( @@ -403,17 +527,24 @@ private void requireWritableReadCommittedOwnerTransaction() { } private Record findByOperationId(UUID operationId) { - return dsl.selectFrom(ASSOCIATION) - .where(OPERATION_ID.eq(operationId).and(TARGET_NAMESPACE.eq(workloadNamespace))) + return selectCompleteAssociation() + .where(ASSOCIATION_OPERATION_ID.eq(operationId).and(TARGET_NAMESPACE.eq(workloadNamespace))) .fetchOne(); } private Record findByRequest(String namespace, UUID requestId) { - return dsl.selectFrom(ASSOCIATION) + return selectCompleteAssociation() .where(TARGET_NAMESPACE.eq(namespace).and(ASSOCIATION_REQUEST_ID.eq(requestId))) .fetchOne(); } + private SelectJoinStep selectCompleteAssociation() { + return dsl.select(ASSOCIATION.asterisk(), ASSOCIATION_PAYLOAD.asterisk()) + .from(ASSOCIATION) + .leftJoin(ASSOCIATION_PAYLOAD) + .on(ASSOCIATION_OPERATION_ID.eq(PAYLOAD_OPERATION_ID)); + } + private Record findByCanonicalTenant(String namespace, UUID tenantId) { return dsl.selectFrom(ASSOCIATION) .where(TARGET_NAMESPACE.eq(namespace).and(CANONICAL_TENANT_ID.eq(tenantId))) @@ -432,6 +563,19 @@ private static String requestDigest( REQUEST_DOMAIN, exactNamespace, associationRequestId.toString(), manifestDigest, signature); } + private static Field payloadField(String name, Class type) { + return DSL.field(DSL.name("game_session_retained_tenant_association_payload", name), type); + } + + private static String captureInstant(Record row) { + OffsetDateTime capturedAt = row.get(CAPTURED_AT); + if (capturedAt == null) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant evidence has no authoritative source capture time"); + } + return capturedAt.toInstant().toString(); + } + private static String receiptDigest( UUID localOperationId, String requestDigest, @@ -512,6 +656,28 @@ public record AssociationReceipt( GameSessionRetainedTenantSnapshot snapshot, String receiptDigest) {} + /** Minimal immutable proof consumed by owner-local tenant identity readers. */ + public record RetainedTenantAssociationIdentity( + String targetNamespace, + UUID canonicalTenantId, + long legacyGameSessionTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + public RetainedTenantAssociationIdentity { + requireNamespace(targetNamespace); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requirePositive(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + requirePositive(sourceGameRowId, "sourceGameRowId"); + if (sourceGameTenantKey == null || sourceGameTenantKey.isBlank()) { + throw new IllegalArgumentException("sourceGameTenantKey is required"); + } + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { + throw new IllegalArgumentException("provenanceKind is not recognized"); + } + } + } + public static class AssociationConflictException extends RuntimeException { public AssociationConflictException(String message) { super(message); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java index 5c880fea9f..129eaf5422 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java @@ -11,6 +11,8 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.DateTimeException; +import java.time.Instant; import java.util.Arrays; import java.util.HexFormat; import java.util.Iterator; @@ -24,9 +26,13 @@ public record GameSessionRetainedTenantSnapshot( String targetNamespace, String legacyGameSessionTenantId, + String capturedAt, String canonicalJson, - String evidenceDigest) { - private static final String DIGEST_DOMAIN = "game-session/retained-tenant-identity-snapshot/v3"; + String evidenceDigest, + String projectionDigest) { + private static final String DIGEST_DOMAIN = "game-session/retained-tenant-identity-snapshot/v4"; + private static final String PROJECTION_DIGEST_DOMAIN = + "game-session/retained-tenant-identity-projection/v4"; private static final Pattern CANONICAL_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*|-[1-9][0-9]*)"); private static final Pattern CANONICAL_UUID = @@ -44,6 +50,7 @@ public record GameSessionRetainedTenantSnapshot( "schemaVersion", "targetNamespace", "legacyGameSessionTenantId", + "capturedAt", "instances", "pointers", "sharedNamespaces", @@ -145,32 +152,79 @@ public record GameSessionRetainedTenantSnapshot( if (evidenceDigest == null || !SHA256.matcher(evidenceDigest).matches()) { throw new IllegalArgumentException("A canonical SHA-256 digest is required"); } - validateCanonicalSnapshot(targetNamespace, legacyGameSessionTenantId, canonicalJson); + validateCanonicalSnapshot( + targetNamespace, legacyGameSessionTenantId, capturedAt, canonicalJson); String expectedDigest = digest(canonicalJson); if (!expectedDigest.equals(evidenceDigest)) { throw new IllegalArgumentException("Retained-tenant snapshot digest does not match its JSON"); } + String expectedProjectionDigest = projectionDigest(canonicalJson); + if (!expectedProjectionDigest.equals(projectionDigest)) { + throw new IllegalArgumentException( + "Retained-tenant snapshot projection digest does not match its JSON"); + } } /** Revalidates stored canonical JSON and its digest without accepting caller-built maps. */ public static GameSessionRetainedTenantSnapshot fromCanonicalJson( String targetNamespace, String legacyGameSessionTenantId, + String capturedAt, String canonicalJson, - String evidenceDigest) { + String evidenceDigest, + String projectionDigest) { return new GameSessionRetainedTenantSnapshot( - targetNamespace, legacyGameSessionTenantId, canonicalJson, evidenceDigest); + targetNamespace, + legacyGameSessionTenantId, + capturedAt, + canonicalJson, + evidenceDigest, + projectionDigest); } static GameSessionRetainedTenantSnapshot fromProjection( - String targetNamespace, String legacyGameSessionTenantId, ObjectNode projection) { + String targetNamespace, + String legacyGameSessionTenantId, + String capturedAt, + ObjectNode projection) { validateIdentity(targetNamespace, legacyGameSessionTenantId); + requireCanonicalInstant(capturedAt); if (projection == null) { throw new IllegalArgumentException("projection must not be null"); } + projection.put("capturedAt", capturedAt); String canonicalJson = canonicalize(projection); return new GameSessionRetainedTenantSnapshot( - targetNamespace, legacyGameSessionTenantId, canonicalJson, digest(canonicalJson)); + targetNamespace, + legacyGameSessionTenantId, + capturedAt, + canonicalJson, + digest(canonicalJson), + projectionDigest(canonicalJson)); + } + + /** Rebinds unchanged source rows to the timestamp authenticated by the owner approval. */ + public GameSessionRetainedTenantSnapshot withCapturedAt(String sourceCapturedAt) { + requireCanonicalInstant(sourceCapturedAt); + if (Instant.parse(sourceCapturedAt).isAfter(Instant.parse(capturedAt))) { + throw new IllegalArgumentException("Approved source capture time is in the future"); + } + try { + JsonNode parsed = JSON.readTree(canonicalJson); + ObjectNode projection = (ObjectNode) parsed; + projection.put("capturedAt", sourceCapturedAt); + String reboundJson = canonicalize(projection); + return new GameSessionRetainedTenantSnapshot( + targetNamespace, + legacyGameSessionTenantId, + sourceCapturedAt, + reboundJson, + digest(reboundJson), + projectionDigest(reboundJson)); + } catch (IOException exception) { + throw new IllegalStateException( + "Validated retained-tenant snapshot became unreadable", exception); + } } static void validateIdentity(String targetNamespace, String legacyGameSessionTenantId) { @@ -195,7 +249,11 @@ private static String canonicalize(ObjectNode projection) { } private static void validateCanonicalSnapshot( - String targetNamespace, String legacyGameSessionTenantId, String canonicalJson) { + String targetNamespace, + String legacyGameSessionTenantId, + String capturedAt, + String canonicalJson) { + requireCanonicalInstant(capturedAt); final JsonNode envelope; final byte[] canonicalBytes; try { @@ -216,11 +274,12 @@ private static void validateCanonicalSnapshot( if (schemaVersion == null || !schemaVersion.isIntegralNumber() || !schemaVersion.canConvertToInt() - || schemaVersion.intValue() != 3) { - throw new IllegalArgumentException("snapshot.schemaVersion must be integer 3"); + || schemaVersion.intValue() != 4) { + throw new IllegalArgumentException("snapshot.schemaVersion must be integer 4"); } requireExactText(object, "targetNamespace", targetNamespace, "snapshot"); requireExactText(object, "legacyGameSessionTenantId", legacyGameSessionTenantId, "snapshot"); + requireExactText(object, "capturedAt", capturedAt, "snapshot"); JsonNode instances = requireArray(object, "instances", "snapshot"); JsonNode pointers = requireArray(object, "pointers", "snapshot"); @@ -465,7 +524,7 @@ private static void requireExactFields(ObjectNode object, Set expected, String field = fields.next(); if (!expected.contains(field)) { throw new IllegalArgumentException( - path + "." + field + " is not declared by schema version 3"); + path + "." + field + " is not declared by schema version 4"); } } for (String field : expected) { @@ -519,6 +578,42 @@ private static String digest(String canonicalJson) { } } + private static String projectionDigest(String canonicalJson) { + try { + JsonNode parsed = JSON.readTree(canonicalJson); + ObjectNode projection = (ObjectNode) parsed; + projection.remove("capturedAt"); + return digestWithDomain(PROJECTION_DIGEST_DOMAIN, canonicalize(projection)); + } catch (IOException exception) { + throw new IllegalArgumentException("Retained-tenant snapshot JSON is malformed", exception); + } + } + + private static String digestWithDomain(String domain, String value) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + updateFrame(hash, domain); + updateFrame(hash, value); + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireCanonicalInstant(String value) { + if (value == null) { + throw new IllegalArgumentException("capturedAt must be canonical UTC Instant text"); + } + try { + if (!Instant.parse(value).toString().equals(value)) { + throw new IllegalArgumentException("capturedAt must be canonical UTC Instant text"); + } + } catch (DateTimeException exception) { + throw new IllegalArgumentException( + "capturedAt must be canonical UTC Instant text", exception); + } + } + private static void updateFrame(MessageDigest hash, String value) { byte[] bytes = value.getBytes(StandardCharsets.UTF_8); hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java index 38ef7824b7..e6b2da8428 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; import java.util.Objects; import java.util.UUID; import java.util.function.Function; @@ -58,8 +60,19 @@ public GameSessionRetainedTenantSnapshot capture( "Game Session retained tenant has an unresolved admission-pointer identity backfill issue"); } + Record capturedAtRow = dsl.fetchOne("SELECT clock_timestamp() AS captured_at"); + OffsetDateTime capturedAtValue = + capturedAtRow == null ? null : capturedAtRow.get("captured_at", OffsetDateTime.class); + if (capturedAtValue == null) { + throw new IllegalStateException("Database capture time is unavailable"); + } + String capturedAt = + Instant.ofEpochSecond( + capturedAtValue.toInstant().getEpochSecond(), capturedAtValue.toInstant().getNano()) + .toString(); + ObjectNode envelope = JSON.createObjectNode(); - envelope.put("schemaVersion", 3); + envelope.put("schemaVersion", 4); envelope.put("targetNamespace", targetNamespace); envelope.put("legacyGameSessionTenantId", legacyGameSessionTenantId); envelope.set("instances", readInstances(tenantId)); @@ -69,7 +82,7 @@ public GameSessionRetainedTenantSnapshot capture( envelope.set("pointerEvents", readPointerEvents(tenantId)); envelope.set("preparedUpgrades", readPreparedUpgrades(tenantId)); return GameSessionRetainedTenantSnapshot.fromProjection( - targetNamespace, legacyGameSessionTenantId, envelope); + targetNamespace, legacyGameSessionTenantId, capturedAt, envelope); } private void requireOwnerTransaction() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java index ded5ce90df..9572f94f9a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java @@ -106,11 +106,13 @@ private LegacyGameSessionTenantAssociationReceipt validateOwnerReceipt( received.approvedBy(), received.approvalReference(), received.signedAt(), + received.sourceCapturedAt(), received.legacyGameSessionTenantId(), received.canonicalTenantId(), received.sourceGameRowId(), received.sourceGameTenantKey(), received.provenanceKind(), + received.gameSessionProjectionDigest(), received.gameSessionEvidenceDigest()); } catch (RuntimeException exception) { throw new IllegalStateException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java new file mode 100644 index 0000000000..e27e3ea613 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import org.jooq.DSLContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +/** + * Gradually erases expired retained-tenant raw payloads while preserving anti-reassignment rows. + */ +@Component +@ConditionalOnProperty( + name = "firemud.retained-tenant.payload-retention.enabled", + havingValue = "true", + matchIfMissing = true) +public class GameSessionRetainedTenantPayloadRetentionJob { + private static final Logger LOG = + LoggerFactory.getLogger(GameSessionRetainedTenantPayloadRetentionJob.class); + + private final DSLContext dsl; + + public GameSessionRetainedTenantPayloadRetentionJob(DSLContext dsl) { + this.dsl = dsl; + } + + @Scheduled(fixedDelayString = "${firemud.retained-tenant.payload-retention.sweep-ms:60000}") + @Transactional + public void purgeExpiredPayloadBatch() { + int deleted = GameSessionRetainedTenantAssociationRepository.purgeExpiredRawPayloads(dsl); + if (deleted > 0) { + LOG.info("Purged {} expired retained-tenant payload(s)", deleted); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql new file mode 100644 index 0000000000..4a7e1b1ba9 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql @@ -0,0 +1,257 @@ +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_schema; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_approval_labels; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_signed_at; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_operation_ids; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_digests; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_signature; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_snapshot; + +ALTER TABLE game_session_retained_tenant_association + ADD COLUMN captured_at TIMESTAMPTZ; +ALTER TABLE game_session_retained_tenant_association + ADD COLUMN terminal_outcome VARCHAR(32) NOT NULL DEFAULT 'ASSOCIATED'; + +CREATE TABLE game_session_retained_tenant_association_payload ( + operation_id UUID PRIMARY KEY + REFERENCES game_session_retained_tenant_association(operation_id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL, + approval_operation_id UUID NOT NULL, + approval_schema_version INTEGER NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + game_session_projection_digest VARCHAR(71), + game_session_evidence_digest VARCHAR(71) NOT NULL, + approval_manifest_digest VARCHAR(71) NOT NULL, + approval_signature VARCHAR(88) NOT NULL, + snapshot_canonical_json TEXT NOT NULL, + snapshot_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chk_gs_retained_tenant_association_payload_schema + CHECK (approval_schema_version IN (1, 2)), + CONSTRAINT chk_gs_retained_tenant_association_payload_capture CHECK ( + (approval_schema_version = 1 AND game_session_projection_digest IS NULL) + OR (approval_schema_version = 2 + AND game_session_projection_digest ~ '^sha256:[0-9a-f]{64}$') + ), + CONSTRAINT chk_gs_retained_tenant_association_payload_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND approval_manifest_digest ~ '^sha256:[0-9a-f]{64}$' + AND snapshot_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gs_retained_tenant_association_payload_signature CHECK ( + approval_signature ~ '^[A-Za-z0-9+/]{86}==$' + ), + CONSTRAINT chk_gs_retained_tenant_association_payload_text CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND char_length(signed_at) BETWEEN 1 AND 64 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ) +); + +INSERT INTO game_session_retained_tenant_association_payload ( + operation_id, + request_digest, + approval_operation_id, + approval_schema_version, + signer_key_id, + approved_by, + approval_reference, + signed_at, + game_session_evidence_digest, + approval_manifest_digest, + approval_signature, + snapshot_canonical_json, + snapshot_evidence_digest, + receipt_digest +) +SELECT + operation_id, + request_digest, + approval_operation_id, + approval_schema_version, + signer_key_id, + approved_by, + approval_reference, + signed_at, + game_session_evidence_digest, + approval_manifest_digest, + approval_signature, + snapshot_canonical_json, + snapshot_evidence_digest, + receipt_digest +FROM game_session_retained_tenant_association; + +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_schema_version; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN request_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_operation_id; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN signer_key_id; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approved_by; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_reference; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN signed_at; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN game_session_evidence_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_manifest_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_signature; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN snapshot_canonical_json; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN snapshot_evidence_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN receipt_digest; + +ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT chk_gs_retained_tenant_association_capture_time CHECK ( + captured_at IS NULL OR captured_at <= created_at + ); +ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT chk_gs_retained_tenant_association_terminal_outcome CHECK ( + terminal_outcome IN ('ASSOCIATED') + ); + +CREATE TABLE game_session_retained_tenant_association_legal_hold ( + hold_id UUID PRIMARY KEY, + operation_id UUID NOT NULL + REFERENCES game_session_retained_tenant_association(operation_id) ON DELETE RESTRICT, + hold_scope VARCHAR(32) NOT NULL, + reason_code VARCHAR(32) NOT NULL, + case_reference VARCHAR(256) NOT NULL, + authorization_id UUID NOT NULL, + authorized_principal VARCHAR(256) NOT NULL, + authorized_at TIMESTAMPTZ NOT NULL, + review_at TIMESTAMPTZ NOT NULL, + released_at TIMESTAMPTZ, + released_by VARCHAR(256), + release_reference VARCHAR(256), + CONSTRAINT chk_gs_retained_tenant_hold_scope CHECK (hold_scope = 'RAW_PAYLOAD'), + CONSTRAINT chk_gs_retained_tenant_hold_reason CHECK ( + reason_code IN ('LITIGATION', 'REGULATORY', 'SECURITY_CASE') + ), + CONSTRAINT chk_gs_retained_tenant_hold_authorization CHECK ( + hold_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND char_length(case_reference) BETWEEN 1 AND 256 + AND char_length(authorized_principal) BETWEEN 1 AND 256 + AND review_at > authorized_at + ), + CONSTRAINT chk_gs_retained_tenant_hold_release CHECK ( + (released_at IS NULL AND released_by IS NULL AND release_reference IS NULL) + OR (released_at IS NOT NULL + AND released_by IS NOT NULL + AND release_reference IS NOT NULL + AND char_length(released_by) BETWEEN 1 AND 256 + AND char_length(release_reference) BETWEEN 1 AND 256) + ) +); + +CREATE UNIQUE INDEX uq_gs_retained_tenant_association_active_hold + ON game_session_retained_tenant_association_legal_hold (operation_id) + WHERE released_at IS NULL; + +CREATE INDEX ix_gs_retained_tenant_association_payload_expiry + ON game_session_retained_tenant_association (captured_at, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION reject_unverified_game_session_retained_tenant_hold() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained-tenant legal holds require an authenticated owner authorization boundary' + USING ERRCODE = 'insufficient_privilege'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_hold_authentication_required + BEFORE INSERT ON game_session_retained_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION reject_unverified_game_session_retained_tenant_hold(); + +CREATE FUNCTION guard_game_session_retained_tenant_payload_update() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained tenant payload is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_payload_immutable + BEFORE UPDATE ON game_session_retained_tenant_association_payload + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_payload_update(); + +CREATE FUNCTION guard_game_session_retained_tenant_payload_delete() RETURNS trigger AS $$ +BEGIN + IF OLD.operation_id IN ( + SELECT operation_id + FROM game_session_retained_tenant_association_legal_hold + WHERE released_at IS NULL + ) THEN + RAISE EXCEPTION 'Game Session retained tenant payload is protected by an active legal hold' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association association + WHERE association.operation_id = OLD.operation_id + AND association.captured_at IS NOT NULL + AND association.captured_at > clock_timestamp() - INTERVAL '30 days' + ) THEN + RAISE EXCEPTION 'Game Session retained tenant payload has not reached its capture-based expiry' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_payload_expiry_guard + BEFORE DELETE ON game_session_retained_tenant_association_payload + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_payload_delete(); + +CREATE FUNCTION guard_game_session_retained_tenant_hold_update() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant legal hold release requires an authenticated owner authorization boundary' + USING ERRCODE = 'insufficient_privilege'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_hold_release_only + BEFORE UPDATE ON game_session_retained_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_hold_update(); + +CREATE FUNCTION guard_game_session_retained_tenant_hold_delete() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant legal hold audit records require a finite policy-controlled expiry' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_hold_audit_no_delete + BEFORE DELETE ON game_session_retained_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_hold_delete(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index d98cbbd3c7..143cdf41f2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -135,6 +135,119 @@ void committedReadRejectsForeignNamespaceBeforeDatabaseAccess() { verifyNoInteractions(dsl, snapshots); } + @Test + void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesMinimalAntiReassignmentProof() { + Fixture fixture = fixture(); + UUID heldOperation = uuid(920); + UUID releasedOperation = uuid(921); + UUID heldCanonical = uuid(922); + UUID releasedCanonical = uuid(923); + fixture.insertExpiredMapping(heldOperation, uuid(924), heldCanonical, 920L); + fixture.insertExpiredMapping(releasedOperation, uuid(925), releasedCanonical, 921L); + + assertThatThrownBy(() -> fixture.insertHold(heldOperation, "ACCOUNT_MAPPING")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authenticated owner authorization boundary"); + assertThatThrownBy(() -> fixture.insertHold(heldOperation, "RAW_PAYLOAD")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authenticated owner authorization boundary"); + assertThatThrownBy(() -> fixture.insertInvalidScopeHold(heldOperation)) + .isInstanceOf(DataAccessException.class); + UUID activeHoldId = fixture.insertActiveHold(heldOperation, uuid(926)); + UUID releasedHoldId = fixture.insertActiveHold(releasedOperation, uuid(927)); + assertThatThrownBy(() -> fixture.releaseHold(releasedHoldId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("authenticated owner authorization boundary"); + fixture.releaseHoldForRetentionTest(releasedHoldId); + assertThatThrownBy(() -> fixture.deleteHold(releasedHoldId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("finite policy-controlled expiry"); + + assertThat(fixture.repository.purgeExpiredRawPayloads()).isEqualTo(1); + assertThat(fixture.payloadExists(releasedOperation)).isFalse(); + assertThat(fixture.payloadExists(heldOperation)).isTrue(); + assertThat( + fixture.dsl.fetchOne( + "SELECT 1 FROM game_session_retained_tenant_association_legal_hold " + + "WHERE hold_id = ? AND operation_id = ? " + + "AND hold_scope = 'RAW_PAYLOAD' AND reason_code = 'LITIGATION' " + + "AND released_at IS NOT NULL " + + "AND released_by = 'fixture-authenticated-owner' " + + "AND release_reference = 'release-927'", + releasedHoldId, + releasedOperation) + != null) + .isTrue(); + assertThat(fixture.repository.purgeExpiredRawPayloads()).isZero(); + fixture.releaseHoldForRetentionTest(activeHoldId); + assertThat(fixture.repository.purgeExpiredRawPayloads()).isEqualTo(1); + assertThat(fixture.payloadExists(heldOperation)).isFalse(); + assertThat( + fixture.dsl.fetchOne( + "SELECT 1 FROM game_session_retained_tenant_association_legal_hold " + + "WHERE hold_id = ? AND operation_id = ? " + + "AND released_at IS NOT NULL AND release_reference = 'release-927'", + activeHoldId, + heldOperation) + != null) + .isTrue(); + assertThat(fixture.repository.readMinimalAssociation(NAMESPACE, heldCanonical)) + .hasValueSatisfying( + identity -> { + assertThat(identity.canonicalTenantId()).isEqualTo(heldCanonical); + assertThat(identity.legacyGameSessionTenantId()).isEqualTo(920L); + assertThat(identity.sourceGameRowId()).isEqualTo(501L); + assertThat(identity.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + }); + assertThat(fixture.repository.readMinimalAssociation(NAMESPACE, releasedCanonical)) + .hasValueSatisfying( + identity -> assertThat(identity.legacyGameSessionTenantId()).isEqualTo(921L)); + assertThatThrownBy( + () -> fixture.repository.read(heldOperation, uuid(924), heldCanonical, 920L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + GameSessionRetainedTenantSnapshot staleCapture = + fixture + .capture(920L) + .withCapturedAt( + java.time.Instant.now().minus(java.time.Duration.ofDays(31)).toString()); + LegacyGameSessionTenantAssociationReceipt staleRetry = + fixture.approval(uuid(928), heldCanonical, 920L, staleCapture); + assertThatThrownBy(() -> fixture.register(uuid(924), staleRetry)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThat(fixture.payloadExists(heldOperation)).isFalse(); + fixture.restoreExpiredPayload(releasedOperation); + assertThatThrownBy( + () -> + fixture.repository.read( + releasedOperation, uuid(925), releasedCanonical, 921L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("expired"); + assertThat(fixture.repository.purgeExpiredRawPayloads()).isEqualTo(1); + assertThat(fixture.repository.readMinimalAssociation(NAMESPACE, uuid(926))).isEmpty(); + } + + @Test + void expiredUnverifiedApprovalCannotBeRegisteredAndRequiresFreshCapture() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + GameSessionRetainedTenantSnapshot current = fixture.capture(42L); + GameSessionRetainedTenantSnapshot expired = + current.withCapturedAt( + java.time.Instant.now().minus(java.time.Duration.ofDays(31)).toString()); + LegacyGameSessionTenantAssociationReceipt oldApproval = + fixture.approval(uuid(930), uuid(931), 42L, expired); + + assertThatThrownBy(() -> fixture.register(uuid(932), oldApproval)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("expired"); + assertThat(fixture.storedRequestCount(uuid(932))).isZero(); + + GameSessionRetainedTenantSnapshot recaptured = fixture.capture(42L); + LegacyGameSessionTenantAssociationReceipt freshApproval = + fixture.approval(uuid(933), uuid(931), 42L, recaptured); + assertThat(fixture.register(uuid(934), freshApproval).snapshot()).isEqualTo(recaptured); + } + @Test void changedRequestAndOneToOneClaimConflictsLeaveNoPartialRows() { Fixture fixture = fixture(); @@ -503,6 +616,145 @@ private record Fixture( GameSessionRetainedTenantSnapshotRepository snapshotRepository, GameSessionRetainedTenantAssociationRepository repository, TransactionTemplate transactions) { + void insertExpiredMapping( + UUID operationId, UUID requestId, UUID canonicalTenantId, long legacyTenantId) { + dsl.execute( + "INSERT INTO game_session_retained_tenant_association (" + + "operation_id, target_namespace, association_request_id, " + + "legacy_game_session_tenant_id, canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, captured_at, terminal_outcome) " + + "VALUES (?, ?, ?, ?, ?, 501, 'source-game-501', 'RETAINED_GAME_V29', " + + "clock_timestamp() - INTERVAL '31 days', 'ASSOCIATED')", + operationId, + NAMESPACE, + requestId, + legacyTenantId, + canonicalTenantId); + insertExpiredPayload(operationId); + } + + void restoreExpiredPayload(UUID operationId) { + insertExpiredPayload(operationId); + } + + private void insertExpiredPayload(UUID operationId) { + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_payload (" + + "operation_id, request_digest, approval_operation_id, approval_schema_version, " + + "signer_key_id, approved_by, approval_reference, signed_at, " + + "game_session_projection_digest, game_session_evidence_digest, " + + "approval_manifest_digest, approval_signature, snapshot_canonical_json, " + + "snapshot_evidence_digest, receipt_digest) VALUES (?, ?, ?, 2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + "sha256:" + "a".repeat(64), + UUID.randomUUID(), + "fixture-owner-key", + "owner-reviewer", + "approval-" + operationId, + java.time.Instant.now().toString(), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64), + Base64.getEncoder().encodeToString(new byte[64]), + "{}", + "sha256:" + "e".repeat(64), + "sha256:" + "f".repeat(64)); + } + + void insertHold(UUID operationId, String scope) { + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_legal_hold (" + + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + + "authorization_id, authorized_principal, authorized_at, review_at) " + + "VALUES (?, ?, ?, 'LITIGATION', 'case-2026-001', ?, 'owner-admin', " + + "clock_timestamp(), clock_timestamp() + INTERVAL '30 days')", + uuid(927), + operationId, + scope, + uuid(928)); + } + + UUID insertActiveHold(UUID operationId, UUID holdId) { + // Seed governed state only to prove expiry blockers; application writes remain denied. + withHoldInsertTriggerDisabled( + () -> + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_legal_hold (" + + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + + "authorization_id, authorized_principal, authorized_at, review_at) " + + "VALUES (?, ?, 'RAW_PAYLOAD', 'LITIGATION', 'test-case-927', ?, " + + "'fixture-authenticated-owner', clock_timestamp() - INTERVAL '2 days', " + + "clock_timestamp() + INTERVAL '30 days')", + holdId, + operationId, + uuid(928))); + return holdId; + } + + void insertInvalidScopeHold(UUID operationId) { + withHoldInsertTriggerDisabled( + () -> + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_legal_hold (" + + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + + "authorization_id, authorized_principal, authorized_at, review_at) " + + "VALUES (?, ?, 'ACCOUNT_MAPPING', 'LITIGATION', 'bad-scope', ?, " + + "'fixture-authenticated-owner', clock_timestamp(), " + + "clock_timestamp() + INTERVAL '30 days')", + uuid(929), + operationId, + uuid(930))); + } + + void releaseHold(UUID holdId) { + dsl.execute( + "UPDATE game_session_retained_tenant_association_legal_hold " + + "SET released_at = clock_timestamp(), released_by = 'fixture-authenticated-owner', " + + "release_reference = 'release-927' WHERE hold_id = ?", + holdId); + } + + void deleteHold(UUID holdId) { + dsl.execute( + "DELETE FROM game_session_retained_tenant_association_legal_hold WHERE hold_id = ?", + holdId); + } + + void releaseHoldForRetentionTest(UUID holdId) { + // This fixture bypasses auth solely to prove release-triggered raw erasure. + dsl.execute( + "ALTER TABLE game_session_retained_tenant_association_legal_hold " + + "DISABLE TRIGGER game_session_retained_tenant_hold_release_only"); + try { + releaseHold(holdId); + } finally { + dsl.execute( + "ALTER TABLE game_session_retained_tenant_association_legal_hold " + + "ENABLE TRIGGER game_session_retained_tenant_hold_release_only"); + } + } + + private void withHoldInsertTriggerDisabled(Runnable insert) { + dsl.execute( + "ALTER TABLE game_session_retained_tenant_association_legal_hold " + + "DISABLE TRIGGER game_session_retained_tenant_hold_authentication_required"); + try { + insert.run(); + } finally { + dsl.execute( + "ALTER TABLE game_session_retained_tenant_association_legal_hold " + + "ENABLE TRIGGER game_session_retained_tenant_hold_authentication_required"); + } + } + + boolean payloadExists(UUID operationId) { + return dsl.fetchOne( + "SELECT 1 FROM game_session_retained_tenant_association_payload " + + "WHERE operation_id = ?", + operationId) + != null; + } + void seedInstance(long tenantId, long instanceId, String runtimeVersion) { dsl.execute( "INSERT INTO game_instances " @@ -543,18 +795,20 @@ LegacyGameSessionTenantAssociationReceipt approval( String evidenceDigest) { GameSessionTenantAssociationEvidence evidence = new GameSessionTenantAssociationEvidence( - 1, + 2, approvalOperationId, NAMESPACE, "fixture-owner-key", "owner-reviewer", "approval-" + approvalOperationId, - "2026-01-01T00:00:00Z", + java.time.Instant.parse(snapshot.capturedAt()).plusSeconds(1).toString(), + snapshot.capturedAt(), Long.toString(legacyTenantId), canonicalTenantId, "501", "source-game-501", "RETAINED_GAME_V29", + snapshot.projectionDigest(), evidenceDigest); String signature = Base64.getEncoder().encodeToString(new byte[64]); return new LegacyGameSessionTenantAssociationReceipt( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java index dc06804969..bbae020095 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java @@ -87,7 +87,7 @@ void capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerT GameSessionRetainedTenantSnapshot snapshot = fixture.capture(); JsonNode root = JSON.readTree(snapshot.canonicalJson()); - assertThat(root.get("schemaVersion").intValue()).isEqualTo(3); + assertThat(root.get("schemaVersion").intValue()).isEqualTo(4); assertThat(root.get("targetNamespace").textValue()).isEqualTo(NAMESPACE); assertThat(root.get("legacyGameSessionTenantId").textValue()).isEqualTo(TENANT_ID); assertThat(textValues(root.get("instances"), "id")).containsExactly("2", "10", "20"); @@ -108,7 +108,12 @@ void capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerT assertThat(root.get("backfillIssues").size()).isZero(); assertThat( GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + NAMESPACE, + TENANT_ID, + snapshot.capturedAt(), + snapshot.canonicalJson(), + snapshot.evidenceDigest(), + snapshot.projectionDigest())) .isEqualTo(snapshot); TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); @@ -179,7 +184,12 @@ void capturesCurrentNumericOwnersAndBindsOwnerChangesToSnapshotDigest() throws E assertThat(newNumericOwner.has("owner_account_uuid")).isFalse(); assertThat( GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + NAMESPACE, + TENANT_ID, + snapshot.capturedAt(), + snapshot.canonicalJson(), + snapshot.evidenceDigest(), + snapshot.projectionDigest())) .isEqualTo(snapshot); fixture.dsl.execute("UPDATE game_instances SET owner_account_id = ? WHERE id = ?", 90011L, 10L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java index b93793181e..da2b0d1c33 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -467,18 +467,20 @@ private static GameSessionTenantAssociationEvidence associationEvidence() { private static GameSessionTenantAssociationEvidence associationEvidenceWith( UUID operationId, String namespace, String retainedTenantKey, UUID canonicalTenantId) { return new GameSessionTenantAssociationEvidence( - 1, + 2, operationId, namespace, "owner-key-1", "owner@example.test", "approval-2026-09", "2026-09-30T12:00:00Z", + "2026-09-30T11:00:00Z", retainedTenantKey, canonicalTenantId, "91", SOURCE_KEY, "RETAINED_GAME_V29", + "sha256:" + "b".repeat(64), ASSOCIATION_SOURCE_DIGEST); } @@ -497,12 +499,14 @@ private static ResolveLegacyGameSessionTenantAssociationResponse associationResp .setApprovedBy(evidence.approvedBy()) .setApprovalReference(evidence.approvalReference()) .setSignedAt(evidence.signedAt()) + .setSourceCapturedAt(evidence.sourceCapturedAt()) .setLegacyGameSessionTenantId(evidence.legacyGameSessionTenantId()) .setCanonicalTenantId(evidence.canonicalTenantId().toString()) .setSourceGameRowId(evidence.sourceGameRowId()) .setSourceGameTenantKey(evidence.sourceGameTenantKey()) .setProvenanceKind(evidence.provenanceKind()) .setGameSessionEvidenceDigest(evidence.gameSessionEvidenceDigest()) + .setGameSessionProjectionDigest(evidence.gameSessionProjectionDigest()) .build(); return ResolveLegacyGameSessionTenantAssociationResponse.newBuilder() .setRequestId(REQUEST_ID.toString()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java index 0d00eac1cb..5b754e3b8c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java @@ -20,10 +20,11 @@ class GameSessionRetainedTenantSnapshotTest { private static final ObjectMapper JSON = new ObjectMapper(); private static final String NAMESPACE = "retained-snapshot-test"; private static final String TENANT_ID = "7"; + private static final String CAPTURED_AT = "2026-10-01T00:00:00Z"; private static final String SNAPSHOT_DIGEST_DOMAIN = - "game-session/retained-tenant-identity-snapshot/v3"; + "game-session/retained-tenant-identity-snapshot/v4"; private static final String SNAPSHOT_DIGEST = - "sha256:79d78d5af138e7261f63696a2ccc2b8f5ceadc4f0e139c348238873e74bda5c4"; + "sha256:8e2db4a01553d67f1f21fb347c2c715a16404465a9342056810ebd48d6cef226"; private static final String IRRELEVANT_DIGEST = "sha256:" + "0".repeat(64); @Test @@ -31,10 +32,16 @@ void emitsCanonicalOrderedUnicodeAndLargeCounterVectorAndBindsChangedFields() { String canonicalJson = snapshotJson("Café 🐉"); GameSessionRetainedTenantSnapshot snapshot = GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, canonicalJson, expectedDigest(canonicalJson)); + NAMESPACE, + TENANT_ID, + CAPTURED_AT, + canonicalJson, + expectedDigest(canonicalJson), + expectedProjectionDigest(canonicalJson)); assertThat(snapshot.canonicalJson()) - .startsWith("{\"backfillIssues\":[],\"instances\":[") + .startsWith( + "{\"backfillIssues\":[],\"capturedAt\":\"2026-10-01T00:00:00Z\",\"instances\":[") .contains("\"runtime_version\":\"Café 🐉\"") .contains("\"row_version\":\"9223372036854775807\""); assertThat(snapshot.canonicalJson().indexOf("\"id\":\"2\"")) @@ -43,17 +50,36 @@ void emitsCanonicalOrderedUnicodeAndLargeCounterVectorAndBindsChangedFields() { assertThat(snapshot.evidenceDigest()).isEqualTo(expectedDigest(canonicalJson)); assertThat( GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + NAMESPACE, + TENANT_ID, + CAPTURED_AT, + snapshot.canonicalJson(), + snapshot.evidenceDigest(), + snapshot.projectionDigest())) .isEqualTo(snapshot); GameSessionRetainedTenantSnapshot changed = GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, snapshotJson("Café 🐲"), expectedDigest(snapshotJson("Café 🐲"))); + NAMESPACE, + TENANT_ID, + CAPTURED_AT, + snapshotJson("Café 🐲"), + expectedDigest(snapshotJson("Café 🐲")), + expectedProjectionDigest(snapshotJson("Café 🐲"))); assertThat(changed.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + GameSessionRetainedTenantSnapshot sourceBoundCapture = + snapshot.withCapturedAt("2026-09-30T00:00:00Z"); + assertThat(sourceBoundCapture.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + assertThat(sourceBoundCapture.projectionDigest()).isEqualTo(snapshot.projectionDigest()); assertThatThrownBy( () -> GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, snapshot.canonicalJson(), IRRELEVANT_DIGEST)) + NAMESPACE, + TENANT_ID, + CAPTURED_AT, + snapshot.canonicalJson(), + IRRELEVANT_DIGEST, + snapshot.projectionDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest"); } @@ -86,7 +112,7 @@ void retainsRequiredCurrentNumericOwnerIdentityAndBindsItToTheDigest() { } @Test - void rejectsMissingOwnerFieldAndIncompatibleV2SnapshotReceipts() { + void rejectsMissingOwnerFieldAndIncompatibleV3SnapshotReceipts() { ObjectNode missingSlot = envelopeWithInstances("runtime"); ((ObjectNode) missingSlot.withArray("instances").get(0)).remove("owner_account_id"); assertThatThrownBy(() -> revalidate(missingSlot)) @@ -94,10 +120,10 @@ void rejectsMissingOwnerFieldAndIncompatibleV2SnapshotReceipts() { .hasMessageContaining("missing or undeclared fields"); ObjectNode oldSchema = envelopeWithInstances("runtime"); - oldSchema.put("schemaVersion", 2); + oldSchema.put("schemaVersion", 3); assertThatThrownBy(() -> revalidate(oldSchema)) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("schemaVersion must be integer 3"); + .hasMessageContaining("schemaVersion must be integer 4"); ObjectNode nullOwner = envelopeWithInstances("runtime"); ((ObjectNode) nullOwner.withArray("instances").get(0)).putNull("owner_account_id"); @@ -154,7 +180,12 @@ void rejectsEmptyUnknownMalformedAndDuplicateMemberEvidence() { assertThatThrownBy( () -> GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, duplicateMemberJson, SNAPSHOT_DIGEST)) + NAMESPACE, + TENANT_ID, + CAPTURED_AT, + duplicateMemberJson, + SNAPSHOT_DIGEST, + IRRELEVANT_DIGEST)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("malformed"); } @@ -165,26 +196,41 @@ void rejectsNonCanonicalNamespaceAndLegacyTenantKeys() { assertThatThrownBy( () -> GameSessionRetainedTenantSnapshot.fromCanonicalJson( - "Invalid-Namespace", TENANT_ID, valid, IRRELEVANT_DIGEST)) + "Invalid-Namespace", + TENANT_ID, + CAPTURED_AT, + valid, + IRRELEVANT_DIGEST, + IRRELEVANT_DIGEST)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical DNS label"); assertThatThrownBy( () -> GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, "07", valid, IRRELEVANT_DIGEST)) + NAMESPACE, "07", CAPTURED_AT, valid, IRRELEVANT_DIGEST, IRRELEVANT_DIGEST)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical decimal"); assertThatThrownBy( () -> GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, "9223372036854775808", valid, IRRELEVANT_DIGEST)) + NAMESPACE, + "9223372036854775808", + CAPTURED_AT, + valid, + IRRELEVANT_DIGEST, + IRRELEVANT_DIGEST)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive BIGINT"); } private static GameSessionRetainedTenantSnapshot revalidate(ObjectNode projection) { return GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, canonicalJson(projection), IRRELEVANT_DIGEST); + NAMESPACE, + TENANT_ID, + CAPTURED_AT, + canonicalJson(projection), + IRRELEVANT_DIGEST, + IRRELEVANT_DIGEST); } private static String snapshotJson(String runtimeVersion) { @@ -203,8 +249,9 @@ private static ObjectNode envelopeWithInstances(String runtimeVersion) { private static ObjectNode envelope() { ObjectNode envelope = JSON.createObjectNode(); envelope.put("targetNamespace", NAMESPACE); - envelope.put("schemaVersion", 3); + envelope.put("schemaVersion", 4); envelope.put("legacyGameSessionTenantId", TENANT_ID); + envelope.put("capturedAt", CAPTURED_AT); envelope.set("instances", JSON.createArrayNode()); envelope.set("pointers", JSON.createArrayNode()); envelope.set("sharedNamespaces", JSON.createArrayNode()); @@ -267,7 +314,12 @@ private static String canonicalJson(ObjectNode projection) { private static GameSessionRetainedTenantSnapshot snapshot(ObjectNode projection) { String canonicalJson = canonicalJson(projection); return GameSessionRetainedTenantSnapshot.fromCanonicalJson( - NAMESPACE, TENANT_ID, canonicalJson, expectedDigest(canonicalJson)); + NAMESPACE, + TENANT_ID, + CAPTURED_AT, + canonicalJson, + expectedDigest(canonicalJson), + expectedProjectionDigest(canonicalJson)); } private static String expectedDigest(String canonicalJson) { @@ -281,6 +333,19 @@ private static String expectedDigest(String canonicalJson) { } } + private static String expectedProjectionDigest(String canonicalJson) { + try { + ObjectNode projection = (ObjectNode) JSON.readTree(canonicalJson); + projection.remove("capturedAt"); + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + updateFrame(hash, "game-session/retained-tenant-identity-projection/v4"); + updateFrame(hash, canonicalJson(projection)); + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (IOException | NoSuchAlgorithmException exception) { + throw new AssertionError("Unable to calculate source projection digest", exception); + } + } + private static void updateFrame(MessageDigest hash, String value) { byte[] bytes = value.getBytes(StandardCharsets.UTF_8); hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java index ba4014b3fa..355ad847f5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java @@ -240,18 +240,20 @@ private static LegacyGameSessionTenantAssociationReceipt receipt( String namespace, UUID operationId, UUID canonicalTenantId, long legacyKey) { GameSessionTenantAssociationEvidence evidence = new GameSessionTenantAssociationEvidence( - 1, + 2, operationId, namespace, "fixture-key", "approved-by-test", "approval-reference-1", "2026-01-01T00:00:00Z", + "2025-12-31T23:00:00Z", Long.toString(legacyKey), canonicalTenantId, "501", "source-game-501", "RETAINED_GAME_V29", + "sha256:" + "b".repeat(64), "sha256:" + "a".repeat(64)); String signature = Base64.getEncoder().encodeToString(new byte[64]); return new LegacyGameSessionTenantAssociationReceipt( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJobTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJobTest.java new file mode 100644 index 0000000000..f72d513074 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJobTest.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +class GameSessionRetainedTenantPayloadRetentionJobTest { + @Test + void componentUsesOnlyTheExistingDslContextAndRetriesFailedCleanup() { + DSLContext dsl = Mockito.mock(DSLContext.class); + when(dsl.execute(anyString())) + .thenThrow(new IllegalStateException("temporary cleanup failure")) + .thenReturn(1); + + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context.registerBean(DSLContext.class, () -> dsl); + context.register(GameSessionRetainedTenantPayloadRetentionJob.class); + context.refresh(); + + assertThat(context.getBean(GameSessionRetainedTenantPayloadRetentionJob.class)).isNotNull(); + assertThat(context.getBeansOfType(GameSessionRetainedTenantAssociationRepository.class)) + .isEmpty(); + + GameSessionRetainedTenantPayloadRetentionJob job = + context.getBean(GameSessionRetainedTenantPayloadRetentionJob.class); + assertThatThrownBy(job::purgeExpiredPayloadBatch) + .isInstanceOf(IllegalStateException.class) + .hasMessage("temporary cleanup failure"); + job.purgeExpiredPayloadBatch(); + } + + verify(dsl, times(2)).execute(anyString()); + } +} From e173f0b36b3fafbf0311cfa1938f88ffaf4c1822 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:34:49 +1300 Subject: [PATCH 068/105] Finalize malformed dry-run account principals as durable denials --- .../impl/ScriptEventIngressServiceImpl.java | 9 ++- .../ScriptEventIngressServiceImplTest.java | 62 ++++++++++++------- 2 files changed, 47 insertions(+), 24 deletions(-) diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java index 1eead61106..af99f44bb5 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java @@ -798,7 +798,14 @@ private TriggerAdmission validateDryRunBudget( if (!request.getIsDryRun()) { return null; } - String principalKey = dryRunPrincipalKey(); + final String principalKey; + try { + principalKey = dryRunPrincipalKey(); + } catch (IllegalArgumentException ex) { + // A malformed Account subject is a permanent principal-validation failure. Keep it in the + // claimed event's normal finalization path so retries converge on a bounded denial. + return new TriggerAdmission(false, OUTCOME_REGISTRY_REJECTED, "dry_run_principal_invalid", 0); + } if (principalKey.isBlank()) { return new TriggerAdmission(false, OUTCOME_QUOTA_DENIED, "dry_run_principal_missing", 0); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java index 6c4ef54238..fdc8cc4743 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java @@ -3263,8 +3263,9 @@ void dryRunBudgetDenialStopsBeforeHandlerResolution() { } @Test - void dryRunRejectsMalformedCurrentAccountClaimBeforeQuotaLookup() { - SessionContext.setContext("not-a-long", List.of(), Map.of()); + void dryRunPersistsRejectionForMalformedCurrentAccountClaimBeforeQuotaLookup() { + SessionContext.setContext( + "not-a-uuid", List.of(), Map.of(), true, "game-session-service", "game-session-1"); ScriptEventIngressAuditRepository repository = Mockito.mock(ScriptEventIngressAuditRepository.class); stubClaimRepository(repository); @@ -3286,12 +3287,14 @@ void dryRunRejectsMalformedCurrentAccountClaimBeforeQuotaLookup() { .build()); ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository eventAuditRepository = Mockito.mock(ScriptEventAuditRepository.class); ScriptEventIngressService service = new ScriptEventIngressServiceImpl( repository, bindingRepository, - Mockito.mock(ScriptWorkItemRepository.class), - Mockito.mock(ScriptEventAuditRepository.class), + workItemRepository, + eventAuditRepository, new BuiltInScriptEventRegistryService(), Mockito.mock(AutomationQueueService.class), outputProperties(), @@ -3304,27 +3307,40 @@ void dryRunRejectsMalformedCurrentAccountClaimBeforeQuotaLookup() { allowingQuotaService(), dryRunQuotaService); - assertThrows( - IllegalArgumentException.class, - () -> - service.admit( - gameplayRequestBuilder() - .setTenantId("1") - .setGameInstanceId("game-1") - .setRegionId("region-1") - .setRegionEpoch(7) - .setEntityId("entity-1") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setScriptId("script-1") - .setEventType("onCommand") - .setScriptPatchVersion("patch-1") - .setScriptEventId("event-dry-run-invalid-account") - .setReadSnapshotToken("snapshot-1") - .setIsDryRun(true) - .build(), - "game-session-service")); + ScriptEventIngressService.TriggerAdmission admission = + service.admit( + gameplayRequestBuilder() + .setTenantId("1") + .setGameInstanceId("game-1") + .setRegionId("region-1") + .setRegionEpoch(7) + .setEntityId("entity-1") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setScriptId("script-1") + .setEventType("onCommand") + .setScriptPatchVersion("patch-1") + .setScriptEventId("event-dry-run-invalid-account") + .setReadSnapshotToken("snapshot-1") + .setIsDryRun(true) + .build(), + "game-session-service"); + assertThat(admission.admitted()).isFalse(); + assertThat(admission.outcome()) + .isEqualTo( + TriggerAdmissionOutcome.TRIGGER_ADMISSION_OUTCOME_EVENT_REGISTRY_REJECTED.name()); + assertThat(admission.reason()).isEqualTo("dry_run_principal_invalid"); + ArgumentCaptor auditCaptor = + ArgumentCaptor.forClass(ScriptEventIngressAudit.class); + verify(repository).save(auditCaptor.capture()); + assertThat(auditCaptor.getValue().getAdmitted()).isFalse(); + assertThat(auditCaptor.getValue().getAdmissionOutcome()) + .isEqualTo( + TriggerAdmissionOutcome.TRIGGER_ADMISSION_OUTCOME_EVENT_REGISTRY_REJECTED.name()); + assertThat(auditCaptor.getValue().getAdmissionReason()).isEqualTo("dry_run_principal_invalid"); + assertThat(auditCaptor.getValue().getSourceState()).isEqualTo("TRIGGER_REJECTED"); verifyNoInteractions(dryRunQuotaService); + verifyNoInteractions(workItemRepository, eventAuditRepository); verify(bindingRepository, never()) .findByTenantIdAndScriptPatchVersionAndEventTypeAndEventSchemaVersionAndEnabledTrueOrderByPriorityAscScriptIdAsc( Mockito.anyLong(), From 140daa12809ab380052520b3afb42cd092a07257 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:38:15 +1300 Subject: [PATCH 069/105] Correct dry-run audit regression accessor and formatting --- .../service/impl/ScriptEventIngressServiceImplTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java index fdc8cc4743..eb4f1b923e 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java @@ -3288,7 +3288,8 @@ void dryRunPersistsRejectionForMalformedCurrentAccountClaimBeforeQuotaLookup() { ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); - ScriptEventAuditRepository eventAuditRepository = Mockito.mock(ScriptEventAuditRepository.class); + ScriptEventAuditRepository eventAuditRepository = + Mockito.mock(ScriptEventAuditRepository.class); ScriptEventIngressService service = new ScriptEventIngressServiceImpl( repository, @@ -3333,7 +3334,7 @@ void dryRunPersistsRejectionForMalformedCurrentAccountClaimBeforeQuotaLookup() { ArgumentCaptor auditCaptor = ArgumentCaptor.forClass(ScriptEventIngressAudit.class); verify(repository).save(auditCaptor.capture()); - assertThat(auditCaptor.getValue().getAdmitted()).isFalse(); + assertThat(auditCaptor.getValue().isAdmitted()).isFalse(); assertThat(auditCaptor.getValue().getAdmissionOutcome()) .isEqualTo( TriggerAdmissionOutcome.TRIGGER_ADMISSION_OUTCOME_EVENT_REGISTRY_REJECTED.name()); From 19961e9b7b48337a6f9b63fd7fb409d9f3dec319 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:42:52 +1300 Subject: [PATCH 070/105] Materialize owner-proved versioned realm catalog and stable shared identity --- .../PublishedRealmEntryPolicySetEvidence.java | 7 + ...PublishedRealmEntryPolicyEvidenceTest.java | 31 +- .../entity/InitialAdmissionBindCatalog.java | 7 +- .../entity/PublishedRealmCatalogEntry.java | 56 ++ .../entity/PublishedRealmCatalogSnapshot.java | 105 +++ ...InitialAdmissionBindCatalogRepository.java | 682 ++++++++++++++++++ .../PublishedRealmCatalogOwnerService.java | 145 ++++ ...V14__published_realm_catalog_snapshots.sql | 244 +++++++ ...RealmCatalogRepositoryIntegrationTest.java | 422 +++++++++++ ...eDesignPublishedRealmPolicyClientTest.java | 44 +- .../PublishedRealmCatalogSnapshotTest.java | 192 +++++ 11 files changed, 1930 insertions(+), 5 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogEntry.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V14__published_realm_catalog_snapshots.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java index 4d6d62ac2c..ea0903e2fe 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java @@ -3,9 +3,11 @@ import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +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 net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import tools.jackson.databind.ObjectMapper; @@ -49,6 +51,7 @@ public record PublishedRealmEntryPolicySetEvidence( String previousWorld = null; String previousRealm = null; int visiblePublicProductionCount = 0; + Set realmSlugs = new HashSet<>(); for (PublishedRealmEntryPolicyEvidence policy : policies) { if (policy == null || !canonicalTenantId.equals(policy.canonicalTenantId()) @@ -72,6 +75,10 @@ public record PublishedRealmEntryPolicySetEvidence( } String world = policy.policy().worldSlug(); String realm = policy.policy().realmSlug(); + if (!realmSlugs.add(realm)) { + throw new IllegalArgumentException( + "Published policy set contains a realm slug more than once within its tenant"); + } if (previousWorld != null && (previousWorld.compareTo(world) > 0 || (previousWorld.equals(world) && previousRealm.compareTo(realm) >= 0))) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java index 70353c3715..649b9a7176 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java @@ -140,7 +140,22 @@ void completeSetRejectsMissingMultipleOrOversizedAddressableSets() { createSet( identity, java.util.Collections.nCopies( - PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1, main))); + PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1, main))); + } + + @Test + void completeSetRejectsRealmSlugRepeatedAcrossDifferentWorlds() { + PublishedRealmEntryPolicyEvidence publicRealm = + policyEvidence("main", "earth", true, true); + PublishedRealmEntryPolicyEvidence duplicateRealm = + policyEvidence("main", "mars", false, false); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + createSet( + publicRealm.releaseBundleIdentity(), List.of(publicRealm, duplicateRealm))) + .withMessageContaining("realm slug more than once"); } private static PublishedRealmEntryPolicySetEvidence createSet( @@ -151,8 +166,17 @@ private static PublishedRealmEntryPolicySetEvidence createSet( private static PublishedRealmEntryPolicyEvidence policyEvidence( String realmSlug, boolean visible, boolean publicProduction) { + return policyEvidence(realmSlug, "earth", visible, publicProduction); + } + + private static PublishedRealmEntryPolicyEvidence policyEvidence( + String realmSlug, String worldSlug, boolean visible, boolean publicProduction) { String sourceJson = - "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + "{\"schemaVersion\":1,\"worldSlug\":\"" + + worldSlug + + "\",\"worldDisplayName\":\"" + + worldSlug + + "\"," + "\"realmSlug\":\"" + realmSlug + "\",\"realmDisplayName\":\"" @@ -167,7 +191,8 @@ private static PublishedRealmEntryPolicyEvidence policyEvidence( PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( TENANT_ID, 7L, WORKFLOW, MANIFEST, MAPPER); return PublishedRealmEntryPolicyEvidence.create( - UUID.nameUUIDFromBytes(realmSlug.getBytes(java.nio.charset.StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (worldSlug + ":" + realmSlug).getBytes(java.nio.charset.StandardCharsets.UTF_8)), TENANT_ID, "NEW_GAME_ROW", 12L, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java index 207f31d78e..1ff02be971 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java @@ -3,7 +3,12 @@ import java.time.Instant; import java.util.UUID; -/** Persisted, immutable revision-one public catalog identity used by an initial pointer bind. */ +/** + * Legacy run-owned fixture catalog evidence used by the initial-bind fixture path. + * + *

Published Game Design authority is stored and read through + * {@link PublishedRealmCatalogSnapshot}; this row is never promoted into that authority. + */ public record InitialAdmissionBindCatalog( UUID realmId, long tenantId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogEntry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogEntry.java new file mode 100644 index 0000000000..b2ef237eda --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogEntry.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.gamesession.entity; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** One immutable Game Design policy within a Game Session-owned catalog snapshot. */ +public record PublishedRealmCatalogEntry( + long tenantId, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, + NamespaceResolution namespaceResolution, + PublishedRealmEntryPolicyEvidence policyEvidence) { + public enum NamespaceResolution { + RESOLVED, + AWAITING_LIFECYCLE_PROOF + } + + public PublishedRealmCatalogEntry { + if (tenantId <= 0 || catalogRevision <= 0) { + throw new IllegalArgumentException("Catalog tenant and revision must be positive"); + } + requireNonNil(realmId, "realmId"); + Objects.requireNonNull(namespaceResolution, "namespaceResolution"); + Objects.requireNonNull(policyEvidence, "policyEvidence"); + if (namespaceResolution == NamespaceResolution.RESOLVED) { + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (policyEvidence.policy().stateScope() == RealmEntryPolicy.StateScope.ISOLATED) { + throw new IllegalArgumentException( + "An isolated catalog entry cannot resolve without owner-proven lifecycle identity"); + } + } else if (playableStateNamespaceId != null) { + throw new IllegalArgumentException( + "A lifecycle-unresolved catalog entry cannot expose a playable namespace"); + } + } + + /** Returns the selected entry's namespace only when this entry has owner-resolved scope. */ + public UUID requirePlayableStateNamespaceId() { + if (namespaceResolution != NamespaceResolution.RESOLVED) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_LIFECYCLE_UNRESOLVED: selected entry has no namespace authority"); + } + return playableStateNamespaceId; + } + + private static UUID requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java new file mode 100644 index 0000000000..66268e41bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.gamesession.entity; + +import java.time.Instant; +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.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import tools.jackson.databind.ObjectMapper; + +/** Exact immutable policy-set and identity snapshot materialized by Game Session. */ +public record PublishedRealmCatalogSnapshot( + long tenantId, + String targetNamespace, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String tenantIdentityProvenanceKind, + long catalogRevision, + PublishedRealmEntryPolicySetEvidence policySetEvidence, + List entries, + Instant createdAt) { + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + public PublishedRealmCatalogSnapshot { + if (tenantId <= 0 || sourceGameRowId <= 0 || catalogRevision <= 0) { + throw new IllegalArgumentException("Published realm catalog identity must be positive"); + } + if (targetNamespace == null || targetNamespace.isBlank()) { + throw new IllegalArgumentException("Published realm catalog namespace is required"); + } + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + if (new UUID(0L, 0L).equals(canonicalTenantId)) { + throw new IllegalArgumentException("canonicalTenantId must not be nil"); + } + if (sourceGameTenantKey == null || sourceGameTenantKey.isBlank()) { + throw new IllegalArgumentException("sourceGameTenantKey is required"); + } + if (!"NEW_GAME_ROW".equals(tenantIdentityProvenanceKind) + && !"RETAINED_GAME_V29".equals(tenantIdentityProvenanceKind)) { + throw new IllegalArgumentException("tenantIdentityProvenanceKind is unsupported"); + } + Objects.requireNonNull(policySetEvidence, "policySetEvidence"); + entries = List.copyOf(Objects.requireNonNull(entries, "entries")); + Objects.requireNonNull(createdAt, "createdAt"); + if (!canonicalTenantId.equals(policySetEvidence.canonicalTenantId()) + || policySetEvidence.policies().size() != entries.size() + || policySetEvidence.versionId() <= 0 + || policySetEvidence.versionNumber() <= 0 + || !policySetEvidence.hasValidDigest(OBJECT_MAPPER)) { + throw new IllegalArgumentException("Catalog snapshot does not match complete owner evidence"); + } + Set realmIds = new HashSet<>(); + for (int index = 0; index < entries.size(); index++) { + PublishedRealmCatalogEntry entry = entries.get(index); + if (entry.tenantId() != tenantId + || entry.catalogRevision() != catalogRevision + || !entry.policyEvidence().equals(policySetEvidence.policies().get(index)) + || !entry.policyEvidence().tenantIdentityProvenanceKind().equals( + tenantIdentityProvenanceKind) + || entry.policyEvidence().sourceGameRowId() != sourceGameRowId + || !entry.policyEvidence().sourceGameTenantKey().equals(sourceGameTenantKey) + || !realmIds.add(entry.realmId())) { + throw new IllegalArgumentException("Catalog snapshot entries are incomplete or contradictory"); + } + } + } + + /** Diagnostic guard requiring lifecycle proof for every entry in this snapshot. */ + public PublishedRealmCatalogSnapshot requireNamespaceResolved() { + if (entries.stream() + .anyMatch(entry -> entry.namespaceResolution() != NamespaceResolution.RESOLVED)) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_LIFECYCLE_UNRESOLVED: complete namespace authority is unavailable"); + } + return this; + } + + /** Selects only a visible realm and refuses to authorize it without its exact namespace. */ + public PublishedRealmCatalogEntry requireVisibleEntryForAdmission( + String worldSlug, String realmSlug) { + if (worldSlug == null || worldSlug.isBlank() || realmSlug == null || realmSlug.isBlank()) { + throw new IllegalArgumentException("Exact world and realm selectors are required"); + } + PublishedRealmCatalogEntry selected = + entries.stream() + .filter( + entry -> + worldSlug.equals(entry.policyEvidence().policy().worldSlug()) + && realmSlug.equals(entry.policyEvidence().policy().realmSlug())) + .findFirst() + .orElseThrow( + () -> + new IllegalArgumentException( + "PUBLISHED_REALM_CATALOG_SELECTOR_NOT_FOUND: exact realm selector is absent")); + if (!selected.policyEvidence().policy().visible()) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_ENTRY_HIDDEN: selected realm is not visible for admission"); + } + selected.requirePlayableStateNamespaceId(); + return selected; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java index 2a91bfc498..5bd291c81b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java @@ -2,19 +2,35 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toOffsetDateTime; import static net.firedevops.firemud.gamesession.jooq.tables.GameplayInitialAdmissionBindCatalog.GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG; import static net.firedevops.firemud.gamesession.jooq.tables.GameplayTenantSharedPlayableStateNamespace.GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.UUID; +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.gamesession.entity.InitialAdmissionBindCatalog; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; @Repository @SuppressFBWarnings( @@ -23,6 +39,72 @@ public class InitialAdmissionBindCatalogRepository { private static final String TENANT_CATALOG_LOCK_PREFIX = "initial-admission-bind-catalog:"; private static final String SHARED_NAMESPACE_LOCK_PREFIX = "tenant-shared-playable-state:"; + private static final String PUBLISHED_CATALOG_LOCK_PREFIX = "published-realm-catalog:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final tools.jackson.databind.ObjectMapper OBJECT_MAPPER = + new tools.jackson.databind.ObjectMapper(); + + private static final Table PUBLISHED_SNAPSHOT = + DSL.table(DSL.name("gameplay_published_realm_catalog_snapshot")); + private static final Table PUBLISHED_IDENTITY = + DSL.table(DSL.name("gameplay_published_realm_catalog_identity")); + private static final Table PUBLISHED_ENTRY = + DSL.table(DSL.name("gameplay_published_realm_catalog_entry")); + private static final Table PUBLISHED_SHARED_NAMESPACE = + DSL.table(DSL.name("gameplay_published_tenant_shared_playable_state_namespace")); + private static final Table RETAINED_ASSOCIATION = + DSL.table(DSL.name("game_session_retained_tenant_association")); + + private static final Field TARGET_NAMESPACE = field("target_namespace", String.class); + private static final Field TENANT_ID = field("tenant_id", Long.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field SOURCE_GAME_ROW_ID = field("source_game_row_id", Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + field("source_game_tenant_key", String.class); + private static final Field TENANT_PROVENANCE_KIND = + field("tenant_identity_provenance_kind", String.class); + private static final Field ASSOCIATION_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field LEGACY_GAME_SESSION_TENANT_ID = + DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class); + private static final Field CATALOG_REVISION = field("catalog_revision", Long.class); + private static final Field VERSION_ID = field("version_id", Long.class); + private static final Field VERSION_NUMBER = field("version_number", Integer.class); + private static final Field RELEASE_BUNDLE_IDENTITY = + field("release_bundle_identity", String.class); + private static final Field PUBLISH_WORKFLOW_ID = + field("publish_workflow_id", String.class); + private static final Field MANIFEST_HASH = field("manifest_hash", String.class); + private static final Field POLICY_SET_DIGEST = field("policy_set_digest", String.class); + private static final Field POLICY_COUNT = field("policy_count", Integer.class); + private static final Field SNAPSHOT_CREATED_AT = + field("created_at", OffsetDateTime.class); + private static final Field REALM_SLUG = field("realm_slug", String.class); + private static final Field WORLD_SLUG = field("world_slug", String.class); + private static final Field INITIAL_WORLD_SLUG = field("initial_world_slug", String.class); + private static final Field REALM_ID = field("realm_id", UUID.class); + private static final Field POLICY_ID = field("policy_id", UUID.class); + private static final Field SOURCE_REVISION_ID = field("source_revision_id", Long.class); + private static final Field WORLD_DISPLAY_NAME = field("world_display_name", String.class); + private static final Field REALM_DISPLAY_NAME = field("realm_display_name", String.class); + private static final Field VISIBLE = field("visible", Boolean.class); + private static final Field PUBLIC_PRODUCTION = field("public_production", Boolean.class); + private static final Field STATE_SCOPE = field("state_scope", String.class); + private static final Field ENTRY_POLICY = field("entry_policy", String.class); + private static final Field POLICY_JSON = field("policy_json", String.class); + private static final Field POLICY_DIGEST = field("policy_digest", String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + field("playable_state_namespace_id", UUID.class); + private static final Field NAMESPACE_RESOLUTION = + field("namespace_resolution", String.class); + private static final Field IDENTITY_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + private static final Field ALLOCATED_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field ALLOCATED_AT = + DSL.field(DSL.name("allocated_at"), OffsetDateTime.class); + + private record NamespaceAssignment(UUID namespaceId, NamespaceResolution resolution) {} private final DSLContext dsl; @@ -30,6 +112,127 @@ public InitialAdmissionBindCatalogRepository(DSLContext dsl) { this.dsl = dsl; } + /** + * Commits one complete immutable Game Design policy set after its remote owner read has + * completed. The retained association is reread locally under this transaction before any + * catalog identity or snapshot row is written. + */ + @Transactional + public PublishedRealmCatalogSnapshot materializePublishedSnapshot( + String exactNamespace, + long tenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + PublishedRealmEntryPolicySetEvidence policySet) { + validatePublishedSource( + exactNamespace, + tenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + policySet); + lockPublishedTenant(exactNamespace, tenantId, canonicalTenantId); + requireRetainedAssociationMatches( + exactNamespace, tenantId, canonicalTenantId, sourceGameRowId, sourceGameTenantKey, + provenanceKind); + + Optional exactVersion = + findPublishedSnapshotByVersionInTransaction( + exactNamespace, tenantId, policySet.versionId()); + if (exactVersion.isPresent()) { + PublishedRealmCatalogSnapshot stored = exactVersion.get(); + requireExactPublishedRetry( + stored, + exactNamespace, + tenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + policySet); + return stored; + } + + Record current = latestSnapshotHeader(exactNamespace, tenantId); + long catalogRevision = + current == null ? 1L : Math.addExact(current.get(CATALOG_REVISION), 1L); + if (current != null && current.get(VERSION_NUMBER) >= policySet.versionNumber()) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_STALE_VERSION: owner version is not newer than the stored snapshot"); + } + + Instant now = Instant.now(); + insertSnapshotHeader( + exactNamespace, + tenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + catalogRevision, + policySet, + now); + + List entries = new ArrayList<>(policySet.policies().size()); + for (PublishedRealmEntryPolicyEvidence evidence : policySet.policies()) { + RealmEntryPolicy policy = evidence.policy(); + UUID realmId = resolveRealmIdentity(exactNamespace, tenantId, canonicalTenantId, policy); + NamespaceAssignment namespace = + resolveNamespace(exactNamespace, tenantId, canonicalTenantId, catalogRevision, realmId, + evidence); + insertPublishedEntry(exactNamespace, tenantId, catalogRevision, realmId, namespace, evidence); + entries.add( + new PublishedRealmCatalogEntry( + tenantId, + catalogRevision, + realmId, + namespace.namespaceId(), + namespace.resolution(), + evidence)); + } + + PublishedRealmCatalogSnapshot snapshot = + new PublishedRealmCatalogSnapshot( + tenantId, + exactNamespace, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + catalogRevision, + policySet, + entries, + now); + return requireSnapshotReadback(snapshot); + } + + /** Reads the exact immutable published snapshot referenced by a catalog revision. */ + @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) + public Optional findPublishedSnapshot( + String exactNamespace, long tenantId, long catalogRevision) { + if (exactNamespace == null || exactNamespace.isBlank() || tenantId <= 0 || catalogRevision <= 0) { + throw new IllegalArgumentException("Exact namespace, tenant, and catalog revision are required"); + } + return findPublishedSnapshotInTransaction(exactNamespace, tenantId, catalogRevision); + } + + /** Returns the newest committed complete policy snapshot, without implying pointer activation. */ + @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) + public Optional findLatestPublishedSnapshot( + String exactNamespace, long tenantId) { + if (exactNamespace == null || exactNamespace.isBlank() || tenantId <= 0) { + throw new IllegalArgumentException("Exact namespace and tenant are required"); + } + Record latest = latestSnapshotHeader(exactNamespace, tenantId); + return latest == null + ? Optional.empty() + : findPublishedSnapshotInTransaction( + exactNamespace, tenantId, latest.get(CATALOG_REVISION)); + } + public Optional findByTenantId(long tenantId) { return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG) .where(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.TENANT_ID.eq(tenantId)) @@ -106,6 +309,485 @@ public InitialAdmissionBindCatalog insert( return findByTenantId(descriptor.tenantId()).orElseThrow(); } + private Optional findPublishedSnapshotInTransaction( + String exactNamespace, long tenantId, long catalogRevision) { + return dsl.selectFrom(PUBLISHED_SNAPSHOT) + .where( + TARGET_NAMESPACE + .eq(exactNamespace) + .and(TENANT_ID.eq(tenantId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .fetchOptional(this::toPublishedSnapshot); + } + + private Optional findPublishedSnapshotByVersionInTransaction( + String exactNamespace, long tenantId, long versionId) { + return dsl.selectFrom(PUBLISHED_SNAPSHOT) + .where( + TARGET_NAMESPACE + .eq(exactNamespace) + .and(TENANT_ID.eq(tenantId)) + .and(VERSION_ID.eq(versionId))) + .fetchOptional(this::toPublishedSnapshot); + } + + private Record latestSnapshotHeader(String exactNamespace, long tenantId) { + return dsl.selectFrom(PUBLISHED_SNAPSHOT) + .where(TARGET_NAMESPACE.eq(exactNamespace).and(TENANT_ID.eq(tenantId))) + .orderBy(CATALOG_REVISION.desc()) + .limit(1) + .fetchOne(); + } + + private PublishedRealmCatalogSnapshot toPublishedSnapshot(Record header) { + String namespace = Objects.requireNonNull(header.get(TARGET_NAMESPACE)); + long tenantId = Objects.requireNonNull(header.get(TENANT_ID)); + long revision = Objects.requireNonNull(header.get(CATALOG_REVISION)); + UUID canonicalTenantId = Objects.requireNonNull(header.get(CANONICAL_TENANT_ID)); + long sourceGameRowId = Objects.requireNonNull(header.get(SOURCE_GAME_ROW_ID)); + String sourceGameTenantKey = Objects.requireNonNull(header.get(SOURCE_GAME_TENANT_KEY)); + String provenanceKind = Objects.requireNonNull(header.get(TENANT_PROVENANCE_KIND)); + long versionId = Objects.requireNonNull(header.get(VERSION_ID)); + int versionNumber = Objects.requireNonNull(header.get(VERSION_NUMBER)); + String releaseBundleIdentity = Objects.requireNonNull(header.get(RELEASE_BUNDLE_IDENTITY)); + String publishWorkflowId = Objects.requireNonNull(header.get(PUBLISH_WORKFLOW_ID)); + String manifestHash = Objects.requireNonNull(header.get(MANIFEST_HASH)); + String policySetDigest = Objects.requireNonNull(header.get(POLICY_SET_DIGEST)); + int policyCount = Objects.requireNonNull(header.get(POLICY_COUNT)); + + List rows = + dsl.selectFrom(PUBLISHED_ENTRY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(TENANT_ID.eq(tenantId)) + .and(CATALOG_REVISION.eq(revision))) + .orderBy(WORLD_SLUG.asc(), REALM_SLUG.asc()) + .fetch(); + if (rows.size() != policyCount || rows.isEmpty() || rows.size() > 128) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_SNAPSHOT_INCOMPLETE: persisted policy set is not complete"); + } + + List policyEvidence = new ArrayList<>(rows.size()); + List entries = new ArrayList<>(rows.size()); + for (Record row : rows) { + RealmEntryPolicy policy; + try { + policy = RealmEntryPolicy.parseCanonical(row.get(POLICY_JSON), OBJECT_MAPPER); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_POLICY_INVALID: persisted policy JSON is invalid", exception); + } + PublishedRealmEntryPolicyEvidence evidence; + try { + evidence = + new PublishedRealmEntryPolicyEvidence( + row.get(POLICY_ID), + canonicalTenantId, + provenanceKind, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + row.get(SOURCE_REVISION_ID), + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policy, + row.get(POLICY_DIGEST)); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_POLICY_INVALID: persisted owner evidence is malformed", + exception); + } + if (!Objects.equals(row.get(CANONICAL_TENANT_ID), canonicalTenantId) + || !Objects.equals(row.get(WORLD_SLUG), policy.worldSlug()) + || !Objects.equals(row.get(WORLD_DISPLAY_NAME), policy.worldDisplayName()) + || !Objects.equals(row.get(REALM_SLUG), policy.realmSlug()) + || !Objects.equals(row.get(REALM_DISPLAY_NAME), policy.realmDisplayName()) + || !Objects.equals(row.get(VISIBLE), policy.visible()) + || !Objects.equals(row.get(PUBLIC_PRODUCTION), policy.publicProduction()) + || !Objects.equals(row.get(STATE_SCOPE), policy.stateScope().name()) + || !Objects.equals(row.get(ENTRY_POLICY), policy.entryPolicy().name())) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_POLICY_INVALID: stored columns contradict canonical policy"); + } + policyEvidence.add(evidence); + String resolutionValue = Objects.requireNonNull(row.get(NAMESPACE_RESOLUTION)); + NamespaceResolution resolution; + try { + resolution = NamespaceResolution.valueOf(resolutionValue); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: unsupported namespace resolution", + exception); + } + entries.add( + new PublishedRealmCatalogEntry( + tenantId, + revision, + row.get(REALM_ID), + row.get(PLAYABLE_STATE_NAMESPACE_ID), + resolution, + evidence)); + } + + PublishedRealmEntryPolicySetEvidence setEvidence; + try { + setEvidence = + new PublishedRealmEntryPolicySetEvidence( + canonicalTenantId, + versionId, + versionNumber, + releaseBundleIdentity, + publishWorkflowId, + manifestHash, + policyEvidence, + policySetDigest); + setEvidence.requireValidDigest(OBJECT_MAPPER); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_SNAPSHOT_INVALID: complete policy-set evidence is invalid", + exception); + } + + OffsetDateTime createdAt = Objects.requireNonNull(header.get(SNAPSHOT_CREATED_AT)); + try { + return new PublishedRealmCatalogSnapshot( + tenantId, + namespace, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + revision, + setEvidence, + entries, + createdAt.toInstant()); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_SNAPSHOT_INVALID: persisted snapshot is contradictory", + exception); + } + } + + private void insertSnapshotHeader( + String exactNamespace, + long tenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + long catalogRevision, + PublishedRealmEntryPolicySetEvidence policySet, + Instant now) { + dsl.insertInto(PUBLISHED_SNAPSHOT) + .set(TARGET_NAMESPACE, exactNamespace) + .set(TENANT_ID, tenantId) + .set(CANONICAL_TENANT_ID, canonicalTenantId) + .set(CATALOG_REVISION, catalogRevision) + .set(SOURCE_GAME_ROW_ID, sourceGameRowId) + .set(SOURCE_GAME_TENANT_KEY, sourceGameTenantKey) + .set(TENANT_PROVENANCE_KIND, provenanceKind) + .set(VERSION_ID, policySet.versionId()) + .set(VERSION_NUMBER, policySet.versionNumber()) + .set(RELEASE_BUNDLE_IDENTITY, policySet.releaseBundleIdentity()) + .set(PUBLISH_WORKFLOW_ID, policySet.publishWorkflowId()) + .set(MANIFEST_HASH, policySet.manifestHash()) + .set(POLICY_SET_DIGEST, policySet.policySetDigest()) + .set(POLICY_COUNT, policySet.policies().size()) + .set(SNAPSHOT_CREATED_AT, toOffsetDateTime(now)) + .execute(); + } + + private UUID resolveRealmIdentity( + String exactNamespace, + long tenantId, + UUID canonicalTenantId, + RealmEntryPolicy policy) { + Record existing = + dsl.selectFrom(PUBLISHED_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(exactNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_SLUG.eq(policy.realmSlug()))) + .fetchOne(); + if (existing != null) { + if (!canonicalTenantId.equals(existing.get(CANONICAL_TENANT_ID))) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_IDENTITY_CONFLICT: realm slug is bound to another tenant"); + } + if (!Long.valueOf(tenantId).equals(existing.get(TENANT_ID))) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_IDENTITY_CONFLICT: canonical tenant mapping changed its local owner ID"); + } + if (!policy.worldSlug().equals(existing.get(INITIAL_WORLD_SLUG))) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_SELECTOR_CHANGED: stable realm selector changed world"); + } + return Objects.requireNonNull(existing.get(REALM_ID)); + } + + UUID realmId = UUID.randomUUID(); + dsl.insertInto(PUBLISHED_IDENTITY) + .set(TARGET_NAMESPACE, exactNamespace) + .set(TENANT_ID, tenantId) + .set(CANONICAL_TENANT_ID, canonicalTenantId) + .set(REALM_SLUG, policy.realmSlug()) + .set(INITIAL_WORLD_SLUG, policy.worldSlug()) + .set(REALM_ID, realmId) + .set(SNAPSHOT_CREATED_AT, toOffsetDateTime(Instant.now())) + .execute(); + return realmId; + } + + private NamespaceAssignment resolveNamespace( + String exactNamespace, + long tenantId, + UUID canonicalTenantId, + long catalogRevision, + UUID realmId, + PublishedRealmEntryPolicyEvidence evidence) { + Record previous = + dsl.selectFrom(PUBLISHED_ENTRY) + .where(TARGET_NAMESPACE.eq(exactNamespace).and(TENANT_ID.eq(tenantId)).and(REALM_ID.eq(realmId))) + .orderBy(CATALOG_REVISION.desc()) + .limit(1) + .fetchOne(); + RealmEntryPolicy policy = evidence.policy(); + if (previous != null) { + String previousScope = Objects.requireNonNull(previous.get(STATE_SCOPE)); + NamespaceResolution previousResolution; + try { + previousResolution = + NamespaceResolution.valueOf(Objects.requireNonNull(previous.get(NAMESPACE_RESOLUTION))); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior namespace state is unsupported", + exception); + } + if (!previousScope.equals(policy.stateScope().name()) + || previousResolution != NamespaceResolution.RESOLVED + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED) { + return new NamespaceAssignment(null, NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + } + UUID previousNamespace = Objects.requireNonNull(previous.get(PLAYABLE_STATE_NAMESPACE_ID)); + if (previousNamespace.equals(NIL_UUID)) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior namespace is nil"); + } + return new NamespaceAssignment(previousNamespace, NamespaceResolution.RESOLVED); + } + + if (policy.stateScope() != RealmEntryPolicy.StateScope.SHARED) { + return new NamespaceAssignment(null, NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + } + return new NamespaceAssignment( + getOrCreateCanonicalTenantSharedNamespace(exactNamespace, canonicalTenantId), + NamespaceResolution.RESOLVED); + } + + private UUID getOrCreateCanonicalTenantSharedNamespace( + String exactNamespace, UUID canonicalTenantId) { + Record existing = + dsl.selectFrom(PUBLISHED_SHARED_NAMESPACE) + .where( + TARGET_NAMESPACE + .eq(exactNamespace) + .and(ALLOCATED_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + if (existing != null) { + UUID namespaceId = Objects.requireNonNull(existing.get(IDENTITY_NAMESPACE_ID)); + if (namespaceId.equals(NIL_UUID)) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: shared namespace is nil"); + } + return namespaceId; + } + UUID namespaceId = UUID.randomUUID(); + dsl.insertInto(PUBLISHED_SHARED_NAMESPACE) + .set(TARGET_NAMESPACE, exactNamespace) + .set(ALLOCATED_TENANT_ID, canonicalTenantId) + .set(IDENTITY_NAMESPACE_ID, namespaceId) + .set(ALLOCATED_AT, toOffsetDateTime(Instant.now())) + .execute(); + return namespaceId; + } + + private void insertPublishedEntry( + String exactNamespace, + long tenantId, + long catalogRevision, + UUID realmId, + NamespaceAssignment namespace, + PublishedRealmEntryPolicyEvidence evidence) { + RealmEntryPolicy policy = evidence.policy(); + dsl.insertInto(PUBLISHED_ENTRY) + .set(TARGET_NAMESPACE, exactNamespace) + .set(TENANT_ID, tenantId) + .set(CANONICAL_TENANT_ID, evidence.canonicalTenantId()) + .set(CATALOG_REVISION, catalogRevision) + .set(REALM_ID, realmId) + .set(POLICY_ID, evidence.policyId()) + .set(SOURCE_REVISION_ID, evidence.sourceRevisionId()) + .set(WORLD_SLUG, policy.worldSlug()) + .set(WORLD_DISPLAY_NAME, policy.worldDisplayName()) + .set(REALM_SLUG, policy.realmSlug()) + .set(REALM_DISPLAY_NAME, policy.realmDisplayName()) + .set(VISIBLE, policy.visible()) + .set(PUBLIC_PRODUCTION, policy.publicProduction()) + .set(STATE_SCOPE, policy.stateScope().name()) + .set(ENTRY_POLICY, policy.entryPolicy().name()) + .set(POLICY_JSON, policy.canonicalJson()) + .set(POLICY_DIGEST, evidence.policyDigest()) + .set(PLAYABLE_STATE_NAMESPACE_ID, namespace.namespaceId()) + .set(NAMESPACE_RESOLUTION, namespace.resolution().name()) + .execute(); + } + + private void requireRetainedAssociationMatches( + String exactNamespace, + long tenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + Record association = + dsl.select( + TARGET_NAMESPACE, + CANONICAL_TENANT_ID, + LEGACY_GAME_SESSION_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + ASSOCIATION_PROVENANCE_KIND) + .from(RETAINED_ASSOCIATION) + .where( + TARGET_NAMESPACE + .eq(exactNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + if (association == null + || !exactNamespace.equals(association.get(TARGET_NAMESPACE)) + || !canonicalTenantId.equals(association.get(CANONICAL_TENANT_ID)) + || !Long.valueOf(tenantId).equals(association.get(LEGACY_GAME_SESSION_TENANT_ID)) + || !Long.valueOf(sourceGameRowId).equals(association.get(SOURCE_GAME_ROW_ID)) + || !sourceGameTenantKey.equals(association.get(SOURCE_GAME_TENANT_KEY)) + || !provenanceKind.equals(association.get(ASSOCIATION_PROVENANCE_KIND))) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_TENANT_IDENTITY_MISMATCH: retained association changed or is absent"); + } + } + + private void lockPublishedTenant(String exactNamespace, long tenantId, UUID canonicalTenantId) { + if (dsl.dialect().family() != SQLDialect.POSTGRES) { + return; + } + List.of( + PUBLISHED_CATALOG_LOCK_PREFIX + exactNamespace + ":canonical:" + canonicalTenantId, + PUBLISHED_CATALOG_LOCK_PREFIX + exactNamespace + ":tenant:" + tenantId) + .stream() + .sorted() + .forEach( + key -> + dsl.fetch( + "select pg_advisory_xact_lock(hashtextextended(cast(? as text), 0))", key)); + } + + private void validatePublishedSource( + String exactNamespace, + long tenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + PublishedRealmEntryPolicySetEvidence policySet) { + if (exactNamespace == null + || exactNamespace.isBlank() + || tenantId <= 0 + || canonicalTenantId == null + || NIL_UUID.equals(canonicalTenantId) + || sourceGameRowId <= 0 + || sourceGameTenantKey == null + || sourceGameTenantKey.isBlank() + || !("NEW_GAME_ROW".equals(provenanceKind) + || "RETAINED_GAME_V29".equals(provenanceKind)) + || policySet == null + || !canonicalTenantId.equals(policySet.canonicalTenantId()) + || !policySet.hasValidDigest(OBJECT_MAPPER)) { + throw new IllegalArgumentException( + "PUBLISHED_REALM_CATALOG_OWNER_EVIDENCE_INVALID: exact owner evidence is required"); + } + for (PublishedRealmEntryPolicyEvidence policy : policySet.policies()) { + if (!canonicalTenantId.equals(policy.canonicalTenantId()) + || sourceGameRowId != policy.sourceGameRowId() + || !sourceGameTenantKey.equals(policy.sourceGameTenantKey()) + || !provenanceKind.equals(policy.tenantIdentityProvenanceKind())) { + throw new IllegalArgumentException( + "PUBLISHED_REALM_CATALOG_SOURCE_MISMATCH: policy provenance contradicts the retained association"); + } + } + } + + private void requireExactPublishedRetry( + PublishedRealmCatalogSnapshot stored, + String exactNamespace, + long tenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + PublishedRealmEntryPolicySetEvidence policySet) { + if (!stored.targetNamespace().equals(exactNamespace) + || stored.tenantId() != tenantId + || !stored.canonicalTenantId().equals(canonicalTenantId) + || stored.sourceGameRowId() != sourceGameRowId + || !stored.sourceGameTenantKey().equals(sourceGameTenantKey) + || !stored.tenantIdentityProvenanceKind().equals(provenanceKind) + || !stored.policySetEvidence().equals(policySet)) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_VERSION_CONFLICT: exact published version was reused with changed evidence"); + } + } + + private PublishedRealmCatalogSnapshot requireSnapshotReadback( + PublishedRealmCatalogSnapshot expected) { + PublishedRealmCatalogSnapshot actual = + findPublishedSnapshotInTransaction( + expected.targetNamespace(), expected.tenantId(), expected.catalogRevision()) + .orElseThrow( + () -> + new IllegalStateException( + "PUBLISHED_REALM_CATALOG_READBACK_MISSING: committed snapshot is absent")); + if (!actual.canonicalTenantId().equals(expected.canonicalTenantId()) + || actual.sourceGameRowId() != expected.sourceGameRowId() + || !actual.sourceGameTenantKey().equals(expected.sourceGameTenantKey()) + || !actual.tenantIdentityProvenanceKind().equals(expected.tenantIdentityProvenanceKind()) + || !actual.policySetEvidence().equals(expected.policySetEvidence()) + || actual.entries().size() != expected.entries().size()) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_READBACK_INVALID: committed snapshot differs from its exact input"); + } + for (int index = 0; index < actual.entries().size(); index++) { + PublishedRealmCatalogEntry actualEntry = actual.entries().get(index); + PublishedRealmCatalogEntry expectedEntry = expected.entries().get(index); + if (!actualEntry.realmId().equals(expectedEntry.realmId()) + || !Objects.equals( + actualEntry.playableStateNamespaceId(), expectedEntry.playableStateNamespaceId()) + || actualEntry.namespaceResolution() != expectedEntry.namespaceResolution() + || !actualEntry.policyEvidence().equals(expectedEntry.policyEvidence())) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_READBACK_INVALID: committed entry differs from its exact input"); + } + } + return actual; + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + private void lock(String key) { dsl.fetch("select pg_advisory_xact_lock(hashtextextended(cast(? as text), 0))", key); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java new file mode 100644 index 0000000000..05444bf9fc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.RetainedTenantAssociationIdentity; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal, non-startup owner path that composes a complete Game Design policy set with the + * committed local tenant association before Game Session materializes its immutable catalog. + */ +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The workload namespace and collaborators are validated before use; this internal owner" + + " service is intentionally not a startup or public admission trigger.") +public final class PublishedRealmCatalogOwnerService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private final GameDesignPublishedRealmPolicyClient gameDesignClient; + private final GameSessionRetainedTenantAssociationRepository retainedAssociationRepository; + private final InitialAdmissionBindCatalogRepository catalogRepository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + public PublishedRealmCatalogOwnerService( + GameDesignPublishedRealmPolicyClient gameDesignClient, + GameSessionRetainedTenantAssociationRepository retainedAssociationRepository, + InitialAdmissionBindCatalogRepository catalogRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.retainedAssociationRepository = + Objects.requireNonNull(retainedAssociationRepository, "retainedAssociationRepository"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Reads Game Design and the committed retained-tenant mapping before opening the local owner + * transaction. The returned immutable policy snapshot may stage unresolved private entries; + * admission must select an exact visible entry and that entry must independently carry resolved + * namespace authority before it can be used. + */ + public PublishedRealmCatalogSnapshot materializePublishedSnapshot( + UUID canonicalTenantId, long versionId) { + requireOutsideOwnerTransaction(); + requireCanonicalTenantId(canonicalTenantId); + if (versionId <= 0) { + throw new IllegalArgumentException("Published version ID must be positive"); + } + + var association = + retainedAssociationRepository + .readMinimalAssociation(workloadNamespace, canonicalTenantId) + .orElseThrow( + () -> + new IllegalStateException( + "PUBLISHED_REALM_CATALOG_TENANT_ASSOCIATION_MISSING: committed local identity is required")); + requireAssociationIdentity(association, canonicalTenantId); + + PublishedRealmEntryPolicySetEvidence policySet = + gameDesignClient.listPublishedRealmEntryPolicies(canonicalTenantId.toString(), versionId); + requirePolicySetMatchesAssociation(policySet, association); + + return ownerTransaction.execute( + status -> + catalogRepository.materializePublishedSnapshot( + workloadNamespace, + association.legacyGameSessionTenantId(), + association.canonicalTenantId(), + association.sourceGameRowId(), + association.sourceGameTenantKey(), + association.provenanceKind(), + policySet)); + } + + private void requireAssociationIdentity( + RetainedTenantAssociationIdentity association, UUID canonicalTenantId) { + if (!workloadNamespace.equals(association.targetNamespace()) + || !canonicalTenantId.equals(association.canonicalTenantId()) + || association.legacyGameSessionTenantId() <= 0 + || association.sourceGameRowId() <= 0 + || association.sourceGameTenantKey() == null + || association.sourceGameTenantKey().isBlank() + || !("NEW_GAME_ROW".equals(association.provenanceKind()) + || "RETAINED_GAME_V29".equals(association.provenanceKind()))) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_TENANT_ASSOCIATION_INVALID: committed local mapping is contradictory"); + } + } + + private void requirePolicySetMatchesAssociation( + PublishedRealmEntryPolicySetEvidence policySet, + RetainedTenantAssociationIdentity association) { + if (policySet == null + || !policySet.hasValidDigest(OBJECT_MAPPER) + || !association.canonicalTenantId().equals(policySet.canonicalTenantId())) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_OWNER_SET_INVALID: complete authenticated owner set is required"); + } + for (PublishedRealmEntryPolicyEvidence evidence : policySet.policies()) { + if (!association.canonicalTenantId().equals(evidence.canonicalTenantId()) + || association.sourceGameRowId() != evidence.sourceGameRowId() + || !association.sourceGameTenantKey().equals(evidence.sourceGameTenantKey()) + || !association.provenanceKind().equals(evidence.tenantIdentityProvenanceKind())) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_SOURCE_MISMATCH: Game Design provenance differs from the committed tenant association"); + } + } + } + + private static void requireCanonicalTenantId(UUID canonicalTenantId) { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID must be non-nil"); + } + } + + private static void requireOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Published realm owner reads must complete before the local catalog transaction starts"); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V14__published_realm_catalog_snapshots.sql b/services/game-session-service/src/main/resources/db/migration/V14__published_realm_catalog_snapshots.sql new file mode 100644 index 0000000000..4fa680bab2 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V14__published_realm_catalog_snapshots.sql @@ -0,0 +1,244 @@ +CREATE TABLE gameplay_published_realm_catalog_snapshot ( + target_namespace VARCHAR(63) NOT NULL, + tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + catalog_revision BIGINT NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + tenant_identity_provenance_kind VARCHAR(32) NOT NULL, + version_id BIGINT NOT NULL, + version_number INTEGER NOT NULL, + release_bundle_identity VARCHAR(71) NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL, + manifest_hash VARCHAR(128) NOT NULL, + policy_set_digest VARCHAR(71) NOT NULL, + policy_count INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_published_realm_catalog_snapshot + PRIMARY KEY (target_namespace, tenant_id, catalog_revision), + CONSTRAINT uq_gs_published_realm_catalog_snapshot_version + UNIQUE (target_namespace, tenant_id, version_id), + CONSTRAINT uq_gs_published_realm_catalog_snapshot_canonical + UNIQUE (target_namespace, canonical_tenant_id, catalog_revision), + CONSTRAINT uq_gs_published_realm_catalog_snapshot_owner_identity + UNIQUE (target_namespace, tenant_id, catalog_revision, canonical_tenant_id), + CONSTRAINT fk_gs_published_realm_catalog_snapshot_association + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_retained_tenant_association + (target_namespace, canonical_tenant_id), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_identity + CHECK (tenant_id > 0 AND source_game_row_id > 0 AND version_id > 0 + AND version_number > 0 AND catalog_revision > 0), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_tenant + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_provenance + CHECK (tenant_identity_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_release_digest + CHECK (release_bundle_identity ~ '^sha256:[0-9a-f]{64}$' + AND policy_set_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_policy_count + CHECK (policy_count BETWEEN 1 AND 128), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_namespace + CHECK (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_source_key + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$'), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_labels + CHECK (char_length(publish_workflow_id) BETWEEN 1 AND 1024 + AND char_length(manifest_hash) BETWEEN 1 AND 128) +); + +CREATE TABLE gameplay_published_realm_catalog_identity ( + target_namespace VARCHAR(63) NOT NULL, + tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + initial_world_slug VARCHAR(64) NOT NULL, + realm_id UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_published_realm_catalog_identity + PRIMARY KEY (target_namespace, canonical_tenant_id, realm_slug), + CONSTRAINT uq_gs_published_realm_catalog_identity_id UNIQUE (realm_id), + CONSTRAINT uq_gs_published_realm_catalog_identity_realm_key + UNIQUE (target_namespace, canonical_tenant_id, realm_slug, realm_id), + CONSTRAINT fk_gs_published_realm_catalog_identity_association + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_retained_tenant_association + (target_namespace, canonical_tenant_id), + CONSTRAINT chk_gs_published_realm_catalog_identity_tenant + CHECK (tenant_id > 0 + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_identity_realm_id + CHECK (realm_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_identity_namespace + CHECK (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT chk_gs_published_realm_catalog_identity_selectors + CHECK (realm_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND initial_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$') +); + +CREATE TABLE gameplay_published_realm_catalog_entry ( + target_namespace VARCHAR(63) NOT NULL, + tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + catalog_revision BIGINT NOT NULL, + realm_id UUID NOT NULL, + policy_id UUID NOT NULL, + source_revision_id BIGINT NOT NULL, + world_slug VARCHAR(64) NOT NULL, + world_display_name VARCHAR(128) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + realm_display_name VARCHAR(128) NOT NULL, + visible BOOLEAN NOT NULL, + public_production BOOLEAN NOT NULL, + state_scope VARCHAR(16) NOT NULL, + entry_policy VARCHAR(32) NOT NULL, + policy_json VARCHAR(4096) NOT NULL, + policy_digest VARCHAR(71) NOT NULL, + playable_state_namespace_id UUID, + namespace_resolution VARCHAR(32) NOT NULL, + CONSTRAINT pk_gs_published_realm_catalog_entry + PRIMARY KEY (target_namespace, tenant_id, catalog_revision, realm_id), + CONSTRAINT uq_gs_published_realm_catalog_entry_selector + UNIQUE (target_namespace, tenant_id, catalog_revision, world_slug, realm_slug), + CONSTRAINT uq_gs_published_realm_catalog_entry_realm_slug + UNIQUE (target_namespace, tenant_id, catalog_revision, realm_slug), + CONSTRAINT fk_gs_published_realm_catalog_entry_snapshot + FOREIGN KEY (target_namespace, tenant_id, catalog_revision, canonical_tenant_id) + REFERENCES gameplay_published_realm_catalog_snapshot + (target_namespace, tenant_id, catalog_revision, canonical_tenant_id), + CONSTRAINT fk_gs_published_realm_catalog_entry_identity + FOREIGN KEY (target_namespace, canonical_tenant_id, realm_slug, realm_id) + REFERENCES gameplay_published_realm_catalog_identity + (target_namespace, canonical_tenant_id, realm_slug, realm_id), + CONSTRAINT chk_gs_published_realm_catalog_entry_identity + CHECK (catalog_revision > 0 AND source_revision_id > 0 + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND policy_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_entry_scope + CHECK (state_scope IN ('SHARED', 'ISOLATED') AND entry_policy = 'PRESEEDED_ONLY'), + CONSTRAINT chk_gs_published_realm_catalog_entry_namespace_resolution + CHECK ((namespace_resolution = 'RESOLVED' + AND playable_state_namespace_id IS NOT NULL + AND playable_state_namespace_id <> + '00000000-0000-0000-0000-000000000000'::UUID) + OR (namespace_resolution = 'AWAITING_LIFECYCLE_PROOF' + AND playable_state_namespace_id IS NULL)), + CONSTRAINT chk_gs_published_realm_catalog_entry_isolated_lifecycle_gate + CHECK (NOT (state_scope = 'ISOLATED' AND namespace_resolution = 'RESOLVED')), + CONSTRAINT chk_gs_published_realm_catalog_entry_selectors + CHECK (world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND realm_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + CONSTRAINT chk_gs_published_realm_catalog_entry_digests + CHECK (policy_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(policy_json) BETWEEN 1 AND 4096), + CONSTRAINT chk_gs_published_realm_catalog_entry_display + CHECK (char_length(world_display_name) BETWEEN 1 AND 128 + AND char_length(realm_display_name) BETWEEN 1 AND 128) +); + +CREATE TABLE gameplay_published_tenant_shared_playable_state_namespace ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + allocated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_published_tenant_shared_namespace + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_published_tenant_shared_namespace_id + UNIQUE (playable_state_namespace_id), + CONSTRAINT fk_gs_published_tenant_shared_namespace_association + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_retained_tenant_association + (target_namespace, canonical_tenant_id), + CONSTRAINT chk_gs_published_tenant_shared_namespace_identity + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> + '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_tenant_shared_namespace_namespace + CHECK (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$') +); + +-- Completeness and tenant-wide realmSlug uniqueness are checked at commit after all rows in the +-- bounded policy set have been inserted. No truncated prefix can become a committed snapshot. +-- [jooq ignore start] +CREATE FUNCTION validate_gameplay_published_realm_catalog_set() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + expected_count INTEGER; + actual_count INTEGER; + public_count INTEGER; +BEGIN + SELECT snapshot.policy_count + INTO expected_count + FROM gameplay_published_realm_catalog_snapshot snapshot + WHERE snapshot.target_namespace = NEW.target_namespace + AND snapshot.tenant_id = NEW.tenant_id + AND snapshot.catalog_revision = NEW.catalog_revision; + + SELECT COUNT(*)::INTEGER, + COUNT(*) FILTER (WHERE entry.visible AND entry.public_production)::INTEGER + INTO actual_count, public_count + FROM gameplay_published_realm_catalog_entry entry + WHERE entry.target_namespace = NEW.target_namespace + AND entry.tenant_id = NEW.tenant_id + AND entry.catalog_revision = NEW.catalog_revision; + + IF expected_count IS NULL OR actual_count <> expected_count OR public_count <> 1 THEN + RAISE EXCEPTION 'published realm catalog snapshot is incomplete or ambiguous' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER gameplay_published_realm_catalog_complete_set +AFTER INSERT ON gameplay_published_realm_catalog_entry +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION validate_gameplay_published_realm_catalog_set(); + +CREATE CONSTRAINT TRIGGER gameplay_published_realm_catalog_header_complete_set +AFTER INSERT ON gameplay_published_realm_catalog_snapshot +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION validate_gameplay_published_realm_catalog_set(); + +CREATE FUNCTION reject_gameplay_published_realm_catalog_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session published realm catalog evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER gameplay_published_realm_catalog_snapshot_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_realm_catalog_snapshot +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_snapshot_no_truncate +BEFORE TRUNCATE ON gameplay_published_realm_catalog_snapshot +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_identity_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_realm_catalog_identity +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_identity_no_truncate +BEFORE TRUNCATE ON gameplay_published_realm_catalog_identity +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_entry_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_realm_catalog_entry +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_entry_no_truncate +BEFORE TRUNCATE ON gameplay_published_realm_catalog_entry +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_tenant_shared_namespace_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_tenant_shared_playable_state_namespace +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_tenant_shared_namespace_no_truncate +BEFORE TRUNCATE ON gameplay_published_tenant_shared_playable_state_namespace +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java new file mode 100644 index 0000000000..e49aa8e010 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java @@ -0,0 +1,422 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +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.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class PublishedRealmCatalogRepositoryIntegrationTest { + private static final String NAMESPACE = "published-catalog-test"; + private static final long TENANT_ID = 70123L; + private static final long OTHER_TENANT_ID = 70124L; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OTHER_CANONICAL_TENANT_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String PROVENANCE_KIND = "NEW_GAME_ROW"; + private static final String WORKFLOW = "published-catalog-integration"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final String SIGNATURE = "A".repeat(86) + "=="; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final Table ADMISSION_POINTER = + DSL.table(DSL.name("gameplay_admission_pointer")); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void snapshotsRetryExactlyKeepStableRealmAndSharedIdentityAndGateLifecycleTransitions() { + Fixture fixture = fixture(); + int originalPointerCount = fixture.dsl().fetchCount(ADMISSION_POINTER); + fixture.seedAssociation(TENANT_ID, CANONICAL_TENANT_ID, 501L, "source-game-501"); + + PublishedRealmEntryPolicySetEvidence firstSet = + evidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501", 100L, 1, "Main", "SHARED"); + PublishedRealmCatalogSnapshot first = fixture.materialize(TENANT_ID, firstSet); + PublishedRealmCatalogSnapshot retry = fixture.materialize(TENANT_ID, firstSet); + assertThat(retry).isEqualTo(first); + assertThat(first.tenantId()).isEqualTo(TENANT_ID); + assertThat(first.sourceGameRowId()).isEqualTo(501L); + assertThat(first.catalogRevision()).isEqualTo(1L); + assertThat(first.entries()).allSatisfy( + entry -> assertThat(entry.namespaceResolution()).isEqualTo(NamespaceResolution.RESOLVED)); + UUID mainRealmId = first.entries().getFirst().realmId(); + UUID sharedNamespaceId = first.entries().getFirst().playableStateNamespaceId(); + assertThat(first.entries().get(1).playableStateNamespaceId()).isEqualTo(sharedNamespaceId); + assertThat(first.requireVisibleEntryForAdmission("firemud", "main").realmId()) + .isEqualTo(mainRealmId); + assertThatThrownBy(() -> first.requireVisibleEntryForAdmission("firemud", "side")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_ENTRY_HIDDEN"); + assertThat(first.entries().getFirst().policyEvidence().policy().realmDisplayName()) + .isEqualTo("Main"); + + PublishedRealmEntryPolicySetEvidence changedReuse = + evidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501", 100L, 1, "Changed", "SHARED"); + assertThatThrownBy(() -> fixture.materialize(TENANT_ID, changedReuse)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_VERSION_CONFLICT"); + + PublishedRealmEntryPolicySetEvidence secondSet = + evidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501", 101L, 2, "Renamed", "SHARED"); + PublishedRealmCatalogSnapshot second = fixture.materialize(TENANT_ID, secondSet); + assertThat(second.catalogRevision()).isEqualTo(2L); + assertThat(second.entries().getFirst().realmId()).isEqualTo(mainRealmId); + assertThat(second.entries().getFirst().playableStateNamespaceId()).isEqualTo(sharedNamespaceId); + PublishedRealmCatalogSnapshot originalRead = + fixture.repository.findPublishedSnapshot(NAMESPACE, TENANT_ID, 1L).orElseThrow(); + assertThat(originalRead.entries().getFirst().policyEvidence().policy().realmDisplayName()) + .isEqualTo("Main"); + + assertThatThrownBy( + () -> + fixture.materialize( + TENANT_ID, + evidenceSet( + CANONICAL_TENANT_ID, + 501L, + "source-game-501", + 99L, + 1, + "Older", + "SHARED"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_STALE_VERSION"); + + fixture.seedAssociation(OTHER_TENANT_ID, OTHER_CANONICAL_TENANT_ID, 502L, "source-game-502"); + PublishedRealmCatalogSnapshot otherTenant = + fixture.materialize( + OTHER_TENANT_ID, + evidenceSet( + OTHER_CANONICAL_TENANT_ID, + 502L, + "source-game-502", + 200L, + 1, + "Main", + "SHARED")); + assertThat(otherTenant.entries().getFirst().realmId()).isNotEqualTo(mainRealmId); + assertThat(otherTenant.entries().getFirst().playableStateNamespaceId()) + .isNotEqualTo(sharedNamespaceId); + + PublishedRealmEntryPolicySetEvidence isolatedSet = + evidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501", 102L, 3, "Renamed", "ISOLATED"); + PublishedRealmCatalogSnapshot awaitingLifecycle = fixture.materialize(TENANT_ID, isolatedSet); + assertThat(awaitingLifecycle.entries().getFirst().namespaceResolution()) + .isEqualTo(NamespaceResolution.RESOLVED); + assertThat(awaitingLifecycle.entries().getFirst().requirePlayableStateNamespaceId()) + .isEqualTo(sharedNamespaceId); + assertThat( + awaitingLifecycle.requireVisibleEntryForAdmission("firemud", "main").realmId()) + .isEqualTo(mainRealmId); + assertThat(awaitingLifecycle.entries().get(1).namespaceResolution()) + .isEqualTo(NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + assertThat(awaitingLifecycle.entries().get(1).playableStateNamespaceId()).isNull(); + assertThatThrownBy( + () -> awaitingLifecycle.requireVisibleEntryForAdmission("firemud", "side")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_LIFECYCLE_UNRESOLVED"); + assertThatThrownBy(awaitingLifecycle::requireNamespaceResolved) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_LIFECYCLE_UNRESOLVED"); + + assertThatThrownBy( + () -> + fixture.materialize( + TENANT_ID, + evidenceSet( + CANONICAL_TENANT_ID, + 999L, + "wrong-source-row", + 103L, + 4, + "Renamed", + "SHARED"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_TENANT_IDENTITY_MISMATCH"); + + assertThatThrownBy( + () -> + fixture.materialize( + TENANT_ID, + evidenceSet( + CANONICAL_TENANT_ID, + 501L, + "wrong-source-key", + 104L, + 5, + "Renamed", + "SHARED"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_TENANT_IDENTITY_MISMATCH"); + + assertThatThrownBy( + () -> + fixture.materialize( + TENANT_ID, + evidenceSet( + CANONICAL_TENANT_ID, + 501L, + "source-game-501", + 105L, + 6, + "Renamed", + "SHARED", + "otherworld"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_SELECTOR_CHANGED"); + assertThat(fixture.dsl().fetchCount(ADMISSION_POINTER)).isEqualTo(originalPointerCount); + } + + private static PublishedRealmEntryPolicySetEvidence evidenceSet( + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + String mainDisplayName, + String sideScope) { + return evidenceSet( + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + mainDisplayName, + sideScope, + "firemud"); + } + + private static PublishedRealmEntryPolicySetEvidence evidenceSet( + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + String mainDisplayName, + String sideScope, + String worldSlug) { + String workflow = WORKFLOW + ":" + versionId; + String manifest = "manifest-" + versionId; + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + canonicalTenantId, versionId, workflow, manifest, JSON); + List policies = + List.of( + evidence( + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + workflow, + manifest, + releaseIdentity, + "main", + mainDisplayName, + true, + true, + "SHARED", + worldSlug), + evidence( + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + workflow, + manifest, + releaseIdentity, + "side", + "Side", + "ISOLATED".equals(sideScope), + false, + sideScope, + worldSlug)); + return PublishedRealmEntryPolicySetEvidence.create( + canonicalTenantId, + versionId, + versionNumber, + releaseIdentity, + workflow, + manifest, + policies, + JSON); + } + + private static PublishedRealmEntryPolicyEvidence evidence( + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + String workflow, + String manifest, + String releaseIdentity, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope) { + return evidence( + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + workflow, + manifest, + releaseIdentity, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + "firemud"); + } + + private static PublishedRealmEntryPolicyEvidence evidence( + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + long versionId, + int versionNumber, + String workflow, + String manifest, + String releaseIdentity, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String worldSlug) { + String policyJson = + "{\"schemaVersion\":1,\"worldSlug\":\"" + + worldSlug + + "\",\"worldDisplayName\":\"FireMUD\"," + + "\"realmSlug\":\"" + + realmSlug + + "\",\"realmDisplayName\":\"" + + realmDisplayName + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"" + + stateScope + + "\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + return PublishedRealmEntryPolicyEvidence.create( + UUID.nameUUIDFromBytes( + (canonicalTenantId + ":" + versionId + ":" + realmSlug) + .getBytes(StandardCharsets.UTF_8)), + canonicalTenantId, + PROVENANCE_KIND, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + versionId * 10 + (realmSlug.equals("main") ? 1 : 2), + releaseIdentity, + workflow, + manifest, + RealmEntryPolicy.parse(policyJson, JSON), + JSON); + } + + private static Fixture fixture() { + String schema = "gs_published_catalog_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture(dsl, new InitialAdmissionBindCatalogRepository(dsl), transactions); + } + + private record Fixture( + DSLContext dsl, + InitialAdmissionBindCatalogRepository repository, + TransactionTemplate transactions) { + PublishedRealmCatalogSnapshot materialize( + long tenantId, PublishedRealmEntryPolicySetEvidence policySet) { + return transactions.execute( + status -> + repository.materializePublishedSnapshot( + NAMESPACE, + tenantId, + policySet.canonicalTenantId(), + policySet.policies().getFirst().sourceGameRowId(), + policySet.policies().getFirst().sourceGameTenantKey(), + PROVENANCE_KIND, + policySet)); + } + + void seedAssociation( + long tenantId, UUID canonicalTenantId, long sourceGameRowId, String sourceGameTenantKey) { + dsl.execute( + "INSERT INTO game_session_retained_tenant_association " + + "(operation_id, approval_schema_version, target_namespace, association_request_id, " + + "request_digest, approval_operation_id, signer_key_id, approved_by, " + + "approval_reference, signed_at, legacy_game_session_tenant_id, canonical_tenant_id, " + + "source_game_row_id, source_game_tenant_key, provenance_kind, " + + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " + + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, ?, 'fixture-key', 'fixture-owner', 'fixture-approval', " + + "'2026-01-01T00:00:00Z', ?, ?, ?, ?, ?, ?, ?, ?, '{}', ?, ?)", + UUID.randomUUID(), + NAMESPACE, + UUID.randomUUID(), + DIGEST, + UUID.randomUUID(), + tenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + PROVENANCE_KIND, + DIGEST, + DIGEST, + SIGNATURE, + DIGEST, + DIGEST); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java index 6ba6ecd77b..052e398072 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -176,6 +176,35 @@ void rejectsUnsortedDuplicateAndPartialPolicySets() throws Exception { assertRejected(valid.toBuilder().setPolicyCount(3).build()); } + @Test + void rejectsRealmSlugRepeatedAcrossDifferentWorlds() throws Exception { + PublishedRealmEntryPolicyEvidence earthMain = + evidence( + "00000000-0000-4000-8000-000000000011", + 511L, + policyForWorld("earth", "main", true, true, RealmEntryPolicy.StateScope.SHARED)); + PublishedRealmEntryPolicyEvidence marsMain = + evidence( + "00000000-0000-4000-8000-000000000012", + 512L, + policyForWorld("mars", "main", false, false, RealmEntryPolicy.StateScope.SHARED)); + ListPublishedRealmEntryPoliciesResponse duplicateSet = + validResponse().toBuilder() + .clearPolicies() + .addPolicies(toWire(earthMain)) + .addPolicies(toWire(marsMain)) + .build(); + + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.listPublishedRealmEntryPolicies(any())).thenReturn(duplicateSet); + GameDesignPublishedRealmPolicyClient client = newClient(stub); + + assertThatThrownBy( + () -> client.listPublishedRealmEntryPolicies(TENANT_ID.toString(), VERSION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Game Design published realm policy response is invalid"); + } + @Test void rejectsResponseFromDifferentMtlSWorkloadNamespace() throws Exception { ManagedChannel channel = mock(ManagedChannel.class); @@ -294,6 +323,15 @@ private static RealmEntryPolicy policy( boolean visible, boolean publicProduction, RealmEntryPolicy.StateScope scope) { + return policyForWorld("firemud", realmSlug, visible, publicProduction, scope); + } + + private static RealmEntryPolicy policyForWorld( + String worldSlug, + String realmSlug, + boolean visible, + boolean publicProduction, + RealmEntryPolicy.StateScope scope) { String json = "{\"entryPolicy\":\"PRESEEDED_ONLY\",\"publicProduction\":" + publicProduction @@ -305,7 +343,11 @@ private static RealmEntryPolicy policy( + quote(scope.name()) + ",\"visible\":" + visible - + ",\"worldDisplayName\":\"FireMUD\",\"worldSlug\":\"firemud\"}"; + + ",\"worldDisplayName\":" + + quote(worldSlug) + + ",\"worldSlug\":" + + quote(worldSlug) + + "}"; return RealmEntryPolicy.parse(json, OBJECT_MAPPER); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java new file mode 100644 index 0000000000..d607eae32f --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java @@ -0,0 +1,192 @@ +package unit.net.firedevops.firemud.gamesession.entity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +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.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmCatalogSnapshotTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final long GAME_SESSION_TENANT_ID = 70123L; + private static final long SOURCE_GAME_ROW_ID = 501L; + private static final String SOURCE_GAME_TENANT_KEY = "source-game-501"; + private static final String PROVENANCE_KIND = "RETAINED_GAME_V29"; + private static final String WORKFLOW = "publish:catalog-unit-test"; + private static final String MANIFEST = "manifest-catalog-unit-test"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void selectedSharedEntryRemainsUsableWhilePrivateLifecycleEvidenceIsMissing() { + PublishedRealmEntryPolicySetEvidence policySet = policySet("ISOLATED", true); + UUID sharedNamespaceId = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + PublishedRealmCatalogSnapshot snapshot = + new PublishedRealmCatalogSnapshot( + GAME_SESSION_TENANT_ID, + "unit-test", + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND, + 4L, + policySet, + List.of( + new PublishedRealmCatalogEntry( + GAME_SESSION_TENANT_ID, + 4L, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + sharedNamespaceId, + NamespaceResolution.RESOLVED, + policySet.policies().getFirst()), + new PublishedRealmCatalogEntry( + GAME_SESSION_TENANT_ID, + 4L, + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + null, + NamespaceResolution.AWAITING_LIFECYCLE_PROOF, + policySet.policies().get(1))), + Instant.parse("2026-01-01T00:00:00Z")); + + assertThat(snapshot.requireVisibleEntryForAdmission("earth", "main").realmId()) + .isEqualTo(snapshot.entries().getFirst().realmId()); + assertThat(snapshot.entries().getFirst().requirePlayableStateNamespaceId()) + .isEqualTo(sharedNamespaceId); + assertThatThrownBy(() -> snapshot.requireVisibleEntryForAdmission("earth", "playtest")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_LIFECYCLE_UNRESOLVED"); + assertThatThrownBy( + () -> + new PublishedRealmCatalogEntry( + GAME_SESSION_TENANT_ID, + 4L, + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + sharedNamespaceId, + NamespaceResolution.RESOLVED, + policySet.policies().get(1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("isolated catalog entry cannot resolve"); + assertThatThrownBy(snapshot::requireNamespaceResolved) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_LIFECYCLE_UNRESOLVED"); + } + + @Test + void visibilityGatesAdmissionWithoutReassigningStableNamespaceIdentity() { + PublishedRealmEntryPolicySetEvidence policySet = policySet("SHARED", false); + UUID sharedNamespaceId = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + PublishedRealmCatalogSnapshot snapshot = + new PublishedRealmCatalogSnapshot( + GAME_SESSION_TENANT_ID, + "unit-test", + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND, + 4L, + policySet, + List.of( + new PublishedRealmCatalogEntry( + GAME_SESSION_TENANT_ID, + 4L, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + sharedNamespaceId, + NamespaceResolution.RESOLVED, + policySet.policies().getFirst()), + new PublishedRealmCatalogEntry( + GAME_SESSION_TENANT_ID, + 4L, + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + sharedNamespaceId, + NamespaceResolution.RESOLVED, + policySet.policies().get(1))), + Instant.parse("2026-01-01T00:00:00Z")); + + assertThat(snapshot.entries().get(1).playableStateNamespaceId()).isEqualTo(sharedNamespaceId); + assertThatThrownBy(() -> snapshot.requireVisibleEntryForAdmission("earth", "playtest")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_ENTRY_HIDDEN"); + } + + private static PublishedRealmEntryPolicySetEvidence policySet( + String sideScope, boolean sideVisible) { + long versionId = 9L; + int versionNumber = 3; + String workflow = WORKFLOW; + String releaseBundleIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, versionId, workflow, MANIFEST, JSON); + List policies = + List.of( + evidence( + versionId, + versionNumber, + releaseBundleIdentity, + "main", + true, + true, + "SHARED"), + evidence( + versionId, + versionNumber, + releaseBundleIdentity, + "playtest", + sideVisible, + false, + sideScope)); + return PublishedRealmEntryPolicySetEvidence.create( + CANONICAL_TENANT_ID, + versionId, + versionNumber, + releaseBundleIdentity, + workflow, + MANIFEST, + policies, + JSON); + } + + private static PublishedRealmEntryPolicyEvidence evidence( + long versionId, + int versionNumber, + String releaseBundleIdentity, + String realmSlug, + boolean visible, + boolean publicProduction, + String stateScope) { + String policyJson = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"" + + realmSlug + + "\",\"realmDisplayName\":\"" + + realmSlug + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"" + + stateScope + + "\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + return PublishedRealmEntryPolicyEvidence.create( + UUID.nameUUIDFromBytes((realmSlug + ":policy").getBytes(StandardCharsets.UTF_8)), + CANONICAL_TENANT_ID, + PROVENANCE_KIND, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + versionId, + versionNumber, + versionId * 10 + (realmSlug.equals("main") ? 1 : 2), + releaseBundleIdentity, + WORKFLOW, + MANIFEST, + RealmEntryPolicy.parse(policyJson, JSON), + JSON); + } +} From 7c199a8139f8a69a617dd0ded3d12f5fccc313d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:45:21 +1300 Subject: [PATCH 071/105] Preserve retained-association UUID guards and changed-v2 evidence proof --- ...V13__retained_tenant_payload_retention.sql | 9 +++++ ...tAssociationRepositoryIntegrationTest.java | 35 +++++++++++++++++-- ...DesignRuntimeTenantIdentityClientTest.java | 7 +++- 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql index 4a7e1b1ba9..bba47e99c6 100644 --- a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql +++ b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql @@ -43,6 +43,9 @@ CREATE TABLE game_session_retained_tenant_association_payload ( OR (approval_schema_version = 2 AND game_session_projection_digest ~ '^sha256:[0-9a-f]{64}$') ), + CONSTRAINT chk_gs_retained_tenant_association_payload_approval_operation_id CHECK ( + approval_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), CONSTRAINT chk_gs_retained_tenant_association_payload_digests CHECK ( request_digest ~ '^sha256:[0-9a-f]{64}$' AND game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' @@ -130,6 +133,12 @@ ALTER TABLE game_session_retained_tenant_association ALTER TABLE game_session_retained_tenant_association DROP COLUMN receipt_digest; +ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT chk_gs_retained_tenant_association_operation_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ); + ALTER TABLE game_session_retained_tenant_association ADD CONSTRAINT chk_gs_retained_tenant_association_capture_time CHECK ( captured_at IS NULL OR captured_at <= created_at diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index 143cdf41f2..cb1eebbd9a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -135,6 +135,28 @@ void committedReadRejectsForeignNamespaceBeforeDatabaseAccess() { verifyNoInteractions(dsl, snapshots); } + @Test + void migrationPreservesNonNilAssociationAndApprovalOperationIdsAfterPayloadSplit() { + Fixture fixture = fixture(); + UUID nilUuid = new UUID(0L, 0L); + + assertThatThrownBy( + () -> fixture.insertAssociationMapping(nilUuid, uuid(930), uuid(931), 930L)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("chk_gs_retained_tenant_association_operation_ids"); + assertThatThrownBy( + () -> fixture.insertAssociationMapping(uuid(932), nilUuid, uuid(933), 932L)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("chk_gs_retained_tenant_association_operation_ids"); + + UUID payloadOperationId = uuid(934); + fixture.insertAssociationMapping(payloadOperationId, uuid(935), uuid(936), 934L); + assertThatThrownBy(() -> fixture.insertExpiredPayload(payloadOperationId, nilUuid)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining( + "chk_gs_retained_tenant_association_payload_approval_operation_id"); + } + @Test void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesMinimalAntiReassignmentProof() { Fixture fixture = fixture(); @@ -618,6 +640,12 @@ private record Fixture( TransactionTemplate transactions) { void insertExpiredMapping( UUID operationId, UUID requestId, UUID canonicalTenantId, long legacyTenantId) { + insertAssociationMapping(operationId, requestId, canonicalTenantId, legacyTenantId); + insertExpiredPayload(operationId); + } + + void insertAssociationMapping( + UUID operationId, UUID requestId, UUID canonicalTenantId, long legacyTenantId) { dsl.execute( "INSERT INTO game_session_retained_tenant_association (" + "operation_id, target_namespace, association_request_id, " @@ -630,7 +658,6 @@ void insertExpiredMapping( requestId, legacyTenantId, canonicalTenantId); - insertExpiredPayload(operationId); } void restoreExpiredPayload(UUID operationId) { @@ -638,6 +665,10 @@ void restoreExpiredPayload(UUID operationId) { } private void insertExpiredPayload(UUID operationId) { + insertExpiredPayload(operationId, UUID.randomUUID()); + } + + void insertExpiredPayload(UUID operationId, UUID approvalOperationId) { dsl.execute( "INSERT INTO game_session_retained_tenant_association_payload (" + "operation_id, request_digest, approval_operation_id, approval_schema_version, " @@ -647,7 +678,7 @@ private void insertExpiredPayload(UUID operationId) { + "snapshot_evidence_digest, receipt_digest) VALUES (?, ?, ?, 2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", operationId, "sha256:" + "a".repeat(64), - UUID.randomUUID(), + approvalOperationId, "fixture-owner-key", "owner-reviewer", "approval-" + operationId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java index da2b0d1c33..47ae6c7a0f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -372,18 +372,23 @@ void retainedAssociationRejectsEveryChangedManifestFieldAgainstOriginalDigest() manifest.toBuilder().setApprovedBy("other-approver").build(), manifest.toBuilder().setApprovalReference("other-reference").build(), manifest.toBuilder().setSignedAt("2026-09-30T12:01:00Z").build(), + manifest.toBuilder().setSourceCapturedAt("2026-09-30T11:00:01Z").build(), manifest.toBuilder().setLegacyGameSessionTenantId("24").build(), manifest.toBuilder().setCanonicalTenantId(REQUEST_ID.toString()).build(), manifest.toBuilder().setSourceGameRowId("92").build(), manifest.toBuilder().setSourceGameTenantKey("game-design-tenant-92").build(), manifest.toBuilder().setProvenanceKind("NEW_GAME_ROW").build(), + manifest + .toBuilder() + .setGameSessionProjectionDigest("sha256:" + "c".repeat(64)) + .build(), manifest.toBuilder().setGameSessionEvidenceDigest("sha256:" + "b".repeat(64)).build()); for (GameSessionTenantAssociationManifestEvidence changed : changedManifests) { assertAssociationRejected(valid.toBuilder().setManifest(changed).build(), "manifest digest"); } assertAssociationRejected( - valid.toBuilder().setManifest(manifest.toBuilder().setSchemaVersion(2).build()).build(), + valid.toBuilder().setManifest(manifest.toBuilder().setSchemaVersion(3).build()).build(), "manifest is invalid"); } From e087f8a8f6fa128d4c8a8f7e824fb730699ea4b0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:48:40 +1300 Subject: [PATCH 072/105] Validate composed catalog and retention types and focused proof --- ...PublishedRealmEntryPolicyEvidenceTest.java | 8 ++- .../entity/InitialAdmissionBindCatalog.java | 4 +- .../entity/PublishedRealmCatalogSnapshot.java | 9 ++-- ...InitialAdmissionBindCatalogRepository.java | 49 ++++++++++--------- ...tAssociationRepositoryIntegrationTest.java | 9 ++-- ...RealmCatalogRepositoryIntegrationTest.java | 28 +++-------- ...DesignRuntimeTenantIdentityClientTest.java | 5 +- .../PublishedRealmCatalogSnapshotTest.java | 11 ++--- 8 files changed, 52 insertions(+), 71 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java index 649b9a7176..a34d39ba4d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java @@ -140,15 +140,13 @@ void completeSetRejectsMissingMultipleOrOversizedAddressableSets() { createSet( identity, java.util.Collections.nCopies( - PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1, main))); + PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1, main))); } @Test void completeSetRejectsRealmSlugRepeatedAcrossDifferentWorlds() { - PublishedRealmEntryPolicyEvidence publicRealm = - policyEvidence("main", "earth", true, true); - PublishedRealmEntryPolicyEvidence duplicateRealm = - policyEvidence("main", "mars", false, false); + PublishedRealmEntryPolicyEvidence publicRealm = policyEvidence("main", "earth", true, true); + PublishedRealmEntryPolicyEvidence duplicateRealm = policyEvidence("main", "mars", false, false); assertThatIllegalArgumentException() .isThrownBy( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java index 1ff02be971..2c51ee8fcd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java @@ -6,8 +6,8 @@ /** * Legacy run-owned fixture catalog evidence used by the initial-bind fixture path. * - *

Published Game Design authority is stored and read through - * {@link PublishedRealmCatalogSnapshot}; this row is never promoted into that authority. + *

Published Game Design authority is stored and read through {@link + * PublishedRealmCatalogSnapshot}; this row is never promoted into that authority. */ public record InitialAdmissionBindCatalog( UUID realmId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java index 66268e41bb..0ba16f5745 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java @@ -58,12 +58,15 @@ public record PublishedRealmCatalogSnapshot( if (entry.tenantId() != tenantId || entry.catalogRevision() != catalogRevision || !entry.policyEvidence().equals(policySetEvidence.policies().get(index)) - || !entry.policyEvidence().tenantIdentityProvenanceKind().equals( - tenantIdentityProvenanceKind) + || !entry + .policyEvidence() + .tenantIdentityProvenanceKind() + .equals(tenantIdentityProvenanceKind) || entry.policyEvidence().sourceGameRowId() != sourceGameRowId || !entry.policyEvidence().sourceGameTenantKey().equals(sourceGameTenantKey) || !realmIds.add(entry.realmId())) { - throw new IllegalArgumentException("Catalog snapshot entries are incomplete or contradictory"); + throw new IllegalArgumentException( + "Catalog snapshot entries are incomplete or contradictory"); } } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java index 5bd291c81b..6031bf3073 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java @@ -114,8 +114,8 @@ public InitialAdmissionBindCatalogRepository(DSLContext dsl) { /** * Commits one complete immutable Game Design policy set after its remote owner read has - * completed. The retained association is reread locally under this transaction before any - * catalog identity or snapshot row is written. + * completed. The retained association is reread locally under this transaction before any catalog + * identity or snapshot row is written. */ @Transactional public PublishedRealmCatalogSnapshot materializePublishedSnapshot( @@ -136,7 +136,11 @@ public PublishedRealmCatalogSnapshot materializePublishedSnapshot( policySet); lockPublishedTenant(exactNamespace, tenantId, canonicalTenantId); requireRetainedAssociationMatches( - exactNamespace, tenantId, canonicalTenantId, sourceGameRowId, sourceGameTenantKey, + exactNamespace, + tenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, provenanceKind); Optional exactVersion = @@ -157,8 +161,7 @@ public PublishedRealmCatalogSnapshot materializePublishedSnapshot( } Record current = latestSnapshotHeader(exactNamespace, tenantId); - long catalogRevision = - current == null ? 1L : Math.addExact(current.get(CATALOG_REVISION), 1L); + long catalogRevision = current == null ? 1L : Math.addExact(current.get(CATALOG_REVISION), 1L); if (current != null && current.get(VERSION_NUMBER) >= policySet.versionNumber()) { throw new IllegalStateException( "PUBLISHED_REALM_CATALOG_STALE_VERSION: owner version is not newer than the stored snapshot"); @@ -181,8 +184,8 @@ public PublishedRealmCatalogSnapshot materializePublishedSnapshot( RealmEntryPolicy policy = evidence.policy(); UUID realmId = resolveRealmIdentity(exactNamespace, tenantId, canonicalTenantId, policy); NamespaceAssignment namespace = - resolveNamespace(exactNamespace, tenantId, canonicalTenantId, catalogRevision, realmId, - evidence); + resolveNamespace( + exactNamespace, tenantId, canonicalTenantId, catalogRevision, realmId, evidence); insertPublishedEntry(exactNamespace, tenantId, catalogRevision, realmId, namespace, evidence); entries.add( new PublishedRealmCatalogEntry( @@ -213,8 +216,12 @@ public PublishedRealmCatalogSnapshot materializePublishedSnapshot( @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) public Optional findPublishedSnapshot( String exactNamespace, long tenantId, long catalogRevision) { - if (exactNamespace == null || exactNamespace.isBlank() || tenantId <= 0 || catalogRevision <= 0) { - throw new IllegalArgumentException("Exact namespace, tenant, and catalog revision are required"); + if (exactNamespace == null + || exactNamespace.isBlank() + || tenantId <= 0 + || catalogRevision <= 0) { + throw new IllegalArgumentException( + "Exact namespace, tenant, and catalog revision are required"); } return findPublishedSnapshotInTransaction(exactNamespace, tenantId, catalogRevision); } @@ -355,7 +362,7 @@ private PublishedRealmCatalogSnapshot toPublishedSnapshot(Record header) { String policySetDigest = Objects.requireNonNull(header.get(POLICY_SET_DIGEST)); int policyCount = Objects.requireNonNull(header.get(POLICY_COUNT)); - List rows = + List rows = dsl.selectFrom(PUBLISHED_ENTRY) .where( TARGET_NAMESPACE @@ -502,10 +509,7 @@ private void insertSnapshotHeader( } private UUID resolveRealmIdentity( - String exactNamespace, - long tenantId, - UUID canonicalTenantId, - RealmEntryPolicy policy) { + String exactNamespace, long tenantId, UUID canonicalTenantId, RealmEntryPolicy policy) { Record existing = dsl.selectFrom(PUBLISHED_IDENTITY) .where( @@ -552,7 +556,11 @@ private NamespaceAssignment resolveNamespace( PublishedRealmEntryPolicyEvidence evidence) { Record previous = dsl.selectFrom(PUBLISHED_ENTRY) - .where(TARGET_NAMESPACE.eq(exactNamespace).and(TENANT_ID.eq(tenantId)).and(REALM_ID.eq(realmId))) + .where( + TARGET_NAMESPACE + .eq(exactNamespace) + .and(TENANT_ID.eq(tenantId)) + .and(REALM_ID.eq(realmId))) .orderBy(CATALOG_REVISION.desc()) .limit(1) .fetchOne(); @@ -594,9 +602,7 @@ private UUID getOrCreateCanonicalTenantSharedNamespace( Record existing = dsl.selectFrom(PUBLISHED_SHARED_NAMESPACE) .where( - TARGET_NAMESPACE - .eq(exactNamespace) - .and(ALLOCATED_TENANT_ID.eq(canonicalTenantId))) + TARGET_NAMESPACE.eq(exactNamespace).and(ALLOCATED_TENANT_ID.eq(canonicalTenantId))) .fetchOne(); if (existing != null) { UUID namespaceId = Objects.requireNonNull(existing.get(IDENTITY_NAMESPACE_ID)); @@ -664,9 +670,7 @@ private void requireRetainedAssociationMatches( ASSOCIATION_PROVENANCE_KIND) .from(RETAINED_ASSOCIATION) .where( - TARGET_NAMESPACE - .eq(exactNamespace) - .and(CANONICAL_TENANT_ID.eq(canonicalTenantId))) + TARGET_NAMESPACE.eq(exactNamespace).and(CANONICAL_TENANT_ID.eq(canonicalTenantId))) .fetchOne(); if (association == null || !exactNamespace.equals(association.get(TARGET_NAMESPACE)) @@ -711,8 +715,7 @@ private void validatePublishedSource( || sourceGameRowId <= 0 || sourceGameTenantKey == null || sourceGameTenantKey.isBlank() - || !("NEW_GAME_ROW".equals(provenanceKind) - || "RETAINED_GAME_V29".equals(provenanceKind)) + || !("NEW_GAME_ROW".equals(provenanceKind) || "RETAINED_GAME_V29".equals(provenanceKind)) || policySet == null || !canonicalTenantId.equals(policySet.canonicalTenantId()) || !policySet.hasValidDigest(OBJECT_MAPPER)) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index cb1eebbd9a..e3e4a815d2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -140,12 +140,10 @@ void migrationPreservesNonNilAssociationAndApprovalOperationIdsAfterPayloadSplit Fixture fixture = fixture(); UUID nilUuid = new UUID(0L, 0L); - assertThatThrownBy( - () -> fixture.insertAssociationMapping(nilUuid, uuid(930), uuid(931), 930L)) + assertThatThrownBy(() -> fixture.insertAssociationMapping(nilUuid, uuid(930), uuid(931), 930L)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("chk_gs_retained_tenant_association_operation_ids"); - assertThatThrownBy( - () -> fixture.insertAssociationMapping(uuid(932), nilUuid, uuid(933), 932L)) + assertThatThrownBy(() -> fixture.insertAssociationMapping(uuid(932), nilUuid, uuid(933), 932L)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("chk_gs_retained_tenant_association_operation_ids"); @@ -153,8 +151,7 @@ void migrationPreservesNonNilAssociationAndApprovalOperationIdsAfterPayloadSplit fixture.insertAssociationMapping(payloadOperationId, uuid(935), uuid(936), 934L); assertThatThrownBy(() -> fixture.insertExpiredPayload(payloadOperationId, nilUuid)) .isInstanceOf(DataAccessException.class) - .hasMessageContaining( - "chk_gs_retained_tenant_association_payload_approval_operation_id"); + .hasMessageContaining("chk_gs_retained_tenant_association_payload_approval_operation_id"); } @Test diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java index e49aa8e010..ea0c1e0919 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java @@ -65,8 +65,10 @@ void snapshotsRetryExactlyKeepStableRealmAndSharedIdentityAndGateLifecycleTransi assertThat(first.tenantId()).isEqualTo(TENANT_ID); assertThat(first.sourceGameRowId()).isEqualTo(501L); assertThat(first.catalogRevision()).isEqualTo(1L); - assertThat(first.entries()).allSatisfy( - entry -> assertThat(entry.namespaceResolution()).isEqualTo(NamespaceResolution.RESOLVED)); + assertThat(first.entries()) + .allSatisfy( + entry -> + assertThat(entry.namespaceResolution()).isEqualTo(NamespaceResolution.RESOLVED)); UUID mainRealmId = first.entries().getFirst().realmId(); UUID sharedNamespaceId = first.entries().getFirst().playableStateNamespaceId(); assertThat(first.entries().get(1).playableStateNamespaceId()).isEqualTo(sharedNamespaceId); @@ -100,13 +102,7 @@ void snapshotsRetryExactlyKeepStableRealmAndSharedIdentityAndGateLifecycleTransi fixture.materialize( TENANT_ID, evidenceSet( - CANONICAL_TENANT_ID, - 501L, - "source-game-501", - 99L, - 1, - "Older", - "SHARED"))) + CANONICAL_TENANT_ID, 501L, "source-game-501", 99L, 1, "Older", "SHARED"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("PUBLISHED_REALM_CATALOG_STALE_VERSION"); @@ -115,13 +111,7 @@ void snapshotsRetryExactlyKeepStableRealmAndSharedIdentityAndGateLifecycleTransi fixture.materialize( OTHER_TENANT_ID, evidenceSet( - OTHER_CANONICAL_TENANT_ID, - 502L, - "source-game-502", - 200L, - 1, - "Main", - "SHARED")); + OTHER_CANONICAL_TENANT_ID, 502L, "source-game-502", 200L, 1, "Main", "SHARED")); assertThat(otherTenant.entries().getFirst().realmId()).isNotEqualTo(mainRealmId); assertThat(otherTenant.entries().getFirst().playableStateNamespaceId()) .isNotEqualTo(sharedNamespaceId); @@ -133,14 +123,12 @@ void snapshotsRetryExactlyKeepStableRealmAndSharedIdentityAndGateLifecycleTransi .isEqualTo(NamespaceResolution.RESOLVED); assertThat(awaitingLifecycle.entries().getFirst().requirePlayableStateNamespaceId()) .isEqualTo(sharedNamespaceId); - assertThat( - awaitingLifecycle.requireVisibleEntryForAdmission("firemud", "main").realmId()) + assertThat(awaitingLifecycle.requireVisibleEntryForAdmission("firemud", "main").realmId()) .isEqualTo(mainRealmId); assertThat(awaitingLifecycle.entries().get(1).namespaceResolution()) .isEqualTo(NamespaceResolution.AWAITING_LIFECYCLE_PROOF); assertThat(awaitingLifecycle.entries().get(1).playableStateNamespaceId()).isNull(); - assertThatThrownBy( - () -> awaitingLifecycle.requireVisibleEntryForAdmission("firemud", "side")) + assertThatThrownBy(() -> awaitingLifecycle.requireVisibleEntryForAdmission("firemud", "side")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("PUBLISHED_REALM_CATALOG_LIFECYCLE_UNRESOLVED"); assertThatThrownBy(awaitingLifecycle::requireNamespaceResolved) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java index 47ae6c7a0f..68e22ecbee 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -378,10 +378,7 @@ void retainedAssociationRejectsEveryChangedManifestFieldAgainstOriginalDigest() manifest.toBuilder().setSourceGameRowId("92").build(), manifest.toBuilder().setSourceGameTenantKey("game-design-tenant-92").build(), manifest.toBuilder().setProvenanceKind("NEW_GAME_ROW").build(), - manifest - .toBuilder() - .setGameSessionProjectionDigest("sha256:" + "c".repeat(64)) - .build(), + manifest.toBuilder().setGameSessionProjectionDigest("sha256:" + "c".repeat(64)).build(), manifest.toBuilder().setGameSessionEvidenceDigest("sha256:" + "b".repeat(64)).build()); for (GameSessionTenantAssociationManifestEvidence changed : changedManifests) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java index d607eae32f..95b0cff74b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshotTest.java @@ -10,7 +10,9 @@ 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.gamesession.entity.PublishedRealmCatalogEntry; import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; @@ -126,14 +128,7 @@ private static PublishedRealmEntryPolicySetEvidence policySet( CANONICAL_TENANT_ID, versionId, workflow, MANIFEST, JSON); List policies = List.of( - evidence( - versionId, - versionNumber, - releaseBundleIdentity, - "main", - true, - true, - "SHARED"), + evidence(versionId, versionNumber, releaseBundleIdentity, "main", true, true, "SHARED"), evidence( versionId, versionNumber, From 2b002ffa6887b760843ccd65ae82316a93363380 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:51:24 +1300 Subject: [PATCH 073/105] Prove published catalog owner ordering and record unwired boundary --- .../game-session-service/api-contracts.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 +- ...PublishedRealmCatalogOwnerServiceTest.java | 268 ++++++++++++++++++ 3 files changed, 270 insertions(+), 2 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 58d88b92cd..e3a103fc5f 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -14,7 +14,7 @@ Realm-catalog identity status: Game Session pointer and audit rows persist a sep V12 retains the immutable tenant-association claim; V13 separates its account-linked approval and raw-snapshot payload into an owner-local erasable table. The candidate remains explicitly unwired. Snapshot schema 4 binds the authoritative database capture time; signed approval schema 2 binds that same capture time, the canonical projection digest, and the complete snapshot digest. Registration recaptures under the owner fence, compares the current projection, and verifies the signed full digest after rebinding only the unchanged rows to the original source capture time. Missing/ambiguous legacy capture evidence fails closed and requires new capture; approval, consume, and retry do not renew the 30-day lifetime. `owner_account_id` remains the actual required numeric field; no canonical Account UUID is inferred. The mapping is identity evidence only, not a pointer seed, admission result, membership, actor promotion, or `PLAY` authorization. Focused proof and PostgreSQL limits are recorded below; raw backup edits and restore-gate proof are not claimed. -Published realm-policy receiving foundation: the standalone `GameDesignPublishedRealmPolicyClient` reads the complete same-namespace owner set and returns validated typed set evidence, rejecting incomplete or contradictory owner, child, digest, selector, and cardinality evidence. Its [focused test](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) passes 8/8. The client is unwired; no Game Session catalog or playable-state namespace materialization, World-held pointer binding, actor validation, or `PLAY` admission proof is established. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and [test](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java). +Published realm-policy receiving/catalog preparation: the internal [catalog owner](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java) reads the committed minimal Game Session tenant association and complete Game Design policy set before its local transaction, rejects source-provenance mismatches, and freezes the exact owner evidence into an immutable [catalog snapshot](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java) using the local private tenant ID rather than the Game Design source row ID. Durable realm identity is canonical tenant plus tenant-wide unique `realmSlug`; proven `SHARED` entries retain a stable opaque playable-state namespace, and policy/display-only changes advance `catalogRevision` without changing pointer version or old snapshot reads. Lifecycle resolution is selected-entry scoped: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation exposes no namespace or initial-bind read, while an unrelated unresolved private entry does not block a proven shared-entry read. This service remains unwired; catalog preparation does not bind the World-held pointer or establish World lifecycle, actor validation, or `PLAY` admission. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), the [policy client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and focused [client](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) and [owner-service tests](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: 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 17a3a748f5..47f64c15be 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -14,7 +14,7 @@ Retained bootstrap correction: V8 recognizes only the unchanged, provenance-back Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. -Published realm-policy receiving foundation: the standalone Game Design client validates the complete typed policy set and passed 8 focused unit tests. It remains unwired and does not materialize Game Session catalog identity or playable-state namespaces, bind a World-held admission pointer, validate actors, or prove `PLAY` admission. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java). +Published realm-policy receiving/catalog preparation: the unwired internal owner now stages immutable snapshots from the complete Game Design policy set plus the committed local tenant association, with source-provenance validation and distinct local-private-tenant versus source-row identities. Tenant-wide `realmSlug` identity supports stable opaque namespaces for proven `SHARED` entries; catalog-only policy/display changes advance `catalogRevision` while preserving exact prior snapshots. Lifecycle resolution gates only the selected entry: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation has no namespace or initial-bind read, without blocking a proven shared entry. This is not a World-held pointer commit, World lifecycle proof, actor validation, activation, or `PLAY` admission; the service remains unwired. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md), [owner service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java), [snapshot](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java), and [owner-service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). Initial-admission owner boundary: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java new file mode 100644 index 0000000000..619a962bf0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java @@ -0,0 +1,268 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.RetainedTenantAssociationIdentity; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmCatalogOwnerServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final long GAME_SESSION_TENANT_ID = 70123L; + private static final long SOURCE_GAME_ROW_ID = 91L; + private static final String SOURCE_GAME_TENANT_KEY = "game-design-tenant-91"; + private static final String PROVENANCE_KIND = "RETAINED_GAME_V29"; + private static final long VERSION_ID = 44L; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final GameDesignPublishedRealmPolicyClient gameDesignClient = + mock(GameDesignPublishedRealmPolicyClient.class); + private final GameSessionRetainedTenantAssociationRepository associationRepository = + mock(GameSessionRetainedTenantAssociationRepository.class); + private final InitialAdmissionBindCatalogRepository catalogRepository = + mock(InitialAdmissionBindCatalogRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final PublishedRealmCatalogOwnerService service = + new PublishedRealmCatalogOwnerService( + gameDesignClient, + associationRepository, + catalogRepository, + transactionManager, + NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsInvocationInsideActualTransactionBeforeAnyOwnerRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("before the local catalog transaction starts"); + + verifyNoInteractions( + gameDesignClient, associationRepository, catalogRepository, transactionManager); + } + + @Test + void missingOrContradictoryMinimalAssociationDeniesBeforeGameDesignRead() { + when(associationRepository.readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID)) + .thenReturn(Optional.empty()) + .thenReturn( + Optional.of( + association( + "other", + CANONICAL_TENANT_ID, + GAME_SESSION_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND))) + .thenReturn( + Optional.of( + association( + NAMESPACE, + UUID.randomUUID(), + GAME_SESSION_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND))); + + for (int attempt = 0; attempt < 3; attempt++) { + assertThatThrownBy( + () -> service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) + .isInstanceOf(IllegalStateException.class); + } + + verify(associationRepository, times(3)) + .readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID); + verifyNoInteractions(gameDesignClient, catalogRepository, transactionManager); + } + + @Test + void rejectsPolicySetWithWrongSourceProvenanceBeforeOwnerTransaction() { + RetainedTenantAssociationIdentity association = + association( + NAMESPACE, + CANONICAL_TENANT_ID, + GAME_SESSION_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND); + when(associationRepository.readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID)) + .thenReturn(Optional.of(association)); + when( + gameDesignClient.listPublishedRealmEntryPolicies( + CANONICAL_TENANT_ID.toString(), VERSION_ID)) + .thenReturn( + policySet( + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID + 1, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND)); + + assertThatThrownBy( + () -> service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_CATALOG_SOURCE_MISMATCH"); + + verify(gameDesignClient) + .listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID.toString(), VERSION_ID); + verifyNoInteractions(catalogRepository, transactionManager); + } + + @Test + void readsBothOwnersBeforeStartingReadCommittedTransactionAndKeepsIdentityFieldsDistinct() { + RetainedTenantAssociationIdentity association = + association( + NAMESPACE, + CANONICAL_TENANT_ID, + GAME_SESSION_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND); + PublishedRealmEntryPolicySetEvidence policySet = + policySet( + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND); + PublishedRealmCatalogSnapshot snapshot = mock(PublishedRealmCatalogSnapshot.class); + when(associationRepository.readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID)) + .thenReturn(Optional.of(association)); + when( + gameDesignClient.listPublishedRealmEntryPolicies( + CANONICAL_TENANT_ID.toString(), VERSION_ID)) + .thenReturn(policySet); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(catalogRepository.materializePublishedSnapshot( + NAMESPACE, + GAME_SESSION_TENANT_ID, + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND, + policySet)) + .thenReturn(snapshot); + + assertThat(service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) + .isSameAs(snapshot); + + InOrder ordered = + inOrder(associationRepository, gameDesignClient, transactionManager, catalogRepository); + ordered.verify(associationRepository).readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID); + ordered + .verify(gameDesignClient) + .listPublishedRealmEntryPolicies(CANONICAL_TENANT_ID.toString(), VERSION_ID); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + ordered.verify(transactionManager).getTransaction(definition.capture()); + ordered + .verify(catalogRepository) + .materializePublishedSnapshot( + NAMESPACE, + GAME_SESSION_TENANT_ID, + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND, + policySet); + ordered.verify(transactionManager).commit(any(TransactionStatus.class)); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(GAME_SESSION_TENANT_ID).isNotEqualTo(SOURCE_GAME_ROW_ID); + } + + private static RetainedTenantAssociationIdentity association( + String namespace, + UUID canonicalTenantId, + long gameSessionTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + return new RetainedTenantAssociationIdentity( + namespace, + canonicalTenantId, + gameSessionTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + } + + private static PublishedRealmEntryPolicySetEvidence policySet( + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + int versionNumber = 3; + String workflow = "publish:realm-catalog-owner-test"; + String manifest = "manifest-realm-catalog-owner-test"; + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + canonicalTenantId, VERSION_ID, workflow, manifest, JSON); + String policyJson = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + PublishedRealmEntryPolicyEvidence evidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + canonicalTenantId, + provenanceKind, + sourceGameRowId, + sourceGameTenantKey, + VERSION_ID, + versionNumber, + 301L, + releaseIdentity, + workflow, + manifest, + RealmEntryPolicy.parse(policyJson, JSON), + JSON); + return PublishedRealmEntryPolicySetEvidence.create( + canonicalTenantId, + VERSION_ID, + versionNumber, + releaseIdentity, + workflow, + manifest, + List.of(evidence), + JSON); + } +} From cb75e2e7a0443ebd691cd9db9ebbd64f6e7ea835 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 18:51:24 +1300 Subject: [PATCH 074/105] Reject null v2 capture projections in both owner stores --- ...n_tenant_association_payload_retention.sql | 1 + ...tAssociationRepositoryIntegrationTest.java | 23 +++++++++++++-- ...V13__retained_tenant_payload_retention.sql | 1 + ...tAssociationRepositoryIntegrationTest.java | 28 +++++++++++++++++-- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql b/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql index 4ffdf38855..885b0e6135 100644 --- a/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql +++ b/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql @@ -32,6 +32,7 @@ CREATE TABLE game_design_game_session_tenant_association_payload ( CONSTRAINT chk_gd_game_session_association_payload_capture CHECK ( (schema_version = 1 AND game_session_projection_digest IS NULL) OR (schema_version = 2 + AND game_session_projection_digest IS NOT NULL AND game_session_projection_digest ~ '^sha256:[0-9a-f]{64}$') ), CONSTRAINT chk_gd_game_session_association_payload_labels CHECK ( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index 771e1ecf28..48a5b080c4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -101,6 +101,20 @@ void exactRetryReturnsSameSignedEvidenceWithoutMutatingSourceOrAssociation() thr assertThat(fixture.read(first)).contains(first); } + @Test + void v2PayloadRequiresProjectionDigestWhileHistoricalV1MayOmitIt() { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + UUID v1OperationId = uuid(910); + fixture.insertExpiredAssociation(v1OperationId, 910L, fixture.retainedSource()); + fixture.insertRawPayload(v1OperationId, 1, null); + + UUID v2OperationId = uuid(911); + fixture.insertExpiredAssociation(v2OperationId, 911L, fixture.freshSource()); + assertThatThrownBy(() -> fixture.insertRawPayload(v2OperationId, 2, null)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("chk_gd_game_session_association_payload_capture"); + } + @Test void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesImmutableAssociationClaim() throws Exception { @@ -619,15 +633,20 @@ void insertExpiredAssociation( } void insertRawPayload(UUID operationId) { + insertRawPayload(operationId, 2, "sha256:" + "a".repeat(64)); + } + + void insertRawPayload(UUID operationId, int schemaVersion, String projectionDigest) { dsl() .execute( "INSERT INTO game_design_game_session_tenant_association_payload (" + "operation_id, schema_version, signer_key_id, approved_by, approval_reference, " + "signed_at, game_session_projection_digest, game_session_evidence_digest, " - + "manifest_digest, signature) VALUES (?, 2, 'owner-key', 'owner', 'case', ?, ?, ?, ?, ?)", + + "manifest_digest, signature) VALUES (?, ?, 'owner-key', 'owner', 'case', ?, ?, ?, ?, ?)", operationId, + schemaVersion, java.time.Instant.now().toString(), - "sha256:" + "a".repeat(64), + projectionDigest, "sha256:" + "b".repeat(64), "sha256:" + "c".repeat(64), Base64.getEncoder().encodeToString(new byte[64])); diff --git a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql index bba47e99c6..79baf46583 100644 --- a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql +++ b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql @@ -41,6 +41,7 @@ CREATE TABLE game_session_retained_tenant_association_payload ( CONSTRAINT chk_gs_retained_tenant_association_payload_capture CHECK ( (approval_schema_version = 1 AND game_session_projection_digest IS NULL) OR (approval_schema_version = 2 + AND game_session_projection_digest IS NOT NULL AND game_session_projection_digest ~ '^sha256:[0-9a-f]{64}$') ), CONSTRAINT chk_gs_retained_tenant_association_payload_approval_operation_id CHECK ( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index e3e4a815d2..1b2f008538 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -154,6 +154,20 @@ void migrationPreservesNonNilAssociationAndApprovalOperationIdsAfterPayloadSplit .hasMessageContaining("chk_gs_retained_tenant_association_payload_approval_operation_id"); } + @Test + void v2PayloadRequiresProjectionDigestWhileHistoricalV1MayOmitIt() { + Fixture fixture = fixture(); + UUID v1OperationId = uuid(937); + fixture.insertAssociationMapping(v1OperationId, uuid(938), uuid(939), 937L); + fixture.insertExpiredPayload(v1OperationId, uuid(940), 1, null); + + UUID v2OperationId = uuid(941); + fixture.insertAssociationMapping(v2OperationId, uuid(942), uuid(943), 941L); + assertThatThrownBy(() -> fixture.insertExpiredPayload(v2OperationId, uuid(944), 2, null)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("chk_gs_retained_tenant_association_payload_capture"); + } + @Test void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesMinimalAntiReassignmentProof() { Fixture fixture = fixture(); @@ -666,21 +680,31 @@ private void insertExpiredPayload(UUID operationId) { } void insertExpiredPayload(UUID operationId, UUID approvalOperationId) { + insertExpiredPayload( + operationId, + approvalOperationId, + 2, + "sha256:" + "b".repeat(64)); + } + + void insertExpiredPayload( + UUID operationId, UUID approvalOperationId, int schemaVersion, String projectionDigest) { dsl.execute( "INSERT INTO game_session_retained_tenant_association_payload (" + "operation_id, request_digest, approval_operation_id, approval_schema_version, " + "signer_key_id, approved_by, approval_reference, signed_at, " + "game_session_projection_digest, game_session_evidence_digest, " + "approval_manifest_digest, approval_signature, snapshot_canonical_json, " - + "snapshot_evidence_digest, receipt_digest) VALUES (?, ?, ?, 2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + "snapshot_evidence_digest, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", operationId, "sha256:" + "a".repeat(64), approvalOperationId, + schemaVersion, "fixture-owner-key", "owner-reviewer", "approval-" + operationId, java.time.Instant.now().toString(), - "sha256:" + "b".repeat(64), + projectionDigest, "sha256:" + "c".repeat(64), "sha256:" + "d".repeat(64), Base64.getEncoder().encodeToString(new byte[64]), From 8194361da3f1c83e624ef2d84207fbe2883cdccd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:01:38 +1300 Subject: [PATCH 075/105] Bound Account profile failures and reuse verified UUID identity --- .../accountservice/AccountUuidText.java | 22 ++ .../controller/AccountRequestReaders.java | 16 +- .../dto/AuthenticationResult.java | 15 +- .../service/impl/AccountGrpcService.java | 71 ++++-- .../service/impl/AccountServiceImpl.java | 86 ++++---- .../RuntimeAccountIdentityGrpcService.java | 17 +- .../accountservice/AccountUuidTextTest.java | 37 ++++ .../dto/AuthenticationResultTest.java | 32 ++- .../service/impl/AccountGrpcServiceTest.java | 202 ++++++++++++++++++ .../service/impl/AccountServiceImplTest.java | 11 +- ...RuntimeAccountIdentityGrpcServiceTest.java | 20 ++ 11 files changed, 421 insertions(+), 108 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java new file mode 100644 index 0000000000..04a0818452 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.accountservice; + +import java.util.UUID; + +/** Canonical non-nil UUID text parsing at Account's local transport boundaries. */ +public final class AccountUuidText { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountUuidText() {} + + public static UUID parseOrNull(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java index 3608a1a482..a0acc080e9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java @@ -1,26 +1,18 @@ package net.firedevops.firemud.accountservice.controller; import java.util.UUID; +import net.firedevops.firemud.accountservice.AccountUuidText; import net.firedevops.firemud.common.security.RequestIdValidation; final class AccountRequestReaders { - private static final UUID NIL_UUID = new UUID(0L, 0L); - private AccountRequestReaders() {} static UUID requireAccountUuid(String accountId) { - if (accountId == null || accountId.isBlank()) { + UUID parsed = AccountUuidText.parseOrNull(accountId); + if (parsed == null) { throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); } - try { - UUID parsed = UUID.fromString(accountId); - if (NIL_UUID.equals(parsed) || !parsed.toString().equals(accountId)) { - throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); - } - return parsed; - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException("accountId must be a canonical non-nil UUID", exception); - } + return parsed; } static long requireAccountId(String accountId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java index de76f21c51..e218c98e09 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java @@ -1,22 +1,11 @@ package net.firedevops.firemud.accountservice.dto; -import java.util.UUID; +import net.firedevops.firemud.accountservice.AccountUuidText; /** Result of a successful authentication attempt. */ public record AuthenticationResult(String accountId, String authToken) { - private static final UUID NIL_UUID = new UUID(0L, 0L); - public AuthenticationResult { - if (accountId == null) { - throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); - } - UUID parsedAccountId; - try { - parsedAccountId = UUID.fromString(accountId); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException("accountId must be a canonical non-nil UUID", exception); - } - if (NIL_UUID.equals(parsedAccountId) || !parsedAccountId.toString().equals(accountId)) { + if (AccountUuidText.parseOrNull(accountId) == null) { throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index d21af640df..983a938543 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -38,6 +38,7 @@ import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; +import net.firedevops.firemud.accountservice.AccountUuidText; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; @@ -61,6 +62,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; +import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -233,18 +235,11 @@ private void requireCallerAccountSubject(UUID accountUuid) { } private static UUID requireCanonicalAccountUuid(String value) { - if (value == null || value.isBlank()) { + UUID accountUuid = AccountUuidText.parseOrNull(value); + if (accountUuid == null) { throw new InvalidRequestException("accountId must be a canonical non-nil UUID", null); } - try { - UUID accountUuid = UUID.fromString(value); - if (accountUuid.equals(new UUID(0L, 0L)) || !accountUuid.toString().equals(value)) { - throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); - } - return accountUuid; - } catch (IllegalArgumentException exception) { - throw new InvalidRequestException("accountId must be a canonical non-nil UUID", exception); - } + return accountUuid; } private DirectTextCallerContext directTextCaller( @@ -669,6 +664,12 @@ public void getProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ignored) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(appError("GetProfile", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } @@ -775,21 +776,39 @@ public void updateProfile( long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); requireCallerAccountSubject(accountUuid); - long accountId = accountService.resolveAccountStorageId(accountUuid); - JsonNode node = JsonMapper.builder().build().readTree(request.getProfileJson()); + long accountId; + try { + accountId = accountService.resolveAccountStorageId(accountUuid); + } catch (IllegalArgumentException ex) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError(appError("UpdateProfile", "NOT_FOUND", ex.getMessage())) + .build()); + responseObserver.onCompleted(); + return; + } + JsonNode node; + ProfilePresenceVisibilityPolicy policy; + try { + node = JsonMapper.builder().build().readTree(request.getProfileJson()); + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("Profile update must be an object"); + } + String policyName = node.path("presenceVisibilityPolicy").asText(null); + policy = + ProfilePresenceVisibilityPolicy.valueOf( + policyName == null + ? ProfilePresenceVisibilityPolicy.FRIENDS_ONLY.name() + : policyName); + } catch (JacksonException | IllegalArgumentException ex) { + throw new InvalidRequestException("profileJson must contain a valid profile update", ex); + } String displayName = node.path("displayName").asText(null); String bio = node.path("bio").asText(null); - String presenceVisibilityPolicy = node.path("presenceVisibilityPolicy").asText(null); accountService.updateProfile( new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - tenantId, - accountId, - displayName, - bio, - ProfilePresenceVisibilityPolicy.valueOf( - presenceVisibilityPolicy == null - ? ProfilePresenceVisibilityPolicy.FRIENDS_ONLY.name() - : presenceVisibilityPolicy))); + tenantId, accountId, displayName, bio, policy)); UpdateProfileResponse response = UpdateProfileResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -809,7 +828,7 @@ public void updateProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); - } catch (Exception ex) { + } catch (IllegalArgumentException ex) { UpdateProfileResponse response = UpdateProfileResponse.newBuilder() .setSuccess(false) @@ -817,6 +836,14 @@ public void updateProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ignored) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError( + appError("UpdateProfile", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 2e819853fd..8427dff753 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -515,7 +515,9 @@ public DirectTextJoinScope issueDirectTextConnectScope( || !caller.playableStateScope().equals(target.playableStateScope())) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } - requireAuthenticationEligible(requireAccount(caller.accountId())); + Account account = requireAccount(caller.accountId()); + requireAuthenticationEligible(account); + String accountUuid = requireAuthenticationPersistedIdentity(account).toString(); RuntimeRealmTarget current = requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); if (!isPublicProductionRealm(current)) { @@ -540,7 +542,7 @@ public DirectTextJoinScope issueDirectTextConnectScope( Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); String scopeId = mintAndRetainConnectScope( - new BootstrapContext(caller.accountId()), current, evaluatedAt, expiresAt); + new BootstrapContext(caller.accountId(), accountUuid), current, evaluatedAt, expiresAt); return new DirectTextJoinScope(scopeId, expiresAt.toString()); } @@ -1012,25 +1014,6 @@ private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { } private JoinEvaluation evaluateJoin(VerifiedJoinScope scope, boolean lockEntitlement) { - return evaluateJoin( - new ConnectScopeContext( - scope.accountId(), - requireAuthenticationPersistedIdentity(requireAccount(scope.accountId())).toString(), - scope.tenantId(), - scope.realmId(), - scope.worldSlug(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion(), - Instant.parse(scope.evaluatedAt()), - Instant.parse(scope.connectScopeExpiresAt())), - lockEntitlement); - } - - private JoinEvaluation evaluateJoin(ConnectScopeContext scope, boolean lockEntitlement) { RuntimeRealmTarget target; try { target = requireCurrentConnectScopeTarget(scope); @@ -1421,7 +1404,7 @@ private BootstrapContext requireBootstrapContext(String bootstrapToken) { if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); } - return new BootstrapContext(accountId); + return new BootstrapContext(accountId, accountUuid); } catch (IllegalArgumentException ex) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token", ex); } @@ -1676,9 +1659,7 @@ private String mintConnectScopeId( RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { - String accountUuid = - requireAuthenticationPersistedIdentity(requireAccount(bootstrapContext.accountId())) - .toString(); + String accountUuid = bootstrapContext.accountUuid(); long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); return mintToken( accountUuid, @@ -1831,16 +1812,49 @@ private void validateConnectScopeRoute( } private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext scopeContext) { - RuntimeRealmTarget currentRealm = - requireRealmTarget( - scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); - if (currentRealm.tenantId() != scopeContext.tenantId() - || !currentRealm.realmId().equals(scopeContext.realmId()) - || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) - || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) - || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() - || currentRealm.catalogRevision() != scopeContext.catalogRevision() - || currentRealm.pointerVersion() != scopeContext.pointerVersion()) { + return requireCurrentConnectScopeTarget( + scopeContext.tenantId(), + scopeContext.realmId(), + scopeContext.worldSlug(), + scopeContext.realmSlug(), + scopeContext.playableStateNamespaceId(), + scopeContext.playableStateScope(), + scopeContext.gameInstanceId(), + scopeContext.catalogRevision(), + scopeContext.pointerVersion()); + } + + private RuntimeRealmTarget requireCurrentConnectScopeTarget(VerifiedJoinScope scope) { + return requireCurrentConnectScopeTarget( + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()); + } + + private RuntimeRealmTarget requireCurrentConnectScopeTarget( + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion) { + RuntimeRealmTarget currentRealm = requireRealmTarget(tenantId, worldSlug, realmSlug); + if (currentRealm.tenantId() != tenantId + || !currentRealm.realmId().equals(realmId) + || !currentRealm.playableStateNamespaceId().equals(playableStateNamespaceId) + || !currentRealm.stateScope().equals(playableStateScope) + || currentRealm.gameInstanceId() != gameInstanceId + || currentRealm.catalogRevision() != catalogRevision + || currentRealm.pointerVersion() != pointerVersion) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } return currentRealm; @@ -2499,7 +2513,7 @@ public void afterCommit() { }); } - private record BootstrapContext(long accountId) {} + private record BootstrapContext(long accountId, String accountUuid) {} private record JoinAuditPayload( long accountId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java index 6607f43f82..ad77b09762 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; import net.firedevops.firemud.account.v1.RuntimeAccountIdentityServiceGrpc; +import net.firedevops.firemud.accountservice.AccountUuidText; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -52,8 +53,8 @@ public void resolveRuntimeAccountIdentity( return; } - UUID canonicalAccountId = parseCanonicalNonNilUuid(request.getCanonicalAccountId()); - UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalAccountId = AccountUuidText.parseOrNull(request.getCanonicalAccountId()); + UUID requestId = AccountUuidText.parseOrNull(request.getRequestId()); if (canonicalAccountId == null || requestId == null || !request.getUnknownFields().asMap().isEmpty()) { @@ -158,18 +159,6 @@ private static boolean hasExactPersistedIdentity(Account account, UUID canonical return AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()); } - private static UUID parseCanonicalNonNilUuid(String value) { - if (value == null) { - return null; - } - try { - UUID parsed = UUID.fromString(value); - return !NIL_UUID.equals(parsed) && parsed.toString().equals(value) ? parsed : null; - } catch (IllegalArgumentException ex) { - return null; - } - } - private static boolean hasConnectionFailureSqlState(Throwable failure) { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { if (cause instanceof SQLException exception) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java new file mode 100644 index 0000000000..dc67f3cc10 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.accountservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +class AccountUuidTextTest { + @Test + void acceptsCanonicalNonNilUuidText() { + String value = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + + assertEquals(UUID.fromString(value), AccountUuidText.parseOrNull(value)); + } + + @ParameterizedTest + @NullSource + @ValueSource( + strings = { + "", + " ", + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + "1-1-1-1-1", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "4cae05e8-7a6b-4b14-9d44-665e3eec450b " + }) + void rejectsMissingNumericMalformedNilAndNoncanonicalText(String value) { + assertNull(AccountUuidText.parseOrNull(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java index aa3f5a8179..755a553ad1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java @@ -4,6 +4,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; class AuthenticationResultTest { @Test @@ -14,15 +17,24 @@ void acceptsCanonicalNonNilAccountUuid() { assertEquals("4cae05e8-7a6b-4b14-9d44-665e3eec450b", result.accountId()); } - @Test - void rejectsNonCanonicalOrNilAccountUuid() { - assertThrows(IllegalArgumentException.class, () -> new AuthenticationResult(null, "token")); - assertThrows(IllegalArgumentException.class, () -> new AuthenticationResult("12", "token")); - assertThrows( - IllegalArgumentException.class, - () -> new AuthenticationResult("00000000-0000-0000-0000-000000000000", "token")); - assertThrows( - IllegalArgumentException.class, - () -> new AuthenticationResult("4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", "token")); + @ParameterizedTest + @NullSource + @ValueSource( + strings = { + "", + " ", + "12", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + "1-1-1-1-1", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b" + }) + void rejectsNonCanonicalOrNilAccountUuid(String accountId) { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, () -> new AuthenticationResult(accountId, "token")); + + assertEquals("accountId must be a canonical non-nil UUID", exception.getMessage()); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 010957180a..fc69de24a6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -67,6 +67,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; @@ -948,6 +949,207 @@ void getProfileRejectsMismatchedCallerSubjectBeforeStorageResolution() { Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); } + @ParameterizedTest + @ValueSource(strings = {"resolution", "profile"}) + void getProfileBoundsUnprovedIdentityAndUnavailableAuthority(String failureStage) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + if ("resolution".equals(failureStage)) { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalStateException("private Account source-row provenance detail")); + } else { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getProfile(1L, 2L)) + .thenThrow(new DataAccessResourceFailureException("private Account database detail")); + } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + } + + @ParameterizedTest + @ValueSource(strings = {"resolution", "profile"}) + void updateProfileBoundsUnprovedIdentityAndUnavailableAuthority(String failureStage) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + if ("resolution".equals(failureStage)) { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalStateException("private Account source-row provenance detail")); + } else { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.updateProfile(Mockito.any())) + .thenThrow(new DataAccessResourceFailureException("private Account database detail")); + } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertFalse(observer.response().getSuccess()); + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + } + + @Test + void profileMethodsPreserveMissingAccountOutcome() { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalArgumentException("Account not found")); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver getObserver = new RecordingObserver<>(); + RecordingObserver updateObserver = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> { + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + getObserver); + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson("{}") + .build(), + updateObserver); + }); + + assertEquals("NOT_FOUND", getObserver.response().getError().getCode()); + assertEquals("NOT_FOUND", updateObserver.response().getError().getCode()); + assertTrue(getObserver.completed()); + assertTrue(updateObserver.completed()); + Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); + Mockito.verify(accountService, Mockito.never()).updateProfile(Mockito.any()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "42", + "1-1-1-1-1", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B" + }) + void profileMethodsRejectNoncanonicalAccountUuidBeforeResolution(String accountUuid) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver getObserver = new RecordingObserver<>(); + RecordingObserver updateObserver = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> { + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build(), + getObserver); + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .setProfileJson("{}") + .build(), + updateObserver); + }); + + assertEquals("INVALID_ARGUMENT", getObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", updateObserver.response().getError().getCode()); + assertTrue(getObserver.completed()); + assertTrue(updateObserver.completed()); + Mockito.verifyNoInteractions(accountService); + } + + @ParameterizedTest + @ValueSource(strings = {"", "{", "null", "[]", "{\"presenceVisibilityPolicy\":\"UNKNOWN\"}"}) + void updateProfileRejectsMalformedJsonAndPolicyWithInvalidArgument(String profileJson) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson(profileJson) + .build(), + observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService, Mockito.never()).updateProfile(Mockito.any()); + } + + @Test + void updateProfilePreservesCallerSubjectPermissionDenial() { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson("{}") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + private static ListPresenceVisibilityPoliciesRequest presencePolicyRequest( String... accountUuids) { ListPresenceVisibilityPoliciesRequest.Builder builder = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index e0074444de..4966a212eb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4514,7 +4514,7 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable } @Test - void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { + void listBootstrapRealmsReadsFreshEntitlementsAndReusesVerifiedAccountIdentity() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); @@ -4585,12 +4585,21 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { var firstCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) .findByTenantId(7L); + org.mockito.Mockito.clearInvocations(accountRepository); var secondCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); assertEquals(2, firstCall.size()); assertEquals(2, secondCall.size()); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(7L); + org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).findById(11L); + JwtUtil tokenReader = new JwtUtil(JWT_SECRET, 3600000L); + for (var realm : secondCall) { + var claims = tokenReader.parseToken(realm.connectScopeId()).getPayload(); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + } } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java index 2cad980ed2..6d2af29a7a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java @@ -131,6 +131,26 @@ void rejectsNoncanonicalNilAndOpenMetadataRequestsBeforeOwnerRead() { verifyNoInteractions(repository); } + @ParameterizedTest + @ValueSource( + strings = { + "", + " ", + "42", + "not-a-uuid", + "1-1-1-1-1", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b" + }) + void rejectsInvalidAccountAndRequestUuidTextWithoutOwnerRead(String value) { + assertThat(status(call(request(value, REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(request(ACCOUNT_ID.toString(), value), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + @Test void returnsNotFoundAndFailsClosedForMalformedAmbiguousOrMismatchedProvenance() { when(repository.findByAccountUuid(ACCOUNT_ID)) From c19d010095802adbe32712cf4eb50377871dbb85 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:01:54 +1300 Subject: [PATCH 076/105] Correct current Account authentication UUID contract status --- .../architecture/microservices/account-service/api-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a5e5de1f81..80e67164fe 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -66,7 +66,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; its Account component exposes the persisted UUID, while profile fields retain their current identifiers. This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration returns the persisted Account UUID in `AccountDto.id` / `CreateAccountResponse.account_id` and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. On connect-token cache misses and text `PLAY`, consumers currently proceed only when `membershipExists` and `gameplayAdmissionAllowed` are true; they do not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. Cached-success connect-token replay can return without fresh membership, entitlement, or pointer checks. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`; when membership exists but gameplay admission is false, connect-token issuance instead returns `CONNECT_TOKEN_REJECTED`. On checked paths, consumers therefore do not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current login/auth/bootstrap results and tenant/profile/member DTOs still use numeric account and tenant identities; only registration and the Account components of the existing Account-local exports now use Account UUID. Migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; its Account component exposes the persisted UUID, while profile fields retain their current identifiers. This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration returns the persisted Account UUID in `AccountDto.id` / `CreateAccountResponse.account_id` and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. On connect-token cache misses and text `PLAY`, consumers currently proceed only when `membershipExists` and `gameplayAdmissionAllowed` are true; they do not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. Cached-success connect-token replay can return without fresh membership, entitlement, or pointer checks. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`; when membership exists but gameplay admission is false, connect-token issuance instead returns `CONNECT_TOKEN_REJECTED`. On checked paths, consumers therefore do not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current `AuthenticationResult.accountId` and `PlayerBootstrapResult.accountId` use canonical Account UUIDs. `ConnectTokenResult`, `ConnectTokenResponse`, `ProfileDto`, `RuntimeMembershipDto`, and `TenantDataExportDto` still carry numeric account and/or tenant identifiers. Registration `AccountDto.id` and the Account components of existing Account-local exports also use Account UUIDs. Migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current vs Target Export Lifecycle From b7039a1e42846255b93c1b68415a3d68151f2038 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:03:05 +1300 Subject: [PATCH 077/105] Compile and format retained catalog regression proof --- ...tAssociationRepositoryIntegrationTest.java | 2 +- ...tAssociationRepositoryIntegrationTest.java | 6 +---- ...PublishedRealmCatalogOwnerServiceTest.java | 26 +++++++------------ 3 files changed, 11 insertions(+), 23 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index 48a5b080c4..e166fd751c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -102,7 +102,7 @@ void exactRetryReturnsSameSignedEvidenceWithoutMutatingSourceOrAssociation() thr } @Test - void v2PayloadRequiresProjectionDigestWhileHistoricalV1MayOmitIt() { + void v2PayloadRequiresProjectionDigestWhileHistoricalV1MayOmitIt() throws Exception { Fixture fixture = fixtureWithFreshAndRetainedSources(); UUID v1OperationId = uuid(910); fixture.insertExpiredAssociation(v1OperationId, 910L, fixture.retainedSource()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index 1b2f008538..d509056d3c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -680,11 +680,7 @@ private void insertExpiredPayload(UUID operationId) { } void insertExpiredPayload(UUID operationId, UUID approvalOperationId) { - insertExpiredPayload( - operationId, - approvalOperationId, - 2, - "sha256:" + "b".repeat(64)); + insertExpiredPayload(operationId, approvalOperationId, 2, "sha256:" + "b".repeat(64)); } void insertExpiredPayload( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java index 619a962bf0..ca7005aa15 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.RetainedTenantAssociationIdentity; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import net.firedevops.firemud.gamesession.service.PublishedRealmCatalogOwnerService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -68,8 +69,7 @@ void clearTransactionState() { void rejectsInvocationInsideActualTransactionBeforeAnyOwnerRead() { TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) + assertThatThrownBy(() -> service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("before the local catalog transaction starts"); @@ -106,8 +106,7 @@ void missingOrContradictoryMinimalAssociationDeniesBeforeGameDesignRead() { .isInstanceOf(IllegalStateException.class); } - verify(associationRepository, times(3)) - .readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID); + verify(associationRepository, times(3)).readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID); verifyNoInteractions(gameDesignClient, catalogRepository, transactionManager); } @@ -123,9 +122,8 @@ void rejectsPolicySetWithWrongSourceProvenanceBeforeOwnerTransaction() { PROVENANCE_KIND); when(associationRepository.readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID)) .thenReturn(Optional.of(association)); - when( - gameDesignClient.listPublishedRealmEntryPolicies( - CANONICAL_TENANT_ID.toString(), VERSION_ID)) + when(gameDesignClient.listPublishedRealmEntryPolicies( + CANONICAL_TENANT_ID.toString(), VERSION_ID)) .thenReturn( policySet( CANONICAL_TENANT_ID, @@ -133,8 +131,7 @@ void rejectsPolicySetWithWrongSourceProvenanceBeforeOwnerTransaction() { SOURCE_GAME_TENANT_KEY, PROVENANCE_KIND)); - assertThatThrownBy( - () -> service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) + assertThatThrownBy(() -> service.materializePublishedSnapshot(CANONICAL_TENANT_ID, VERSION_ID)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("PUBLISHED_REALM_CATALOG_SOURCE_MISMATCH"); @@ -154,17 +151,12 @@ void readsBothOwnersBeforeStartingReadCommittedTransactionAndKeepsIdentityFields SOURCE_GAME_TENANT_KEY, PROVENANCE_KIND); PublishedRealmEntryPolicySetEvidence policySet = - policySet( - CANONICAL_TENANT_ID, - SOURCE_GAME_ROW_ID, - SOURCE_GAME_TENANT_KEY, - PROVENANCE_KIND); + policySet(CANONICAL_TENANT_ID, SOURCE_GAME_ROW_ID, SOURCE_GAME_TENANT_KEY, PROVENANCE_KIND); PublishedRealmCatalogSnapshot snapshot = mock(PublishedRealmCatalogSnapshot.class); when(associationRepository.readMinimalAssociation(NAMESPACE, CANONICAL_TENANT_ID)) .thenReturn(Optional.of(association)); - when( - gameDesignClient.listPublishedRealmEntryPolicies( - CANONICAL_TENANT_ID.toString(), VERSION_ID)) + when(gameDesignClient.listPublishedRealmEntryPolicies( + CANONICAL_TENANT_ID.toString(), VERSION_ID)) .thenReturn(policySet); when(transactionManager.getTransaction(any(TransactionDefinition.class))) .thenReturn(new SimpleTransactionStatus()); From 10972d4d54923595addd5d5ea6f0eda3b12cece2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:29:34 +1300 Subject: [PATCH 078/105] Bind initial admission to immutable published realm snapshots --- .../game-session-service/api-contracts.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 4 +- .../entity/InitialAdmissionBindAttempt.java | 63 ++- ...InitialAdmissionBindAttemptRepository.java | 101 +++-- .../service/InitialAdmissionBindRequest.java | 45 +- .../PublishedRealmCatalogOwnerService.java | 7 +- ...ishedRealmInitialAdmissionBindCommand.java | 43 ++ ...dRealmInitialAdmissionBindCoordinator.java | 417 ++++++++++++++++++ ...abaseInitialAdmissionBindOwnerService.java | 237 +++++++++- .../V15__published_initial_admission_bind.sql | 73 +++ ...lAdmissionBindPostgresIntegrationTest.java | 195 ++++++++ ...ialAdmissionBindAttemptRepositoryTest.java | 9 + ...lmInitialAdmissionBindCoordinatorTest.java | 126 ++++++ .../impl/InitialAdmissionBindServiceTest.java | 7 +- 14 files changed, 1275 insertions(+), 54 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCommand.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index e3a103fc5f..29b7304e8f 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -14,7 +14,7 @@ Realm-catalog identity status: Game Session pointer and audit rows persist a sep V12 retains the immutable tenant-association claim; V13 separates its account-linked approval and raw-snapshot payload into an owner-local erasable table. The candidate remains explicitly unwired. Snapshot schema 4 binds the authoritative database capture time; signed approval schema 2 binds that same capture time, the canonical projection digest, and the complete snapshot digest. Registration recaptures under the owner fence, compares the current projection, and verifies the signed full digest after rebinding only the unchanged rows to the original source capture time. Missing/ambiguous legacy capture evidence fails closed and requires new capture; approval, consume, and retry do not renew the 30-day lifetime. `owner_account_id` remains the actual required numeric field; no canonical Account UUID is inferred. The mapping is identity evidence only, not a pointer seed, admission result, membership, actor promotion, or `PLAY` authorization. Focused proof and PostgreSQL limits are recorded below; raw backup edits and restore-gate proof are not claimed. -Published realm-policy receiving/catalog preparation: the internal [catalog owner](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java) reads the committed minimal Game Session tenant association and complete Game Design policy set before its local transaction, rejects source-provenance mismatches, and freezes the exact owner evidence into an immutable [catalog snapshot](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java) using the local private tenant ID rather than the Game Design source row ID. Durable realm identity is canonical tenant plus tenant-wide unique `realmSlug`; proven `SHARED` entries retain a stable opaque playable-state namespace, and policy/display-only changes advance `catalogRevision` without changing pointer version or old snapshot reads. Lifecycle resolution is selected-entry scoped: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation exposes no namespace or initial-bind read, while an unrelated unresolved private entry does not block a proven shared-entry read. This service remains unwired; catalog preparation does not bind the World-held pointer or establish World lifecycle, actor validation, or `PLAY` admission. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), the [policy client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and focused [client](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) and [owner-service tests](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). +Published realm-policy receiving/catalog preparation: the lazy internal [catalog owner](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java) reads the committed minimal Game Session tenant association and complete Game Design policy set before its local transaction, rejects source-provenance mismatches, and freezes the exact owner evidence into an immutable [catalog snapshot](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java) using the local private tenant ID rather than the Game Design source row ID. Durable realm identity is canonical tenant plus tenant-wide unique `realmSlug`; proven `SHARED` entries retain a stable opaque playable-state namespace, and policy/display-only changes advance `catalogRevision` without changing pointer version or old snapshot reads. Lifecycle resolution is selected-entry scoped: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation exposes no namespace or initial-bind read, while an unrelated unresolved private entry does not block a proven shared-entry read. An explicit internal [published bind coordinator](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java) selects an exact V14 snapshot/entry, then cross-checks authored launch and World lifecycle readback before persisting a V14-linked intent and acquiring/attaching the World hold; its GS transaction commits pointer, audit, and outcome together. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID because the existing launch API uses one numeric ID for both roles; a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is validated against authored launch readback and stored separately from the V14 release digest; no identity translation is inferred. New attempts retain the configured target namespace, canonical tenant UUID, retained local GS tenant ID, selected realm/namespace/revision, published version/release evidence, and exact local launch tuple; V9 fixture attempts remain separately identified historical evidence. The new composition and focused proof have not yet been run in this worktree. It does not establish actor validation, roster cardinality, strict Account `JOIN`, or `PLAY` admission. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), the [policy client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and focused [client](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) and [owner-service tests](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: 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 47f64c15be..d2597ae4c5 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -14,7 +14,9 @@ Retained bootstrap correction: V8 recognizes only the unchanged, provenance-back Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. -Published realm-policy receiving/catalog preparation: the unwired internal owner now stages immutable snapshots from the complete Game Design policy set plus the committed local tenant association, with source-provenance validation and distinct local-private-tenant versus source-row identities. Tenant-wide `realmSlug` identity supports stable opaque namespaces for proven `SHARED` entries; catalog-only policy/display changes advance `catalogRevision` while preserving exact prior snapshots. Lifecycle resolution gates only the selected entry: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation has no namespace or initial-bind read, without blocking a proven shared entry. This is not a World-held pointer commit, World lifecycle proof, actor validation, activation, or `PLAY` admission; the service remains unwired. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md), [owner service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java), [snapshot](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java), and [owner-service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). +Published realm-policy receiving/catalog preparation: the lazy internal owner stages immutable snapshots from the complete Game Design policy set plus the committed local tenant association, with source-provenance validation and distinct local-private-tenant versus source-row identities. Tenant-wide `realmSlug` identity supports stable opaque namespaces for proven `SHARED` entries; catalog-only policy/display changes advance `catalogRevision` while preserving exact prior snapshots. Lifecycle resolution gates only the selected entry: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation has no namespace or initial-bind read, without blocking a proven shared entry. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md), [owner service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java), [snapshot](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java), and [owner-service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). + +Published-snapshot initial-bind composition: the explicit internal coordinator consumes that immutable V14 snapshot and exact visible public `SHARED` `PRESEEDED_ONLY` entry, then cross-checks authored launch and World's exact ACTIVE lifecycle readback, including template, descriptor, version, release-bundle ID/reference, version-state epoch, and lifecycle epoch. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID: the existing authored-launch API passes one numeric tenant ID to both local ownership and Game Design descriptor lookup, so a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is retained as separate launch evidence alongside the V14 release digest, without inferred identity conversion. V15 links new `V14_PUBLISHED` attempts to the exact snapshot and entry while retaining historical V9 attempts as `V9_FIXTURE`; the owner writes `PRESEEDED_ONLY` directly and conservatively sets the legacy `requiresCharacterSelection` pointer field true. No startup/environment trigger or raw fixture promotion is added. Focused source-distinct fail-closed and PostgreSQL bind proofs are authored but this worktree has not run validation; restart/lost-response/finalize ambiguity remains for the consolidated proof. This code does not implement strict Account `JOIN`, actor/roster validation, or `PLAY` admission. See the [coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java), [V15 migration](../../../services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql), and [API contract status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Initial-admission owner boundary: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java index 1b3f1221d9..a4c33f15b9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java @@ -24,7 +24,68 @@ public record InitialAdmissionBindAttempt( Long auditEventId, Instant createdAt, Instant updatedAt, - Instant terminalAt) { + Instant terminalAt, + String catalogSourceKind, + String publishedTargetNamespace, + UUID canonicalTenantId, + Long gameTemplateId, + String launchDescriptorId, + Long releaseBundleId, + String publishedReleaseBundleRef, + Long versionStateEpoch) { + /** Historical V9 fixture attempt shape retained for existing tests and migration readers. */ + public InitialAdmissionBindAttempt( + UUID attemptId, + long tenantId, + String initialAdmissionRequestId, + String requestDigest, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + boolean expectedNoPriorPointer, + long catalogRevision, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + UUID holdId, + UUID holdFence, + Status status, + Long pointerId, + Long auditEventId, + Instant createdAt, + Instant updatedAt, + Instant terminalAt) { + this( + attemptId, + tenantId, + initialAdmissionRequestId, + requestDigest, + realmId, + playableStateNamespaceId, + playableStateScope, + expectedNoPriorPointer, + catalogRevision, + gameInstanceId, + versionId, + activeLifecycleEpoch, + holdId, + holdFence, + status, + pointerId, + auditEventId, + createdAt, + updatedAt, + terminalAt, + "V9_FIXTURE", + null, + null, + null, + null, + null, + null, + null); + } + public enum Status { PENDING, COMMITTED, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java index d416468e94..067905f79a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java @@ -15,10 +15,11 @@ import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerRecord; -import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayInitialAdmissionBindAttemptRecord; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; import org.jooq.SQLDialect; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -28,6 +29,19 @@ public class InitialAdmissionBindAttemptRepository { private static final String ATTEMPT_LOCK_PREFIX = "initial-admission-bind-attempt:"; private static final String REALM_LOCK_PREFIX = "initial-admission-bind-realm:"; + private static final Field CATALOG_SOURCE_KIND = field("catalog_source_kind", String.class); + private static final Field FIXTURE_CATALOG_REALM_ID = + field("fixture_catalog_realm_id", UUID.class); + private static final Field PUBLISHED_TARGET_NAMESPACE = + field("published_target_namespace", String.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field GAME_TEMPLATE_ID = field("game_template_id", Long.class); + private static final Field LAUNCH_DESCRIPTOR_ID = + field("launch_descriptor_id", String.class); + private static final Field RELEASE_BUNDLE_ID = field("release_bundle_id", Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + field("published_release_bundle_ref", String.class); + private static final Field VERSION_STATE_EPOCH = field("version_state_epoch", Long.class); private final DSLContext dsl; @@ -49,7 +63,8 @@ public void lockAttemptAndRealm(long tenantId, String requestId, UUID realmId) { public Optional findByTenantAndRequestId( long tenantId, String requestId) { - return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + return dsl.select(DSL.asterisk()) + .from(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) .where( GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT .TENANT_ID @@ -62,7 +77,8 @@ public Optional findByTenantAndRequestId( public Optional findByTenantAndRequestIdForUpdate( long tenantId, String requestId) { - return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + return dsl.select(DSL.asterisk()) + .from(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) .where( GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT .TENANT_ID @@ -76,7 +92,8 @@ public Optional findByTenantAndRequestIdForUpdate( public Optional findPendingByTenantAndRealmForUpdate( long tenantId, UUID realmId) { - return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + return dsl.select(DSL.asterisk()) + .from(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) .where( GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT .TENANT_ID @@ -88,25 +105,47 @@ public Optional findPendingByTenantAndRealmForUpdat } public InitialAdmissionBindAttempt insertPending(InitialAdmissionBindAttempt attempt) { - GameplayInitialAdmissionBindAttemptRecord record = - dsl.newRecord(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT); - record.setAttemptId(attempt.attemptId()); - record.setTenantId(attempt.tenantId()); - record.setInitialAdmissionRequestId(attempt.initialAdmissionRequestId()); - record.setRequestDigest(attempt.requestDigest()); - record.setRealmId(attempt.realmId()); - record.setPlayableStateNamespaceId(attempt.playableStateNamespaceId()); - record.setPlayableStateScope(attempt.playableStateScope()); - record.setExpectedNoPriorPointer(true); - record.setCatalogRevision(attempt.catalogRevision()); - record.setGameInstanceId(attempt.gameInstanceId()); - record.setVersionId(attempt.versionId()); - record.setActiveLifecycleEpoch(attempt.activeLifecycleEpoch()); - record.setStatus(Status.PENDING.name()); - record.setCreatedAt(toLocalDateTime(attempt.createdAt())); - record.setUpdatedAt(toLocalDateTime(attempt.updatedAt())); - record.setTerminalAt(null); - record.store(); + dsl.insertInto(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.ATTEMPT_ID, attempt.attemptId()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TENANT_ID, attempt.tenantId()) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.INITIAL_ADMISSION_REQUEST_ID, + attempt.initialAdmissionRequestId()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.REQUEST_DIGEST, attempt.requestDigest()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.REALM_ID, attempt.realmId()) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.PLAYABLE_STATE_NAMESPACE_ID, + attempt.playableStateNamespaceId()) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.PLAYABLE_STATE_SCOPE, + attempt.playableStateScope()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.EXPECTED_NO_PRIOR_POINTER, true) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.CATALOG_REVISION, attempt.catalogRevision()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.GAME_INSTANCE_ID, attempt.gameInstanceId()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.VERSION_ID, attempt.versionId()) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.ACTIVE_LIFECYCLE_EPOCH, + attempt.activeLifecycleEpoch()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS, Status.PENDING.name()) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.CREATED_AT, + toLocalDateTime(attempt.createdAt())) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT, + toLocalDateTime(attempt.updatedAt())) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT, null) + .set(CATALOG_SOURCE_KIND, attempt.catalogSourceKind()) + .set( + FIXTURE_CATALOG_REALM_ID, + "V9_FIXTURE".equals(attempt.catalogSourceKind()) ? attempt.realmId() : null) + .set(PUBLISHED_TARGET_NAMESPACE, attempt.publishedTargetNamespace()) + .set(CANONICAL_TENANT_ID, attempt.canonicalTenantId()) + .set(GAME_TEMPLATE_ID, attempt.gameTemplateId()) + .set(LAUNCH_DESCRIPTOR_ID, attempt.launchDescriptorId()) + .set(RELEASE_BUNDLE_ID, attempt.releaseBundleId()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, attempt.publishedReleaseBundleRef()) + .set(VERSION_STATE_EPOCH, attempt.versionStateEpoch()) + .execute(); return findByTenantAndRequestId(attempt.tenantId(), attempt.initialAdmissionRequestId()) .orElseThrow(); } @@ -224,7 +263,7 @@ public GameplayAdmissionPointer insertPointer( record.setPublicProductionRealm(true); record.setRequiresCharacterSelection(catalog.requiresCharacterSelection()); record.setStateScope("SHARED"); - record.setCharacterCreationPolicy("ALLOW_NEW"); + record.setCharacterCreationPolicy(catalog.characterCreationPolicy()); record.setLastUpdatedBy("game-session-initial-admission-bind"); record.setLastUpdateReason("initial admission pointer bind"); record.setCreatedAt(toLocalDateTime(now)); @@ -265,7 +304,15 @@ private InitialAdmissionBindAttempt toEntity(Record record) { record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.AUDIT_EVENT_ID), toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.CREATED_AT)), toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT)), - toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT))); + toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT)), + record.get(CATALOG_SOURCE_KIND), + record.get(PUBLISHED_TARGET_NAMESPACE), + record.get(CANONICAL_TENANT_ID), + record.get(GAME_TEMPLATE_ID), + record.get(LAUNCH_DESCRIPTOR_ID), + record.get(RELEASE_BUNDLE_ID), + record.get(PUBLISHED_RELEASE_BUNDLE_REF), + record.get(VERSION_STATE_EPOCH)); } private GameplayAdmissionPointer toPointer(Record record) { @@ -296,4 +343,8 @@ private GameplayAdmissionPointer toPointer(Record record) { pointer.setUpdatedAt(toInstant(record.get(GAMEPLAY_ADMISSION_POINTER.UPDATED_AT))); return pointer; } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java index a3c17fc381..c5c0c1daf1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.service; +import java.util.UUID; + /** Runtime-bound GS intent persisted before the coordinator contacts the World hold owner. */ public record InitialAdmissionBindRequest( long tenantId, @@ -9,4 +11,45 @@ public record InitialAdmissionBindRequest( String requestDigest, long gameInstanceId, long versionId, - long activeLifecycleEpoch) {} + long activeLifecycleEpoch, + PublishedCatalogBinding publishedCatalog, + LaunchEvidence launchEvidence) { + /** Historical V9 fixture request shape. New published admissions must use the full shape. */ + public InitialAdmissionBindRequest( + long tenantId, + String worldSlug, + String realmSlug, + String initialAdmissionRequestId, + String requestDigest, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch) { + this( + tenantId, + worldSlug, + realmSlug, + initialAdmissionRequestId, + requestDigest, + gameInstanceId, + versionId, + activeLifecycleEpoch, + null, + null); + } + + public boolean isPublishedCatalogRequest() { + return publishedCatalog != null && launchEvidence != null; + } + + /** Exact V14 snapshot identity; version and selected entry are checked against that snapshot. */ + public record PublishedCatalogBinding( + String targetNamespace, UUID canonicalTenantId, long catalogRevision) {} + + /** Authored launch evidence independently confirmed by World lifecycle readback. */ + public record LaunchEvidence( + long gameTemplateId, + String launchDescriptorId, + long releaseBundleId, + String publishedReleaseBundleRef, + long versionStateEpoch) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java index 05444bf9fc..e66bc69970 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java @@ -11,6 +11,9 @@ import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.RetainedTenantAssociationIdentity; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -26,6 +29,8 @@ justification = "The workload namespace and collaborators are validated before use; this internal owner" + " service is intentionally not a startup or public admission trigger.") +@Service +@Lazy public final class PublishedRealmCatalogOwnerService { private static final UUID NIL_UUID = new UUID(0L, 0L); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @@ -41,7 +46,7 @@ public PublishedRealmCatalogOwnerService( GameSessionRetainedTenantAssociationRepository retainedAssociationRepository, InitialAdmissionBindCatalogRepository catalogRepository, PlatformTransactionManager transactionManager, - String workloadNamespace) { + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); this.retainedAssociationRepository = Objects.requireNonNull(retainedAssociationRepository, "retainedAssociationRepository"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCommand.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCommand.java new file mode 100644 index 0000000000..46331ba0a6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCommand.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.UUID; + +/** Explicit internal request to launch and bind one exact published realm for first admission. */ +public record PublishedRealmInitialAdmissionBindCommand( + UUID canonicalTenantId, + long publishedVersionId, + long gameTemplateId, + long ownerAccountId, + String worldSlug, + String realmSlug, + String initialAdmissionRequestId) { + public PublishedRealmInitialAdmissionBindCommand { + if (canonicalTenantId == null + || new UUID(0L, 0L).equals(canonicalTenantId) + || publishedVersionId <= 0 + || gameTemplateId <= 0 + || ownerAccountId <= 0 + || !canonicalUuid(initialAdmissionRequestId)) { + throw new IllegalArgumentException("Published initial admission identity is incomplete"); + } + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + } + + private static boolean canonicalUuid(String value) { + if (value == null) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static void requireSlug(String value, String name) { + if (value == null || !value.matches("[a-z0-9]+(?:-[a-z0-9]+)*") || value.length() > 64) { + throw new IllegalArgumentException(name + " must be a canonical realm-policy slug"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java new file mode 100644 index 0000000000..943d0e0040 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java @@ -0,0 +1,417 @@ +package net.firedevops.firemud.gamesession.service; + +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.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +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.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; +import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +/** Explicit internal composition of one immutable published realm with the World initial-bind hold. */ +@Service +@Lazy +public final class PublishedRealmInitialAdmissionBindCoordinator { + private static final String DIGEST_DOMAIN = "firemud.published-realm-initial-admission-bind.v1"; + private static final String RUNNING = "RUNNING"; + + private final PublishedRealmCatalogOwnerService publishedCatalogOwner; + private final GameInstanceService gameInstanceService; + private final InitialAdmissionBindOwnerService ownerService; + private final WorldManagementClient worldManagementClient; + + public PublishedRealmInitialAdmissionBindCoordinator( + PublishedRealmCatalogOwnerService publishedCatalogOwner, + GameInstanceService gameInstanceService, + InitialAdmissionBindOwnerService ownerService, + WorldManagementClient worldManagementClient) { + this.publishedCatalogOwner = + Objects.requireNonNull(publishedCatalogOwner, "publishedCatalogOwner"); + this.gameInstanceService = Objects.requireNonNull(gameInstanceService, "gameInstanceService"); + this.ownerService = Objects.requireNonNull(ownerService, "ownerService"); + this.worldManagementClient = + Objects.requireNonNull(worldManagementClient, "worldManagementClient"); + } + + /** + * Runs only when explicitly invoked by an internal owner. Retries reuse the authored launch, + * immutable published revision, request identity, World hold, and GS owner attempt. + */ + public Result coordinate(PublishedRealmInitialAdmissionBindCommand command) { + Objects.requireNonNull(command, "command"); + PublishedRealmCatalogSnapshot snapshot = + publishedCatalogOwner.materializePublishedSnapshot( + command.canonicalTenantId(), command.publishedVersionId()); + PublishedRealmCatalogEntry entry = + snapshot.requireVisibleEntryForAdmission(command.worldSlug(), command.realmSlug()); + RealmEntryPolicy policy = entry.policyEvidence().policy(); + if (snapshot.policySetEvidence().versionId() != command.publishedVersionId() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || entry.namespaceResolution() != PublishedRealmCatalogEntry.NamespaceResolution.RESOLVED) { + throw unresolved( + "INITIAL_ADMISSION_PUBLISHED_POLICY_UNSUPPORTED: only an exact visible public SHARED PRESEEDED_ONLY entry with resolved namespace is admissible"); + } + if (snapshot.sourceGameRowId() != snapshot.tenantId()) { + throw unresolved( + "INITIAL_ADMISSION_LAUNCH_TENANT_IDENTITY_UNAVAILABLE: existing authored launch accepts one numeric tenant ID for both the retained local GS key and the Game Design descriptor lookup; a source/local identity adapter is required"); + } + + RunOwnedInitialLaunchResult launch = + gameInstanceService.startRunOwnedInitialLaunch( + new StartSessionRequest( + snapshot.tenantId(), + command.gameTemplateId(), + command.initialAdmissionRequestId(), + command.ownerAccountId())); + GameInstanceDto target = requireExactActiveLaunch(launch, command, snapshot); + WorldInstanceLifecycleSnapshot lifecycle = requireExactWorldLifecycle(target, command, snapshot); + if (launch.activeLifecycleEpoch() != lifecycle.getLifecycleEpoch()) { + throw unresolved( + "INITIAL_ADMISSION_WORLD_LIFECYCLE_MISMATCH: ACTIVE epoch differs from authored launch proof"); + } + long lifecycleEpoch = lifecycle.getLifecycleEpoch(); + String requestDigest = requestDigest(command, snapshot, entry, target, lifecycle); + InitialAdmissionBindRequest request = + new InitialAdmissionBindRequest( + snapshot.tenantId(), + command.worldSlug(), + command.realmSlug(), + command.initialAdmissionRequestId(), + requestDigest, + target.id(), + command.publishedVersionId(), + lifecycleEpoch, + new InitialAdmissionBindRequest.PublishedCatalogBinding( + snapshot.targetNamespace(), snapshot.canonicalTenantId(), snapshot.catalogRevision()), + new InitialAdmissionBindRequest.LaunchEvidence( + command.gameTemplateId(), + lifecycle.getLaunchDescriptorId(), + parsePositiveId(lifecycle.getReleaseBundleId(), "releaseBundleId"), + lifecycle.getPublishedReleaseBundleRef(), + lifecycle.getVersionStateEpoch())); + var attempt = ownerService.beginIntent(request); + requireExactAttempt(attempt, request, entry); + + AcquireInitialAdmissionBindHoldResponse acquire = + worldManagementClient.acquireInitialAdmissionBindHold( + snapshot.tenantId(), + target.id(), + command.publishedVersionId(), + lifecycleEpoch, + command.initialAdmissionRequestId(), + requestDigest, + entry.realmId(), + entry.requirePlayableStateNamespaceId(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + snapshot.catalogRevision()); + if (acquire == null || acquire.hasError() || !acquire.hasHold()) { + throw unresolved("INITIAL_ADMISSION_WORLD_HOLD_UNRESOLVED: World did not return the exact hold"); + } + InitialAdmissionBindHold hold = acquire.getHold(); + InitialAdmissionBindHoldBinding binding = + requireExactHold(hold, request, entry, snapshot.catalogRevision()); + + if (hold.getStatus() == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED + || hold.getStatus() == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED) { + return terminalResult(ownerService.read(binding), binding, attempt); + } + if (!isRetryable(hold.getStatus())) { + throw unresolved("INITIAL_ADMISSION_WORLD_HOLD_UNRESOLVED: World returned an unknown hold state"); + } + + InitialAdmissionBindAttempt attached = ownerService.attachHold(binding); + requireExactAttempt(attached, request, entry); + InitialAdmissionBindOwnerProof proof = + attached.status() == net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status.PENDING + ? ownerService.commit(binding) + : ownerService.read(binding); + return terminalResult(proof, binding, attached); + } + + private static GameInstanceDto requireExactActiveLaunch( + RunOwnedInitialLaunchResult launch, + PublishedRealmInitialAdmissionBindCommand command, + PublishedRealmCatalogSnapshot snapshot) { + if (launch == null || launch.gameInstance() == null || launch.activeLifecycleEpoch() <= 0) { + throw unresolved("INITIAL_ADMISSION_LAUNCH_UNRESOLVED: authored launch did not prove ACTIVE"); + } + GameInstanceDto target = launch.gameInstance(); + if (target.id() == null + || target.id() <= 0 + || !Objects.equals(target.tenantId(), snapshot.tenantId()) + || !Objects.equals(target.gameTemplateId(), command.gameTemplateId()) + || !Objects.equals(target.ownerAccountId(), command.ownerAccountId()) + || !Objects.equals(target.versionId(), command.publishedVersionId()) + || target.launchDescriptorId() == null + || target.launchDescriptorId().isBlank() + || target.releaseBundleId() == null + || target.releaseBundleId() <= 0 + || target.versionStateEpoch() == null + || target.versionStateEpoch() <= 0 + || !RUNNING.equals(target.status()) + || snapshot.policySetEvidence().versionId() != target.versionId()) { + throw unresolved( + "INITIAL_ADMISSION_LAUNCH_MISMATCH: authored launch does not match the local tenant, requested template, or exact published version"); + } + return target; + } + + private WorldInstanceLifecycleSnapshot requireExactWorldLifecycle( + GameInstanceDto target, + PublishedRealmInitialAdmissionBindCommand command, + PublishedRealmCatalogSnapshot snapshot) { + final GetWorldInstanceLifecycleResponse response; + try { + response = worldManagementClient.getWorldInstanceLifecycle(snapshot.tenantId(), target.id()); + } catch (RuntimeException exception) { + throw unresolved("INITIAL_ADMISSION_WORLD_LIFECYCLE_UNAVAILABLE: exact launch readback failed"); + } + if (response == null || response.hasError() || !response.hasWorldInstance()) { + throw unresolved("INITIAL_ADMISSION_WORLD_LIFECYCLE_INVALID: exact launch readback is absent"); + } + WorldInstanceLifecycleSnapshot lifecycle = response.getWorldInstance(); + if (parsePositiveId(lifecycle.getTenantId(), "tenantId") != snapshot.tenantId() + || parsePositiveId(lifecycle.getGameInstanceId(), "gameInstanceId") != target.id() + || parsePositiveId(lifecycle.getGameTemplateId(), "gameTemplateId") + != command.gameTemplateId() + || !command.initialAdmissionRequestId().equals(lifecycle.getControlPlaneRequestId()) + || !target.launchDescriptorId().equals(lifecycle.getLaunchDescriptorId()) + || parsePositiveId(lifecycle.getVersionId(), "versionId") != target.versionId() + || parsePositiveId(lifecycle.getReleaseBundleId(), "releaseBundleId") + != target.releaseBundleId() + || lifecycle.getVersionStateEpoch() != target.versionStateEpoch() + || lifecycle.getLifecycleEpoch() <= 0 + || lifecycle.getStatus() + != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE + || lifecycle.getPublishedReleaseBundleRef() == null + || lifecycle.getPublishedReleaseBundleRef().isBlank()) { + throw unresolved( + "INITIAL_ADMISSION_WORLD_LIFECYCLE_MISMATCH: World template, descriptor, version, release, or ACTIVE epoch differs from authored launch readback"); + } + return lifecycle; + } + + private static String requestDigest( + PublishedRealmInitialAdmissionBindCommand command, + PublishedRealmCatalogSnapshot snapshot, + PublishedRealmCatalogEntry entry, + GameInstanceDto target, + WorldInstanceLifecycleSnapshot lifecycle) { + var evidence = entry.policyEvidence(); + var policySet = snapshot.policySetEvidence(); + return sha256( + DIGEST_DOMAIN, + command.initialAdmissionRequestId(), + snapshot.targetNamespace(), + Long.toString(snapshot.tenantId()), + snapshot.canonicalTenantId().toString(), + Long.toString(snapshot.sourceGameRowId()), + snapshot.sourceGameTenantKey(), + snapshot.tenantIdentityProvenanceKind(), + Long.toString(snapshot.catalogRevision()), + Long.toString(policySet.versionId()), + Integer.toString(policySet.versionNumber()), + policySet.releaseBundleIdentity(), + policySet.publishWorkflowId(), + policySet.manifestHash(), + policySet.policySetDigest(), + evidence.policyId().toString(), + evidence.policyDigest(), + entry.realmId().toString(), + entry.requirePlayableStateNamespaceId().toString(), + evidence.policy().stateScope().name(), + evidence.policy().entryPolicy().name(), + evidence.policy().worldSlug(), + evidence.policy().realmSlug(), + Long.toString(command.gameTemplateId()), + Long.toString(target.id()), + target.launchDescriptorId(), + Long.toString(target.versionId()), + Long.toString(target.releaseBundleId()), + lifecycle.getPublishedReleaseBundleRef(), + Long.toString(target.versionStateEpoch()), + Long.toString(lifecycle.getLifecycleEpoch())); + } + + private static String sha256(String... fields) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + for (String field : fields) { + byte[] encoded = field.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } + } + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (IOException | NoSuchAlgorithmException exception) { + throw new IllegalStateException("Initial admission request digest could not be computed", exception); + } + } + + private static void requireExactAttempt( + net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt attempt, + InitialAdmissionBindRequest request, + PublishedRealmCatalogEntry entry) { + if (attempt == null + || attempt.attemptId() == null + || !"V14_PUBLISHED".equals(attempt.catalogSourceKind()) + || attempt.tenantId() != request.tenantId() + || !request.initialAdmissionRequestId().equals(attempt.initialAdmissionRequestId()) + || !request.requestDigest().equals(attempt.requestDigest()) + || !entry.realmId().equals(attempt.realmId()) + || !entry.requirePlayableStateNamespaceId().equals(attempt.playableStateNamespaceId()) + || !"SHARED".equals(attempt.playableStateScope()) + || !attempt.expectedNoPriorPointer() + || attempt.catalogRevision() != request.publishedCatalog().catalogRevision() + || attempt.gameInstanceId() != request.gameInstanceId() + || attempt.versionId() != request.versionId() + || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() + || !Objects.equals( + attempt.publishedTargetNamespace(), request.publishedCatalog().targetNamespace()) + || !Objects.equals( + attempt.canonicalTenantId(), request.publishedCatalog().canonicalTenantId()) + || !Objects.equals(attempt.gameTemplateId(), request.launchEvidence().gameTemplateId()) + || !Objects.equals(attempt.launchDescriptorId(), request.launchEvidence().launchDescriptorId()) + || !Objects.equals(attempt.releaseBundleId(), request.launchEvidence().releaseBundleId()) + || !Objects.equals( + attempt.publishedReleaseBundleRef(), + request.launchEvidence().publishedReleaseBundleRef()) + || !Objects.equals(attempt.versionStateEpoch(), request.launchEvidence().versionStateEpoch())) { + throw unresolved("INITIAL_ADMISSION_ATTEMPT_READBACK_MISMATCH: durable intent changed"); + } + } + + private static InitialAdmissionBindHoldBinding requireExactHold( + InitialAdmissionBindHold hold, + InitialAdmissionBindRequest request, + PublishedRealmCatalogEntry entry, + long catalogRevision) { + if (!isCanonicalUuid(hold.getHoldId()) + || !isCanonicalUuid(hold.getHoldFence()) + || !Long.toString(request.tenantId()).equals(hold.getTenantId()) + || !entry.realmId().toString().equals(hold.getRealmUuid()) + || !entry.playableStateNamespaceId().toString().equals(hold.getPlayableStateNamespaceUuid()) + || hold.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || !Long.toString(request.gameInstanceId()).equals(hold.getGameInstanceId()) + || !Long.toString(request.versionId()).equals(hold.getVersionId()) + || hold.getActiveLifecycleEpoch() != request.activeLifecycleEpoch() + || !request.initialAdmissionRequestId().equals(hold.getInitialAdmissionRequestId()) + || !request.requestDigest().equals(hold.getRequestDigest()) + || !hold.getExpectedNoPriorPointer() + || hold.getExpectedCatalogRevision() != catalogRevision + || hold.getStatus() + == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED) { + throw unresolved("INITIAL_ADMISSION_WORLD_HOLD_MISMATCH: World returned a different hold tuple"); + } + return new InitialAdmissionBindHoldBinding( + hold.getHoldId(), + hold.getHoldFence(), + request.tenantId(), + hold.getRealmUuid(), + hold.getPlayableStateNamespaceUuid(), + "SHARED", + request.gameInstanceId(), + request.versionId(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + request.requestDigest(), + true, + catalogRevision); + } + + private Result terminalResult( + InitialAdmissionBindOwnerProof proof, + InitialAdmissionBindHoldBinding binding, + net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt attempt) { + if (proof == null + || !binding.holdId().equals(proof.holdId()) + || !binding.holdFence().equals(proof.holdFence()) + || binding.tenantId() != proof.tenantId() + || !binding.realmUuid().equals(proof.realmUuid()) + || !binding.playableStateNamespaceUuid().equals(proof.playableStateNamespaceUuid()) + || !binding.playableStateScope().equals(proof.playableStateScope()) + || binding.gameInstanceId() != proof.gameInstanceId() + || binding.versionId() != proof.versionId() + || binding.activeLifecycleEpoch() != proof.activeLifecycleEpoch() + || !binding.initialAdmissionRequestId().equals(proof.initialAdmissionRequestId()) + || !binding.requestDigest().equals(proof.requestDigest()) + || !proof.expectedNoPriorPointer() + || binding.expectedCatalogRevision() != proof.expectedCatalogRevision()) { + throw unresolved("INITIAL_ADMISSION_OWNER_PROOF_MISMATCH: owner readback differs from hold"); + } + if (proof.outcome() == Outcome.COMMITTED + && Objects.equals(proof.ownerProofId(), attempt.attemptId().toString()) + && proof.pointerAuditId() != null + && proof.pointerVersion() == 1L + && proof.requestDigest().equals(proof.pointerAuditRequestDigest())) { + return new Result(TerminalOutcome.COMMITTED, proof); + } + if (proof.outcome() == Outcome.ABORTED + && proof.futureCommitPrevented() + && Objects.equals(proof.ownerProofId(), attempt.attemptId().toString()) + && proof.pointerAuditId() == null) { + return new Result(TerminalOutcome.ABORTED, proof); + } + throw unresolved("INITIAL_ADMISSION_OWNER_PROOF_UNRESOLVED: exact terminal owner proof is absent"); + } + + private static boolean isRetryable(InitialAdmissionBindHoldStatus status) { + return status + == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING + || status + == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED; + } + + private static boolean isCanonicalUuid(String value) { + try { + return value != null && java.util.UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static long parsePositiveId(String value, String name) { + try { + long parsed = Long.parseLong(value); + if (parsed > 0 && Long.toString(parsed).equals(value)) { + return parsed; + } + } catch (RuntimeException ignored) { + // Report only the stable owner failure code below. + } + throw unresolved("INITIAL_ADMISSION_WORLD_LIFECYCLE_INVALID: " + name + " is malformed"); + } + + private static IllegalStateException unresolved(String message) { + return new IllegalStateException(message); + } + + public enum TerminalOutcome { + COMMITTED, + ABORTED + } + + /** A verified GS owner outcome; World still owns asynchronous hold finalization. */ + public record Result(TerminalOutcome outcome, InitialAdmissionBindOwnerProof ownerProof) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java index 55758189af..c9212ec953 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java @@ -6,12 +6,15 @@ import java.util.Optional; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; @@ -35,7 +38,9 @@ public class DatabaseInitialAdmissionBindOwnerService implements InitialAdmissio private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); private static final Pattern SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); private static final String STATE_SCOPE = "SHARED"; - private static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + private static final String FIXTURE_SOURCE = "V9_FIXTURE"; + private static final String PUBLISHED_SOURCE = "V14_PUBLISHED"; + private static final String PUBLISHED_CHARACTER_CREATION_POLICY = "PRESEEDED_ONLY"; private static final String AUDIT_ACTOR = "game-session-initial-admission-bind"; private static final String AUDIT_REASON = "initial admission pointer bind"; @@ -87,14 +92,7 @@ public InitialAdmissionBindCatalog registerPublicSharedFixtureCatalog( @Transactional public InitialAdmissionBindAttempt beginIntent(InitialAdmissionBindRequest request) { validateRequest(request); - InitialAdmissionBindCatalog catalog = - catalogRepository - .findByTenantIdAndSelectors( - request.tenantId(), request.worldSlug(), request.realmSlug()) - .orElseThrow( - () -> - new IllegalArgumentException( - "INITIAL_ADMISSION_CATALOG_NOT_FOUND: owner catalog row is missing")); + InitialAdmissionBindCatalog catalog = resolveCatalog(request); attemptRepository.lockAttemptAndRealm( request.tenantId(), request.initialAdmissionRequestId(), catalog.realmId()); @@ -146,7 +144,17 @@ public InitialAdmissionBindAttempt beginIntent(InitialAdmissionBindRequest reque null, now, now, - null)); + null, + request.isPublishedCatalogRequest() ? PUBLISHED_SOURCE : FIXTURE_SOURCE, + request.publishedCatalog() == null ? null : request.publishedCatalog().targetNamespace(), + request.publishedCatalog() == null ? null : request.publishedCatalog().canonicalTenantId(), + request.launchEvidence() == null ? null : request.launchEvidence().gameTemplateId(), + request.launchEvidence() == null ? null : request.launchEvidence().launchDescriptorId(), + request.launchEvidence() == null ? null : request.launchEvidence().releaseBundleId(), + request.launchEvidence() == null + ? null + : request.launchEvidence().publishedReleaseBundleRef(), + request.launchEvidence() == null ? null : request.launchEvidence().versionStateEpoch())); } @Override @@ -184,17 +192,7 @@ public InitialAdmissionBindOwnerProof commit(InitialAdmissionBindHoldBinding bin } catch (IllegalStateException exception) { return proof(binding, Outcome.ERROR, null, null, 0L, null, false); } - requireTargetMatchesCatalogAndRequest( - catalog, - new InitialAdmissionBindRequest( - attempt.tenantId(), - catalog.worldSlug(), - catalog.realmSlug(), - attempt.initialAdmissionRequestId(), - attempt.requestDigest(), - attempt.gameInstanceId(), - attempt.versionId(), - attempt.activeLifecycleEpoch())); + requireTargetMatchesCatalogAndAttempt(catalog, attempt); if (attemptRepository.hasPointerForCatalog(catalog) || attemptRepository.hasPointerForRuntimeTarget( attempt.tenantId(), attempt.gameInstanceId())) { @@ -363,6 +361,11 @@ private boolean matchesCommittedEvidence( && Objects.equals(pointer.getRealmSlug(), catalog.realmSlug()) && Objects.equals(pointer.getRealmId(), attempt.realmId()) && Objects.equals(pointer.getPlayableStateNamespaceId(), attempt.playableStateNamespaceId()) + && pointer.isVisible() + && pointer.isPublicProductionRealm() + && pointer.isRequiresCharacterSelection() == catalog.requiresCharacterSelection() + && Objects.equals(pointer.getStateScope(), catalog.stateScope()) + && Objects.equals(pointer.getCharacterCreationPolicy(), catalog.characterCreationPolicy()) && pointer.getPointerVersion() != null && pointer.getPointerVersion() >= 1L && Objects.equals(audit.getId(), attempt.auditEventId()) @@ -379,8 +382,8 @@ private boolean matchesCommittedEvidence( && audit.isVisible() && audit.isPublicProductionRealm() && audit.isRequiresCharacterSelection() == catalog.requiresCharacterSelection() - && Objects.equals(audit.getStateScope(), STATE_SCOPE) - && Objects.equals(audit.getCharacterCreationPolicy(), CHARACTER_CREATION_POLICY) + && Objects.equals(audit.getStateScope(), catalog.stateScope()) + && Objects.equals(audit.getCharacterCreationPolicy(), catalog.characterCreationPolicy()) && Objects.equals(audit.getControlPlaneRequestId(), attempt.initialAdmissionRequestId()) && Objects.equals(audit.getActorPrincipal(), AUDIT_ACTOR) && Objects.equals(audit.getReason(), AUDIT_REASON) @@ -389,6 +392,46 @@ private boolean matchesCommittedEvidence( private InitialAdmissionBindCatalog requireCatalogForAttempt( InitialAdmissionBindAttempt attempt) { + if (PUBLISHED_SOURCE.equals(attempt.catalogSourceKind())) { + PublishedRealmCatalogSnapshot snapshot = + catalogRepository + .findPublishedSnapshot( + attempt.publishedTargetNamespace(), attempt.tenantId(), attempt.catalogRevision()) + .orElseThrow( + () -> + new IllegalStateException( + "INITIAL_ADMISSION_PUBLISHED_SNAPSHOT_MISSING: durable attempt lost its immutable snapshot")); + if (!snapshot.canonicalTenantId().equals(attempt.canonicalTenantId()) + || snapshot.policySetEvidence().versionId() != attempt.versionId()) { + throw new IllegalStateException( + "INITIAL_ADMISSION_PUBLISHED_SNAPSHOT_MISMATCH: attempt no longer matches its exact published snapshot"); + } + PublishedRealmCatalogEntry entry = + snapshot.entries().stream() + .filter(candidate -> candidate.realmId().equals(attempt.realmId())) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "INITIAL_ADMISSION_PUBLISHED_ENTRY_MISSING: durable attempt lost its selected entry")); + InitialAdmissionBindCatalog catalog = requirePublishedCatalog( + snapshot, + entry, + attempt.gameTemplateId() == null ? 0L : attempt.gameTemplateId(), + entry.policyEvidence().policy().worldSlug(), + entry.policyEvidence().policy().realmSlug()); + if (!entry.playableStateNamespaceId().equals(attempt.playableStateNamespaceId()) + || !catalog.stateScope().equals(attempt.playableStateScope()) + || !PUBLISHED_SOURCE.equals(attempt.catalogSourceKind())) { + throw new IllegalStateException( + "INITIAL_ADMISSION_PUBLISHED_ENTRY_MISMATCH: attempt no longer matches its exact published entry"); + } + return catalog; + } + if (!FIXTURE_SOURCE.equals(attempt.catalogSourceKind())) { + throw new IllegalStateException( + "INITIAL_ADMISSION_CATALOG_SOURCE_INVALID: durable attempt has an unknown source kind"); + } InitialAdmissionBindCatalog catalog = catalogRepository .findByTenantId(attempt.tenantId()) @@ -406,6 +449,90 @@ private InitialAdmissionBindCatalog requireCatalogForAttempt( return catalog; } + private InitialAdmissionBindCatalog resolveCatalog(InitialAdmissionBindRequest request) { + if (!request.isPublishedCatalogRequest()) { + if (request.publishedCatalog() != null || request.launchEvidence() != null) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: published catalog and launch evidence must be supplied together"); + } + return catalogRepository + .findByTenantIdAndSelectors(request.tenantId(), request.worldSlug(), request.realmSlug()) + .orElseThrow( + () -> + new IllegalArgumentException( + "INITIAL_ADMISSION_CATALOG_NOT_FOUND: owner fixture catalog row is missing")); + } + InitialAdmissionBindRequest.PublishedCatalogBinding reference = request.publishedCatalog(); + InitialAdmissionBindRequest.LaunchEvidence launch = request.launchEvidence(); + if (reference.targetNamespace() == null + || reference.targetNamespace().isBlank() + || reference.canonicalTenantId() == null + || reference.catalogRevision() <= 0 + || launch.gameTemplateId() <= 0 + || launch.releaseBundleId() <= 0 + || launch.versionStateEpoch() <= 0 + || launch.launchDescriptorId() == null + || launch.launchDescriptorId().isBlank() + || launch.publishedReleaseBundleRef() == null + || launch.publishedReleaseBundleRef().isBlank()) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: published admission requires exact snapshot and authored launch evidence"); + } + PublishedRealmCatalogSnapshot snapshot = + catalogRepository + .findPublishedSnapshot( + reference.targetNamespace(), request.tenantId(), reference.catalogRevision()) + .orElseThrow( + () -> + new IllegalArgumentException( + "INITIAL_ADMISSION_PUBLISHED_SNAPSHOT_NOT_FOUND: exact immutable snapshot is absent")); + if (!reference.canonicalTenantId().equals(snapshot.canonicalTenantId()) + || snapshot.policySetEvidence().versionId() != request.versionId()) { + throw new IllegalArgumentException( + "INITIAL_ADMISSION_PUBLISHED_SNAPSHOT_MISMATCH: local tenant, canonical tenant, revision, or version changed"); + } + PublishedRealmCatalogEntry selected = + snapshot.requireVisibleEntryForAdmission(request.worldSlug(), request.realmSlug()); + return requirePublishedCatalog( + snapshot, selected, launch.gameTemplateId(), request.worldSlug(), request.realmSlug()); + } + + private InitialAdmissionBindCatalog requirePublishedCatalog( + PublishedRealmCatalogSnapshot snapshot, + PublishedRealmCatalogEntry entry, + long gameTemplateId, + String worldSlug, + String realmSlug) { + RealmEntryPolicy policy = entry.policyEvidence().policy(); + if (gameTemplateId <= 0 + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !policy.worldSlug().equals(worldSlug) + || !policy.realmSlug().equals(realmSlug) + || entry.namespaceResolution() != PublishedRealmCatalogEntry.NamespaceResolution.RESOLVED) { + throw new IllegalStateException( + "INITIAL_ADMISSION_PUBLISHED_POLICY_UNSUPPORTED: only visible public SHARED PRESEEDED_ONLY entries with resolved namespaces are admissible"); + } + return new InitialAdmissionBindCatalog( + entry.realmId(), + snapshot.tenantId(), + gameTemplateId, + policy.worldSlug(), + policy.worldDisplayName(), + policy.realmSlug(), + policy.realmDisplayName(), + snapshot.catalogRevision(), + entry.requirePlayableStateNamespaceId(), + true, + true, + true, + STATE_SCOPE, + PUBLISHED_CHARACTER_CREATION_POLICY, + snapshot.createdAt()); + } + private InitialAdmissionBindAttempt attachHoldIfNeeded( InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding, Instant now) { if (attempt.holdId() != null || attempt.holdFence() != null) { @@ -457,6 +584,7 @@ private void requireSameRequest( if (attempt.tenantId() != request.tenantId() || !attempt.initialAdmissionRequestId().equals(request.initialAdmissionRequestId()) || !attempt.requestDigest().equals(request.requestDigest()) + || !matchesCatalogSource(attempt, request) || !attempt.realmId().equals(catalog.realmId()) || !attempt.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) || !attempt.playableStateScope().equals(catalog.stateScope()) @@ -470,6 +598,31 @@ private void requireSameRequest( } } + private boolean matchesCatalogSource( + InitialAdmissionBindAttempt attempt, InitialAdmissionBindRequest request) { + if (request.isPublishedCatalogRequest()) { + var reference = request.publishedCatalog(); + var launch = request.launchEvidence(); + return PUBLISHED_SOURCE.equals(attempt.catalogSourceKind()) + && Objects.equals(attempt.publishedTargetNamespace(), reference.targetNamespace()) + && Objects.equals(attempt.canonicalTenantId(), reference.canonicalTenantId()) + && Objects.equals(attempt.gameTemplateId(), launch.gameTemplateId()) + && Objects.equals(attempt.launchDescriptorId(), launch.launchDescriptorId()) + && Objects.equals(attempt.releaseBundleId(), launch.releaseBundleId()) + && Objects.equals( + attempt.publishedReleaseBundleRef(), launch.publishedReleaseBundleRef()) + && Objects.equals(attempt.versionStateEpoch(), launch.versionStateEpoch()); + } + return FIXTURE_SOURCE.equals(attempt.catalogSourceKind()) + && attempt.publishedTargetNamespace() == null + && attempt.canonicalTenantId() == null + && attempt.gameTemplateId() == null + && attempt.launchDescriptorId() == null + && attempt.releaseBundleId() == null + && attempt.publishedReleaseBundleRef() == null + && attempt.versionStateEpoch() == null; + } + private void requireSameBinding( InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding) { if (!sameBindingTuple(attempt, binding)) { @@ -510,6 +663,44 @@ private void requireTargetMatchesCatalogAndRequest( throw new IllegalArgumentException( "INITIAL_ADMISSION_TARGET_MISMATCH: target does not match persisted tenant/template/version"); } + if (request.isPublishedCatalogRequest()) { + InitialAdmissionBindRequest.LaunchEvidence launch = request.launchEvidence(); + if (!Objects.equals(gameInstance.getLaunchDescriptorId(), launch.launchDescriptorId()) + || !Objects.equals(gameInstance.getReleaseBundleId(), launch.releaseBundleId()) + || !Objects.equals(gameInstance.getVersionStateEpoch(), launch.versionStateEpoch()) + || !Objects.equals( + gameInstance.getRunOwnedStartPublishedReleaseBundleRef(), + launch.publishedReleaseBundleRef())) { + throw new IllegalArgumentException( + "INITIAL_ADMISSION_LAUNCH_EVIDENCE_MISMATCH: authored descriptor no longer matches the persisted runtime target"); + } + } + } + + private void requireTargetMatchesCatalogAndAttempt( + InitialAdmissionBindCatalog catalog, InitialAdmissionBindAttempt attempt) { + GameInstance gameInstance = + gameInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate(attempt.tenantId(), attempt.gameInstanceId()) + .orElseThrow( + () -> + new IllegalStateException( + "GAME_INSTANCE_NOT_FOUND: initial admission target is not GS-owned")); + if (!Objects.equals(gameInstance.getGameTemplateId(), catalog.gameTemplateId()) + || !Objects.equals(gameInstance.getVersionId(), attempt.versionId())) { + throw new IllegalStateException( + "INITIAL_ADMISSION_TARGET_MISMATCH: target does not match persisted tenant/template/version"); + } + if (PUBLISHED_SOURCE.equals(attempt.catalogSourceKind()) + && (!Objects.equals(gameInstance.getLaunchDescriptorId(), attempt.launchDescriptorId()) + || !Objects.equals(gameInstance.getReleaseBundleId(), attempt.releaseBundleId()) + || !Objects.equals(gameInstance.getVersionStateEpoch(), attempt.versionStateEpoch()) + || !Objects.equals( + gameInstance.getRunOwnedStartPublishedReleaseBundleRef(), + attempt.publishedReleaseBundleRef()))) { + throw new IllegalStateException( + "INITIAL_ADMISSION_LAUNCH_EVIDENCE_MISMATCH: authored descriptor no longer matches the persisted runtime target"); + } } private void validateCatalogDescriptor(InitialAdmissionBindCatalogDescriptor descriptor) { diff --git a/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql new file mode 100644 index 0000000000..255861d6d1 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql @@ -0,0 +1,73 @@ +-- Keep V9 fixture attempts readable as historical fixture evidence while allowing a new +-- production attempt to reference the exact immutable V14 published snapshot and entry. +ALTER TABLE gameplay_published_realm_catalog_snapshot + ADD CONSTRAINT uq_gs_published_realm_catalog_snapshot_bind_identity + UNIQUE (target_namespace, tenant_id, catalog_revision, canonical_tenant_id, version_id); + +ALTER TABLE gameplay_initial_admission_bind_attempt + ADD COLUMN catalog_source_kind character varying(16) NOT NULL DEFAULT 'V9_FIXTURE', + ADD COLUMN fixture_catalog_realm_id uuid, + ADD COLUMN published_target_namespace character varying(63), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN game_template_id bigint, + ADD COLUMN launch_descriptor_id character varying(128), + ADD COLUMN release_bundle_id bigint, + ADD COLUMN published_release_bundle_ref character varying(200), + ADD COLUMN version_state_epoch bigint; + +UPDATE gameplay_initial_admission_bind_attempt + SET fixture_catalog_realm_id = realm_id; + +ALTER TABLE gameplay_initial_admission_bind_attempt + DROP CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_fk, + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_fixture_catalog_fk + FOREIGN KEY (tenant_id, fixture_catalog_realm_id, playable_state_namespace_id, catalog_revision) + REFERENCES gameplay_initial_admission_bind_catalog + (tenant_id, realm_id, playable_state_namespace_id, catalog_revision), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_snapshot_fk + FOREIGN KEY (published_target_namespace, tenant_id, catalog_revision, + canonical_tenant_id, version_id) + REFERENCES gameplay_published_realm_catalog_snapshot + (target_namespace, tenant_id, catalog_revision, canonical_tenant_id, version_id), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_entry_fk + FOREIGN KEY (published_target_namespace, tenant_id, catalog_revision, realm_id) + REFERENCES gameplay_published_realm_catalog_entry + (target_namespace, tenant_id, catalog_revision, realm_id), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_source_shape + CHECK ( + (catalog_source_kind = 'V9_FIXTURE' + AND fixture_catalog_realm_id = realm_id + AND published_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND game_template_id IS NULL + AND launch_descriptor_id IS NULL + AND release_bundle_id IS NULL + AND published_release_bundle_ref IS NULL + AND version_state_epoch IS NULL) + OR + (catalog_source_kind = 'V14_PUBLISHED' + AND fixture_catalog_realm_id IS NULL + AND published_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND game_template_id IS NOT NULL AND game_template_id > 0 + AND launch_descriptor_id IS NOT NULL + AND release_bundle_id IS NOT NULL AND release_bundle_id > 0 + AND published_release_bundle_ref IS NOT NULL + AND version_state_epoch IS NOT NULL AND version_state_epoch > 0 + AND playable_state_scope = 'SHARED' + AND expected_no_prior_pointer) + ); + +ALTER TABLE gameplay_initial_admission_bind_attempt + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_namespace + CHECK (published_target_namespace IS NULL OR + (octet_length(published_target_namespace) BETWEEN 1 AND 63 + AND published_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_identity + CHECK (canonical_tenant_id IS NULL OR + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_launch + CHECK ((launch_descriptor_id IS NULL OR + char_length(launch_descriptor_id) BETWEEN 1 AND 128) + AND (published_release_bundle_ref IS NULL OR + char_length(published_release_bundle_ref) BETWEEN 1 AND 200)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index cc43052120..7f13030618 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -4,12 +4,19 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; +import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.Objects; +import java.util.UUID; +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.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; import net.firedevops.firemud.gamesession.service.impl.DatabaseInitialAdmissionBindOwnerService; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -23,12 +30,17 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class InitialAdmissionBindPostgresIntegrationTest { private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String PUBLISHED_NAMESPACE = "published-bind-test"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final ObjectMapper JSON = new ObjectMapper(); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -147,6 +159,127 @@ void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFails assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isEqualTo(1); } + @Test + void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transactionTemplate = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + GameInstanceRepository gameInstanceRepository = new GameInstanceRepository(dsl); + GameInstance runtime = gameInstance(); + runtime.setLaunchDescriptorId("published-launch-v1"); + runtime.setReleaseBundleId(77L); + runtime.setVersionStateEpoch(4L); + runtime.setRunOwnedStartRequestId("4c31b7b9-e9e8-41a4-a5b1-334db8bc49ae"); + runtime.setRunOwnedStartPublishedReleaseBundleRef("prb:41:902:77"); + GameInstance savedRuntime = gameInstanceRepository.save(runtime); + seedAssociation(dsl, 41L, CANONICAL_TENANT_ID, 731L, "source-game-key-not-local-id"); + InitialAdmissionBindCatalogRepository catalogRepository = + new InitialAdmissionBindCatalogRepository(dsl); + PublishedRealmEntryPolicySetEvidence policySet = publishedPolicySet(); + var snapshot = + transactionTemplate.execute( + status -> + catalogRepository.materializePublishedSnapshot( + PUBLISHED_NAMESPACE, + 41L, + CANONICAL_TENANT_ID, + 731L, + "source-game-key-not-local-id", + "NEW_GAME_ROW", + policySet)); + var entry = Objects.requireNonNull(snapshot).entries().getFirst(); + DatabaseInitialAdmissionBindOwnerService service = + new DatabaseInitialAdmissionBindOwnerService( + catalogRepository, + new InitialAdmissionBindAttemptRepository(dsl), + new GameplayAdmissionPointerEventRepository(dsl), + gameInstanceRepository); + String requestId = "4c31b7b9-e9e8-41a4-a5b1-334db8bc49ae"; + String digest = "b".repeat(64); + var request = + new InitialAdmissionBindRequest( + 41L, + "firemud", + "main", + requestId, + digest, + savedRuntime.getId(), + 902L, + 13L, + new InitialAdmissionBindRequest.PublishedCatalogBinding( + PUBLISHED_NAMESPACE, CANONICAL_TENANT_ID, snapshot.catalogRevision()), + new InitialAdmissionBindRequest.LaunchEvidence( + 810L, "published-launch-v1", 77L, "prb:41:902:77", 4L)); + + assertThat(dsl.fetchCount(DSL.table("gameplay_initial_admission_bind_catalog"))).isZero(); + assertThatThrownBy( + () -> + transactionTemplate.execute( + status -> + service.beginIntent( + new InitialAdmissionBindRequest( + 41L, + "firemud", + "main", + requestId, + "c".repeat(64), + savedRuntime.getId(), + 902L, + 13L, + request.publishedCatalog(), + request.launchEvidence())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); + + var attempt = transactionTemplate.execute(status -> service.beginIntent(request)); + assertThat(attempt.catalogSourceKind()).isEqualTo("V14_PUBLISHED"); + assertThat(attempt.tenantId()).isEqualTo(41L); + assertThat(attempt.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(attempt.publishedTargetNamespace()).isEqualTo(PUBLISHED_NAMESPACE); + assertThat(attempt.realmId()).isEqualTo(entry.realmId()); + assertThat(attempt.playableStateNamespaceId()).isEqualTo(entry.playableStateNamespaceId()); + assertThat(attempt.gameTemplateId()).isEqualTo(810L); + assertThat(attempt.versionId()).isEqualTo(policySet.versionId()); + var binding = + new InitialAdmissionBindHoldBinding( + "291787b2-ed31-4ae0-9d72-1f872931e7ed", + "ea29d3c4-bb4c-4ce5-8f81-8fd60d21b472", + 41L, + entry.realmId().toString(), + entry.playableStateNamespaceId().toString(), + "SHARED", + savedRuntime.getId(), + 902L, + 13L, + requestId, + digest, + true, + snapshot.catalogRevision()); + transactionTemplate.execute(status -> service.attachHold(binding)); + var proof = transactionTemplate.execute(status -> service.commit(binding)); + assertThat(proof.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.COMMITTED); + assertThat(proof.pointerAuditRequestDigest()).isEqualTo(digest); + assertThat( + dsl.fetchOne( + "SELECT character_creation_policy, requires_character_selection, state_scope " + + "FROM gameplay_admission_pointer WHERE tenant_id = 41") + .get("character_creation_policy", String.class)) + .isEqualTo("PRESEEDED_ONLY"); + assertThat( + dsl.fetchOne( + "SELECT requires_character_selection FROM gameplay_admission_pointer " + + "WHERE tenant_id = 41") + .get("requires_character_selection", Boolean.class)) + .isTrue(); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isEqualTo(1); + } + private static DriverManagerDataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); @@ -164,9 +297,71 @@ private static GameInstance gameInstance() { gameInstance.setStatus("RUNNING"); gameInstance.setGameTemplateId(810L); gameInstance.setVersionId(902L); + gameInstance.setGameTemplateId(810L); return gameInstance; } + private static void seedAssociation( + DSLContext dsl, + long tenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey) { + dsl.execute( + "INSERT INTO game_session_retained_tenant_association " + + "(operation_id, target_namespace, association_request_id, " + + "legacy_game_session_tenant_id, canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, terminal_outcome) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'ASSOCIATED')", + UUID.fromString("a2b30fc4-c2d9-40f9-81a8-e559f6ab672e"), + PUBLISHED_NAMESPACE, + UUID.fromString("34d29e68-15d7-4f8a-9bc9-2289aa91563a"), + tenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey); + } + + private static PublishedRealmEntryPolicySetEvidence publishedPolicySet() { + long versionId = 902L; + String workflow = "published-initial-bind"; + String manifest = "manifest-v1"; + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, versionId, workflow, manifest, JSON); + String policyJson = + "{\"schemaVersion\":1,\"worldSlug\":\"firemud\"," + + "\"worldDisplayName\":\"FireMUD\",\"realmSlug\":\"main\"," + + "\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + var policy = RealmEntryPolicy.parse(policyJson, JSON); + var evidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.nameUUIDFromBytes("published-policy".getBytes(StandardCharsets.UTF_8)), + CANONICAL_TENANT_ID, + "NEW_GAME_ROW", + 731L, + "source-game-key-not-local-id", + versionId, + 1, + 901L, + releaseIdentity, + workflow, + manifest, + policy, + JSON); + return PublishedRealmEntryPolicySetEvidence.create( + CANONICAL_TENANT_ID, + versionId, + 1, + releaseIdentity, + workflow, + manifest, + List.of(evidence), + JSON); + } + private static InitialAdmissionBindCatalogSnapshot toSnapshot( net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog catalog) { return new InitialAdmissionBindCatalogSnapshot( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java index 919ab297cb..491f933d07 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java @@ -112,6 +112,15 @@ playable_state_scope VARCHAR(32) NOT NULL, status VARCHAR(16) NOT NULL, pointer_id BIGINT, audit_event_id BIGINT, + catalog_source_kind VARCHAR(16) NOT NULL DEFAULT 'V9_FIXTURE', + fixture_catalog_realm_id UUID, + published_target_namespace VARCHAR(63), + canonical_tenant_id UUID, + game_template_id BIGINT, + launch_descriptor_id VARCHAR(128), + release_bundle_id BIGINT, + published_release_bundle_ref VARCHAR(200), + version_state_epoch BIGINT, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL, terminal_at TIMESTAMP, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java new file mode 100644 index 0000000000..60ecb67f9f --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java @@ -0,0 +1,126 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +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.gamesession.client.WorldManagementClient; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; +import net.firedevops.firemud.gamesession.service.PublishedRealmCatalogOwnerService; +import net.firedevops.firemud.gamesession.service.PublishedRealmInitialAdmissionBindCommand; +import net.firedevops.firemud.gamesession.service.PublishedRealmInitialAdmissionBindCoordinator; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmInitialAdmissionBindCoordinatorTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final long LOCAL_GAME_SESSION_TENANT_ID = 41L; + private static final long SOURCE_GAME_ROW_ID = 731L; + private static final long PUBLISHED_VERSION_ID = 902L; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void distinctSourceAndLocalTenantIdsFailBeforeAuthoredLaunchOrWorldHold() { + PublishedRealmCatalogOwnerService catalogOwner = mock(PublishedRealmCatalogOwnerService.class); + GameInstanceService gameInstanceService = mock(GameInstanceService.class); + InitialAdmissionBindOwnerService ownerService = mock(InitialAdmissionBindOwnerService.class); + WorldManagementClient worldManagementClient = mock(WorldManagementClient.class); + when(catalogOwner.materializePublishedSnapshot(CANONICAL_TENANT_ID, PUBLISHED_VERSION_ID)) + .thenReturn(snapshotWithDistinctSourceAndLocalIds()); + PublishedRealmInitialAdmissionBindCoordinator coordinator = + new PublishedRealmInitialAdmissionBindCoordinator( + catalogOwner, gameInstanceService, ownerService, worldManagementClient); + + assertThatThrownBy( + () -> + coordinator.coordinate( + new PublishedRealmInitialAdmissionBindCommand( + CANONICAL_TENANT_ID, + PUBLISHED_VERSION_ID, + 12L, + 88L, + "earth", + "main", + "44444444-4444-4444-8444-444444444444"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("INITIAL_ADMISSION_LAUNCH_TENANT_IDENTITY_UNAVAILABLE") + .hasMessageContaining("source/local identity adapter is required"); + + verifyNoInteractions(gameInstanceService, ownerService, worldManagementClient); + } + + private static PublishedRealmCatalogSnapshot snapshotWithDistinctSourceAndLocalIds() { + String workflow = "publish:published-bind-unit-test"; + String manifest = "published-bind-manifest"; + long versionId = PUBLISHED_VERSION_ID; + int versionNumber = 3; + RealmEntryPolicy policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON); + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, versionId, workflow, manifest, JSON); + PublishedRealmEntryPolicyEvidence policyEvidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("55555555-5555-4555-8555-555555555555"), + CANONICAL_TENANT_ID, + "RETAINED_GAME_V29", + SOURCE_GAME_ROW_ID, + "gd-source-731", + versionId, + versionNumber, + 903L, + releaseIdentity, + workflow, + manifest, + policy, + JSON); + PublishedRealmEntryPolicySetEvidence policySet = + PublishedRealmEntryPolicySetEvidence.create( + CANONICAL_TENANT_ID, + versionId, + versionNumber, + releaseIdentity, + workflow, + manifest, + List.of(policyEvidence), + JSON); + return new PublishedRealmCatalogSnapshot( + LOCAL_GAME_SESSION_TENANT_ID, + "gameplay-test", + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + "gd-source-731", + "RETAINED_GAME_V29", + 5L, + policySet, + List.of( + new PublishedRealmCatalogEntry( + LOCAL_GAME_SESSION_TENANT_ID, + 5L, + REALM_ID, + NAMESPACE_ID, + NamespaceResolution.RESOLVED, + policyEvidence)), + Instant.parse("2026-01-01T00:00:00Z")); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java index 348c071737..38a5487836 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java @@ -230,7 +230,12 @@ private static void createSchema(DSLContext dsl) { + "catalog_revision BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, version_id BIGINT NOT NULL, " + "active_lifecycle_epoch BIGINT NOT NULL, hold_id UUID, hold_fence UUID, status VARCHAR(16) NOT NULL, " + "pointer_id BIGINT, audit_event_id BIGINT, created_at TIMESTAMP NOT NULL, " - + "updated_at TIMESTAMP NOT NULL, terminal_at TIMESTAMP, UNIQUE (tenant_id, initial_admission_request_id))"); + + "updated_at TIMESTAMP NOT NULL, terminal_at TIMESTAMP, " + + "catalog_source_kind VARCHAR(16) NOT NULL DEFAULT 'V9_FIXTURE', " + + "fixture_catalog_realm_id UUID, published_target_namespace VARCHAR(63), " + + "canonical_tenant_id UUID, game_template_id BIGINT, launch_descriptor_id VARCHAR(128), " + + "release_bundle_id BIGINT, published_release_bundle_ref VARCHAR(200), version_state_epoch BIGINT, " + + "UNIQUE (tenant_id, initial_admission_request_id))"); dsl.execute( "CREATE TABLE gameplay_admission_pointer (" + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, world_slug VARCHAR(120) NOT NULL, " From c761010864c9bb31ff0ee8b5eaa7ef25a0739904 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:29:51 +1300 Subject: [PATCH 079/105] Compose published realm admission owner readback --- ...PublishedRealmAdmissionOwnerReadProof.java | 96 +++++ ...blishedRealmAdmissionOwnerReadRequest.java | 35 ++ ...blishedRealmAdmissionOwnerReadService.java | 315 ++++++++++++++ ...hedRealmAdmissionOwnerReadServiceTest.java | 396 ++++++++++++++++++ 4 files changed, 842 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadProof.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadProof.java new file mode 100644 index 0000000000..be55c8b2c3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadProof.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** + * Point-in-time owner composition for one exact published PRESEEDED_ONLY realm and its first + * admission bind. This observation is not a pointer mutation or through-commit admission gate. + */ +public record PublishedRealmAdmissionOwnerReadProof( + long gameSessionTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String tenantIdentityProvenanceKind, + PublishedRealmEntryPolicySetEvidence publishedPolicySet, + PublishedRealmEntryPolicyEvidence selectedPolicyEvidence, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + long pointerVersion, + long gameInstanceId, + long publishedVersionId, + long activeLifecycleEpoch, + long gameTemplateId, + String launchDescriptorId, + long releaseBundleId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String initialAdmissionRequestId, + String requestDigest, + UUID initialAdmissionAttemptId, + long pointerAuditId) { + public PublishedRealmAdmissionOwnerReadProof { + if (gameSessionTenantId <= 0 + || sourceGameRowId <= 0 + || catalogRevision <= 0 + || pointerVersion <= 0 + || gameInstanceId <= 0 + || publishedVersionId <= 0 + || activeLifecycleEpoch <= 0 + || gameTemplateId <= 0 + || releaseBundleId <= 0 + || versionStateEpoch <= 0 + || pointerAuditId <= 0) { + throw new IllegalArgumentException("Published realm admission proof tuple must be positive"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNonNil(initialAdmissionAttemptId, "initialAdmissionAttemptId"); + requireText(sourceGameTenantKey, "sourceGameTenantKey"); + requireText(tenantIdentityProvenanceKind, "tenantIdentityProvenanceKind"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireText(initialAdmissionRequestId, "initialAdmissionRequestId"); + if (requestDigest == null || !requestDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("requestDigest must be lowercase SHA-256 hex"); + } + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(publishedPolicySet, "publishedPolicySet"); + Objects.requireNonNull(selectedPolicyEvidence, "selectedPolicyEvidence"); + if (!canonicalTenantId.equals(publishedPolicySet.canonicalTenantId()) + || publishedVersionId != publishedPolicySet.versionId() + || !publishedPolicySet.policies().contains(selectedPolicyEvidence) + || !canonicalTenantId.equals(selectedPolicyEvidence.canonicalTenantId()) + || sourceGameRowId != selectedPolicyEvidence.sourceGameRowId() + || !sourceGameTenantKey.equals(selectedPolicyEvidence.sourceGameTenantKey()) + || !tenantIdentityProvenanceKind.equals( + selectedPolicyEvidence.tenantIdentityProvenanceKind()) + || !selectedPolicyEvidence.policy().visible() + || !selectedPolicyEvidence.policy().publicProduction() + || playableStateScope != RealmEntryPolicy.StateScope.SHARED + || selectedPolicyEvidence.policy().entryPolicy() + != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || selectedPolicyEvidence.policy().stateScope() != playableStateScope) { + throw new IllegalArgumentException("Published realm proof evidence is contradictory"); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadRequest.java new file mode 100644 index 0000000000..0a77ac61c3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadRequest.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact target and caller-observed revisions for a read-only published realm admission proof. */ +public record PublishedRealmAdmissionOwnerReadRequest( + String targetNamespace, + UUID canonicalTenantId, + long gameSessionTenantId, + String worldSlug, + String realmSlug, + long expectedCatalogRevision, + long expectedPointerVersion) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public PublishedRealmAdmissionOwnerReadRequest { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || canonicalTenantId == null + || NIL_UUID.equals(canonicalTenantId) + || gameSessionTenantId <= 0 + || expectedCatalogRevision <= 0 + || expectedPointerVersion <= 0) { + throw new IllegalArgumentException("Published realm admission target is incomplete"); + } + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + } + + private static void requireSlug(String value, String name) { + if (value == null || value.length() > 64 || !value.matches("[a-z0-9]+(?:-[a-z0-9]+)*")) { + throw new IllegalArgumentException(name + " must be a canonical published realm selector"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java new file mode 100644 index 0000000000..db277b1554 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java @@ -0,0 +1,315 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import tools.jackson.databind.ObjectMapper; + +/** Read-only composition of immutable published policy, current pointer, audit, and bind evidence. */ +@Service +@Lazy +public final class PublishedRealmAdmissionOwnerReadService { + private static final String PUBLISHED_SOURCE = "V14_PUBLISHED"; + private static final String INITIAL_BIND_ACTOR = "game-session-initial-admission-bind"; + private static final String INITIAL_BIND_REASON = "initial admission pointer bind"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private final InitialAdmissionBindCatalogRepository catalogRepository; + private final GameplayAdmissionPointerRepository pointerRepository; + private final GameplayAdmissionPointerEventRepository pointerEventRepository; + private final InitialAdmissionBindAttemptRepository attemptRepository; + private final InitialAdmissionBindOwnerProofReader ownerProofReader; + + public PublishedRealmAdmissionOwnerReadService( + InitialAdmissionBindCatalogRepository catalogRepository, + GameplayAdmissionPointerRepository pointerRepository, + GameplayAdmissionPointerEventRepository pointerEventRepository, + InitialAdmissionBindAttemptRepository attemptRepository, + InitialAdmissionBindOwnerProofReader ownerProofReader) { + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); + this.pointerEventRepository = + Objects.requireNonNull(pointerEventRepository, "pointerEventRepository"); + this.attemptRepository = Objects.requireNonNull(attemptRepository, "attemptRepository"); + this.ownerProofReader = Objects.requireNonNull(ownerProofReader, "ownerProofReader"); + } + + /** + * Reads exact published and owner-local evidence. The accepted source is deliberately limited to + * a currently unchanged version-1 pointer: this first-bind proof does not authorize a later, + * unproved pointer cutover. + */ + public PublishedRealmAdmissionOwnerReadProof read(PublishedRealmAdmissionOwnerReadRequest request) { + Objects.requireNonNull(request, "request"); + PublishedRealmCatalogSnapshot snapshot = + catalogRepository + .findPublishedSnapshot( + request.targetNamespace(), + request.gameSessionTenantId(), + request.expectedCatalogRevision()) + .orElseThrow( + () -> unresolved("PUBLISHED_REALM_ADMISSION_SNAPSHOT_MISSING")); + requireSnapshotMatchesRequest(snapshot, request); + + PublishedRealmCatalogEntry entry = + snapshot.requireVisibleEntryForAdmission(request.worldSlug(), request.realmSlug()); + requireSupportedPolicy(entry); + + GameplayAdmissionPointer pointer = + pointerRepository + .findByTenantIdAndWorldSlugAndRealmSlug( + request.gameSessionTenantId(), request.worldSlug(), request.realmSlug()) + .orElseThrow(() -> unresolved("PUBLISHED_REALM_ADMISSION_POINTER_MISSING")); + requireCurrentPointerMatches(pointer, snapshot, entry, request); + + GameplayAdmissionPointerEvent audit = + pointerEventRepository + .findLatestByTenantIdAndWorldSlugAndRealmSlug( + request.gameSessionTenantId(), request.worldSlug(), request.realmSlug()) + .orElseThrow(() -> unresolved("PUBLISHED_REALM_ADMISSION_POINTER_AUDIT_MISSING")); + requireLatestAuditMatches(audit, pointer, snapshot, entry, request); + + InitialAdmissionBindAttempt attempt = + attemptRepository + .findByTenantAndRequestId( + request.gameSessionTenantId(), audit.getControlPlaneRequestId()) + .orElseThrow(() -> unresolved("PUBLISHED_REALM_ADMISSION_BIND_ATTEMPT_MISSING")); + requirePublishedCommittedAttempt(attempt, snapshot, entry, pointer, audit, request); + + InitialAdmissionBindHoldBinding binding = binding(attempt); + InitialAdmissionBindOwnerProof ownerProof = ownerProofReader.read(binding); + requireOwnerProofMatches(ownerProof, attempt, audit, request); + + return new PublishedRealmAdmissionOwnerReadProof( + snapshot.tenantId(), + snapshot.canonicalTenantId(), + snapshot.sourceGameRowId(), + snapshot.sourceGameTenantKey(), + snapshot.tenantIdentityProvenanceKind(), + snapshot.policySetEvidence(), + entry.policyEvidence(), + snapshot.catalogRevision(), + entry.realmId(), + entry.requirePlayableStateNamespaceId(), + entry.policyEvidence().policy().stateScope(), + pointer.getPointerVersion(), + pointer.getGameInstanceId(), + attempt.versionId(), + attempt.activeLifecycleEpoch(), + attempt.gameTemplateId(), + attempt.launchDescriptorId(), + attempt.releaseBundleId(), + attempt.publishedReleaseBundleRef(), + attempt.versionStateEpoch(), + attempt.initialAdmissionRequestId(), + attempt.requestDigest(), + attempt.attemptId(), + audit.getId()); + } + + private static void requireSnapshotMatchesRequest( + PublishedRealmCatalogSnapshot snapshot, PublishedRealmAdmissionOwnerReadRequest request) { + if (snapshot.tenantId() != request.gameSessionTenantId() + || !request.targetNamespace().equals(snapshot.targetNamespace()) + || !request.canonicalTenantId().equals(snapshot.canonicalTenantId()) + || snapshot.catalogRevision() != request.expectedCatalogRevision() + || !request.canonicalTenantId().equals(snapshot.policySetEvidence().canonicalTenantId()) + || !snapshot.policySetEvidence().hasValidDigest(OBJECT_MAPPER)) { + throw unresolved("PUBLISHED_REALM_ADMISSION_SNAPSHOT_MISMATCH"); + } + } + + private static void requireSupportedPolicy(PublishedRealmCatalogEntry entry) { + RealmEntryPolicy policy = entry.policyEvidence().policy(); + if (entry.namespaceResolution() != NamespaceResolution.RESOLVED + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY) { + throw unresolved("PUBLISHED_REALM_ADMISSION_POLICY_UNSUPPORTED"); + } + } + + private static void requireCurrentPointerMatches( + GameplayAdmissionPointer pointer, + PublishedRealmCatalogSnapshot snapshot, + PublishedRealmCatalogEntry entry, + PublishedRealmAdmissionOwnerReadRequest request) { + RealmEntryPolicy policy = entry.policyEvidence().policy(); + if (pointer.getId() == null + || !Objects.equals(pointer.getTenantId(), request.gameSessionTenantId()) + || pointer.getGameInstanceId() == null + || pointer.getGameInstanceId() <= 0 + || !request.worldSlug().equals(pointer.getWorldSlug()) + || !request.realmSlug().equals(pointer.getRealmSlug()) + || !entry.realmId().equals(pointer.getRealmId()) + || !entry.requirePlayableStateNamespaceId().equals(pointer.getPlayableStateNamespaceId()) + || !Objects.equals(pointer.getCatalogRevision(), request.expectedCatalogRevision()) + || !Objects.equals(pointer.getPointerVersion(), request.expectedPointerVersion()) + || !Objects.equals(pointer.getPointerVersion(), 1L) + || !pointer.isVisible() + || !pointer.isPublicProductionRealm() + || !Objects.equals(pointer.getStateScope(), policy.stateScope().name()) + || !Objects.equals(pointer.getCharacterCreationPolicy(), policy.entryPolicy().name()) + || !INITIAL_BIND_ACTOR.equals(pointer.getLastUpdatedBy()) + || !INITIAL_BIND_REASON.equals(pointer.getLastUpdateReason()) + || snapshot.catalogRevision() != pointer.getCatalogRevision()) { + throw unresolved("PUBLISHED_REALM_ADMISSION_POINTER_STALE_OR_MISMATCHED"); + } + } + + private static void requireLatestAuditMatches( + GameplayAdmissionPointerEvent audit, + GameplayAdmissionPointer pointer, + PublishedRealmCatalogSnapshot snapshot, + PublishedRealmCatalogEntry entry, + PublishedRealmAdmissionOwnerReadRequest request) { + RealmEntryPolicy policy = entry.policyEvidence().policy(); + if (audit.getId() == null + || !Objects.equals(audit.getTenantId(), request.gameSessionTenantId()) + || !request.worldSlug().equals(audit.getWorldSlug()) + || !request.realmSlug().equals(audit.getRealmSlug()) + || !Objects.equals(audit.getWorldDisplayName(), policy.worldDisplayName()) + || !Objects.equals(audit.getRealmDisplayName(), policy.realmDisplayName()) + || !Objects.equals(audit.getGameInstanceId(), pointer.getGameInstanceId()) + || !Objects.equals(audit.getPointerVersion(), pointer.getPointerVersion()) + || !Objects.equals(audit.getCatalogRevision(), snapshot.catalogRevision()) + || !Objects.equals(audit.getRealmId(), entry.realmId()) + || !Objects.equals( + audit.getPlayableStateNamespaceId(), entry.requirePlayableStateNamespaceId()) + || !audit.isVisible() + || !audit.isPublicProductionRealm() + || !Objects.equals(audit.getStateScope(), policy.stateScope().name()) + || !Objects.equals(audit.getCharacterCreationPolicy(), policy.entryPolicy().name()) + || audit.isRequiresCharacterSelection() != pointer.isRequiresCharacterSelection() + || !INITIAL_BIND_ACTOR.equals(audit.getActorPrincipal()) + || !INITIAL_BIND_REASON.equals(audit.getReason()) + || !isCanonicalUuid(audit.getControlPlaneRequestId()) + || audit.getOccurredAt() == null) { + throw unresolved("PUBLISHED_REALM_ADMISSION_POINTER_AUDIT_MISMATCH"); + } + } + + private static void requirePublishedCommittedAttempt( + InitialAdmissionBindAttempt attempt, + PublishedRealmCatalogSnapshot snapshot, + PublishedRealmCatalogEntry entry, + GameplayAdmissionPointer pointer, + GameplayAdmissionPointerEvent audit, + PublishedRealmAdmissionOwnerReadRequest request) { + if (attempt.attemptId() == null + || attempt.status() != Status.COMMITTED + || !PUBLISHED_SOURCE.equals(attempt.catalogSourceKind()) + || !request.targetNamespace().equals(attempt.publishedTargetNamespace()) + || !request.canonicalTenantId().equals(attempt.canonicalTenantId()) + || attempt.tenantId() != request.gameSessionTenantId() + || !audit.getControlPlaneRequestId().equals(attempt.initialAdmissionRequestId()) + || attempt.requestDigest() == null + || !attempt.requestDigest().matches("[0-9a-f]{64}") + || !entry.realmId().equals(attempt.realmId()) + || !entry.requirePlayableStateNamespaceId().equals(attempt.playableStateNamespaceId()) + || !"SHARED".equals(attempt.playableStateScope()) + || !attempt.expectedNoPriorPointer() + || attempt.catalogRevision() != request.expectedCatalogRevision() + || attempt.versionId() != snapshot.policySetEvidence().versionId() + || attempt.gameInstanceId() != pointer.getGameInstanceId() + || attempt.activeLifecycleEpoch() <= 0 + || attempt.gameTemplateId() == null + || attempt.gameTemplateId() <= 0 + || attempt.launchDescriptorId() == null + || attempt.launchDescriptorId().isBlank() + || attempt.releaseBundleId() == null + || attempt.releaseBundleId() <= 0 + || attempt.publishedReleaseBundleRef() == null + || attempt.publishedReleaseBundleRef().isBlank() + || attempt.versionStateEpoch() == null + || attempt.versionStateEpoch() <= 0 + || attempt.holdId() == null + || attempt.holdFence() == null + || attempt.pointerId() == null + || !attempt.pointerId().equals(pointer.getId()) + || attempt.auditEventId() == null + || !attempt.auditEventId().equals(audit.getId()) + || attempt.terminalAt() == null) { + throw unresolved("PUBLISHED_REALM_ADMISSION_BIND_ATTEMPT_MISMATCH"); + } + } + + private static InitialAdmissionBindHoldBinding binding(InitialAdmissionBindAttempt attempt) { + return new InitialAdmissionBindHoldBinding( + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.tenantId(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.gameInstanceId(), + attempt.versionId(), + attempt.activeLifecycleEpoch(), + attempt.initialAdmissionRequestId(), + attempt.requestDigest(), + attempt.expectedNoPriorPointer(), + attempt.catalogRevision()); + } + + private static void requireOwnerProofMatches( + InitialAdmissionBindOwnerProof proof, + InitialAdmissionBindAttempt attempt, + GameplayAdmissionPointerEvent audit, + PublishedRealmAdmissionOwnerReadRequest request) { + if (proof == null + || proof.outcome() != InitialAdmissionBindOwnerProof.Outcome.COMMITTED + || !Objects.equals(proof.holdId(), attempt.holdId().toString()) + || !Objects.equals(proof.holdFence(), attempt.holdFence().toString()) + || proof.tenantId() != request.gameSessionTenantId() + || !Objects.equals(proof.realmUuid(), attempt.realmId().toString()) + || !Objects.equals( + proof.playableStateNamespaceUuid(), attempt.playableStateNamespaceId().toString()) + || !Objects.equals(proof.playableStateScope(), "SHARED") + || proof.gameInstanceId() != attempt.gameInstanceId() + || proof.versionId() != attempt.versionId() + || proof.activeLifecycleEpoch() != attempt.activeLifecycleEpoch() + || !Objects.equals(proof.initialAdmissionRequestId(), attempt.initialAdmissionRequestId()) + || !Objects.equals(proof.requestDigest(), attempt.requestDigest()) + || !Objects.equals(proof.ownerProofId(), attempt.attemptId().toString()) + || !proof.expectedNoPriorPointer() + || proof.expectedCatalogRevision() != request.expectedCatalogRevision() + || proof.pointerVersion() != request.expectedPointerVersion() + || !Objects.equals(proof.pointerAuditId(), audit.getId().toString()) + || !Objects.equals(proof.pointerAuditRequestDigest(), attempt.requestDigest()) + || proof.futureCommitPrevented() + || proof.ownerProofId() == null + || proof.ownerProofId().isBlank()) { + throw unresolved("PUBLISHED_REALM_ADMISSION_OWNER_PROOF_MISSING_OR_MISMATCHED"); + } + } + + private static IllegalStateException unresolved(String code) { + return new IllegalStateException( + code + ": authoritative published realm admission evidence is unavailable"); + } + + private static boolean isCanonicalUuid(String value) { + if (value == null) { + return false; + } + try { + return value.equals(UUID.fromString(value).toString()); + } catch (IllegalArgumentException exception) { + return false; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java new file mode 100644 index 0000000000..4cbdf40f22 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java @@ -0,0 +1,396 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +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.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; +import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmAdmissionOwnerReadServiceTest { + private static final String NAMESPACE = "realm-ns"; + private static final long GAME_SESSION_TENANT_ID = 70123L; + private static final long SOURCE_GAME_ROW_ID = 91L; + private static final String SOURCE_GAME_TENANT_KEY = "gd-tenant-91"; + private static final String PROVENANCE_KIND = "RETAINED_GAME_V29"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_NAMESPACE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID ATTEMPT_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID HOLD_FENCE = + UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final String REQUEST_ID = + "88888888-8888-4888-8888-888888888888"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final long PUBLISHED_VERSION_ID = 44L; + private static final int PUBLISHED_VERSION_NUMBER = 3; + private static final long CATALOG_REVISION = 8L; + private static final long GAME_INSTANCE_ID = 93L; + private static final long ACTIVE_LIFECYCLE_EPOCH = 12L; + private static final long POINTER_AUDIT_ID = 601L; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final InitialAdmissionBindCatalogRepository catalogRepository = + mock(InitialAdmissionBindCatalogRepository.class); + private final GameplayAdmissionPointerRepository pointerRepository = + mock(GameplayAdmissionPointerRepository.class); + private final GameplayAdmissionPointerEventRepository pointerEventRepository = + mock(GameplayAdmissionPointerEventRepository.class); + private final InitialAdmissionBindAttemptRepository attemptRepository = + mock(InitialAdmissionBindAttemptRepository.class); + private final InitialAdmissionBindOwnerProofReader ownerProofReader = + mock(InitialAdmissionBindOwnerProofReader.class); + private final PublishedRealmAdmissionOwnerReadService service = + new PublishedRealmAdmissionOwnerReadService( + catalogRepository, + pointerRepository, + pointerEventRepository, + attemptRepository, + ownerProofReader); + + @Test + void composesPublishedPolicyCurrentPointerAuditAndCommittedPublishedAttempt() { + PublishedRealmCatalogSnapshot snapshot = snapshot(); + PublishedRealmCatalogEntry entry = snapshot.entries().get(0); + GameplayAdmissionPointerSnapshot pointer = pointer(); + GameplayAdmissionPointerEvent audit = audit(); + InitialAdmissionBindAttempt attempt = attempt("V14_PUBLISHED"); + InitialAdmissionBindHoldBinding binding = binding(attempt); + stubSnapshot(snapshot); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug( + GAME_SESSION_TENANT_ID, "earth", "main")) + .thenReturn(Optional.of(pointer)); + when(pointerEventRepository.findLatestByTenantIdAndWorldSlugAndRealmSlug( + GAME_SESSION_TENANT_ID, "earth", "main")) + .thenReturn(Optional.of(audit)); + when(attemptRepository.findByTenantAndRequestId(GAME_SESSION_TENANT_ID, REQUEST_ID)) + .thenReturn(Optional.of(attempt)); + when(ownerProofReader.read(binding)).thenReturn(ownerProof()); + + PublishedRealmAdmissionOwnerReadProof proof = service.read(request()); + + assertThat(proof.gameSessionTenantId()).isEqualTo(GAME_SESSION_TENANT_ID); + assertThat(proof.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(proof.sourceGameRowId()).isEqualTo(SOURCE_GAME_ROW_ID); + assertThat(proof.sourceGameTenantKey()).isEqualTo(SOURCE_GAME_TENANT_KEY); + assertThat(proof.publishedPolicySet()).isEqualTo(snapshot.policySetEvidence()); + assertThat(proof.selectedPolicyEvidence()).isEqualTo(entry.policyEvidence()); + assertThat(proof.catalogRevision()).isEqualTo(CATALOG_REVISION); + assertThat(proof.playableStateNamespaceId()).isEqualTo(PLAYABLE_NAMESPACE_ID); + assertThat(proof.pointerVersion()).isEqualTo(1L); + assertThat(proof.gameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(proof.publishedVersionId()).isEqualTo(PUBLISHED_VERSION_ID); + assertThat(proof.activeLifecycleEpoch()).isEqualTo(ACTIVE_LIFECYCLE_EPOCH); + assertThat(proof.gameTemplateId()).isEqualTo(55L); + assertThat(proof.launchDescriptorId()).isEqualTo("launch-earth-v44"); + assertThat(proof.releaseBundleId()).isEqualTo(810L); + assertThat(proof.versionStateEpoch()).isEqualTo(6L); + assertThat(proof.initialAdmissionAttemptId()).isEqualTo(ATTEMPT_ID); + assertThat(proof.pointerAuditId()).isEqualTo(POINTER_AUDIT_ID); + verify(ownerProofReader).read(binding); + } + + @Test + void rejectsFixtureAttemptEvenWhenItsMutablePointerTupleMatches() { + stubSnapshot(snapshot()); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug( + GAME_SESSION_TENANT_ID, "earth", "main")) + .thenReturn(Optional.of(pointer())); + when(pointerEventRepository.findLatestByTenantIdAndWorldSlugAndRealmSlug( + GAME_SESSION_TENANT_ID, "earth", "main")) + .thenReturn(Optional.of(audit())); + when(attemptRepository.findByTenantAndRequestId(GAME_SESSION_TENANT_ID, REQUEST_ID)) + .thenReturn(Optional.of(attempt("V9_FIXTURE"))); + + assertThatThrownBy(() -> service.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_ADMISSION_BIND_ATTEMPT_MISMATCH"); + + verifyNoInteractions(ownerProofReader); + } + + @Test + void rejectsStaleOrLaterPointerVersionWithoutTreatingInitialBindAsCutoverProof() { + stubSnapshot(snapshot()); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug( + GAME_SESSION_TENANT_ID, "earth", "main")) + .thenReturn(Optional.of(pointer(2L))); + + assertThatThrownBy(() -> service.read(request(2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_ADMISSION_POINTER_STALE_OR_MISMATCHED"); + + verifyNoInteractions(pointerEventRepository, attemptRepository, ownerProofReader); + } + + @Test + void rejectsMissingOwnerProofAfterAllLocalTuplesMatch() { + PublishedRealmCatalogSnapshot snapshot = snapshot(); + InitialAdmissionBindAttempt attempt = attempt("V14_PUBLISHED"); + stubSnapshot(snapshot); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug( + GAME_SESSION_TENANT_ID, "earth", "main")) + .thenReturn(Optional.of(pointer())); + when(pointerEventRepository.findLatestByTenantIdAndWorldSlugAndRealmSlug( + GAME_SESSION_TENANT_ID, "earth", "main")) + .thenReturn(Optional.of(audit())); + when(attemptRepository.findByTenantAndRequestId(GAME_SESSION_TENANT_ID, REQUEST_ID)) + .thenReturn(Optional.of(attempt)); + when(ownerProofReader.read(binding(attempt))) + .thenReturn( + new InitialAdmissionBindOwnerProof( + InitialAdmissionBindOwnerProof.Outcome.PENDING, + HOLD_ID.toString(), + HOLD_FENCE.toString(), + GAME_SESSION_TENANT_ID, + REALM_ID.toString(), + PLAYABLE_NAMESPACE_ID.toString(), + "SHARED", + GAME_INSTANCE_ID, + PUBLISHED_VERSION_ID, + ACTIVE_LIFECYCLE_EPOCH, + REQUEST_ID, + REQUEST_DIGEST, + true, + CATALOG_REVISION, + ATTEMPT_ID.toString(), + Long.toString(POINTER_AUDIT_ID), + 1L, + REQUEST_DIGEST, + false)); + + assertThatThrownBy(() -> service.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("PUBLISHED_REALM_ADMISSION_OWNER_PROOF_MISSING_OR_MISMATCHED"); + } + + private void stubSnapshot(PublishedRealmCatalogSnapshot snapshot) { + when(catalogRepository.findPublishedSnapshot(NAMESPACE, GAME_SESSION_TENANT_ID, CATALOG_REVISION)) + .thenReturn(Optional.of(snapshot)); + } + + private static PublishedRealmAdmissionOwnerReadRequest request() { + return request(1L); + } + + private static PublishedRealmAdmissionOwnerReadRequest request(long pointerVersion) { + return new PublishedRealmAdmissionOwnerReadRequest( + NAMESPACE, + CANONICAL_TENANT_ID, + GAME_SESSION_TENANT_ID, + "earth", + "main", + CATALOG_REVISION, + pointerVersion); + } + + private static PublishedRealmCatalogSnapshot snapshot() { + PublishedRealmEntryPolicySetEvidence policySet = policySet(); + PublishedRealmCatalogEntry entry = + new PublishedRealmCatalogEntry( + GAME_SESSION_TENANT_ID, + CATALOG_REVISION, + REALM_ID, + PLAYABLE_NAMESPACE_ID, + NamespaceResolution.RESOLVED, + policySet.policies().get(0)); + return new PublishedRealmCatalogSnapshot( + GAME_SESSION_TENANT_ID, + NAMESPACE, + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE_KIND, + CATALOG_REVISION, + policySet, + List.of(entry), + Instant.parse("2026-10-02T00:00:00Z")); + } + + private static PublishedRealmEntryPolicySetEvidence policySet() { + String workflow = "publish:published-admission-owner-read-test"; + String manifest = "manifest-published-admission-owner-read-test"; + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, PUBLISHED_VERSION_ID, workflow, manifest, JSON); + String policyJson = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + PublishedRealmEntryPolicyEvidence evidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + CANONICAL_TENANT_ID, + PROVENANCE_KIND, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PUBLISHED_VERSION_ID, + PUBLISHED_VERSION_NUMBER, + 301L, + releaseIdentity, + workflow, + manifest, + RealmEntryPolicy.parse(policyJson, JSON), + JSON); + return PublishedRealmEntryPolicySetEvidence.create( + CANONICAL_TENANT_ID, + PUBLISHED_VERSION_ID, + PUBLISHED_VERSION_NUMBER, + releaseIdentity, + workflow, + manifest, + List.of(evidence), + JSON); + } + + private static GameplayAdmissionPointer pointer() { + return pointer(1L); + } + + private static GameplayAdmissionPointer pointer(long pointerVersion) { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setId(501L); + pointer.setWorldSlug("earth"); + pointer.setWorldDisplayName("Earth"); + pointer.setRealmSlug("main"); + pointer.setRealmDisplayName("Main"); + pointer.setTenantId(GAME_SESSION_TENANT_ID); + pointer.setGameInstanceId(GAME_INSTANCE_ID); + pointer.setPointerVersion(pointerVersion); + pointer.setCatalogRevision(CATALOG_REVISION); + pointer.setRealmId(REALM_ID); + pointer.setPlayableStateNamespaceId(PLAYABLE_NAMESPACE_ID); + pointer.setVisible(true); + pointer.setPublicProductionRealm(true); + pointer.setRequiresCharacterSelection(true); + pointer.setStateScope("SHARED"); + pointer.setCharacterCreationPolicy("PRESEEDED_ONLY"); + pointer.setLastUpdatedBy("game-session-initial-admission-bind"); + pointer.setLastUpdateReason("initial admission pointer bind"); + return pointer; + } + + private static GameplayAdmissionPointerEvent audit() { + GameplayAdmissionPointerEvent audit = new GameplayAdmissionPointerEvent(); + audit.setId(POINTER_AUDIT_ID); + audit.setWorldSlug("earth"); + audit.setWorldDisplayName("Earth"); + audit.setRealmSlug("main"); + audit.setRealmDisplayName("Main"); + audit.setTenantId(GAME_SESSION_TENANT_ID); + audit.setGameInstanceId(GAME_INSTANCE_ID); + audit.setPointerVersion(1L); + audit.setCatalogRevision(CATALOG_REVISION); + audit.setRealmId(REALM_ID); + audit.setPlayableStateNamespaceId(PLAYABLE_NAMESPACE_ID); + audit.setVisible(true); + audit.setPublicProductionRealm(true); + audit.setRequiresCharacterSelection(true); + audit.setStateScope("SHARED"); + audit.setCharacterCreationPolicy("PRESEEDED_ONLY"); + audit.setActorPrincipal("game-session-initial-admission-bind"); + audit.setReason("initial admission pointer bind"); + audit.setControlPlaneRequestId(REQUEST_ID); + audit.setOccurredAt(Instant.parse("2026-10-02T00:01:00Z")); + return audit; + } + + private static InitialAdmissionBindAttempt attempt(String catalogSourceKind) { + Instant createdAt = Instant.parse("2026-10-02T00:00:00Z"); + return new InitialAdmissionBindAttempt( + ATTEMPT_ID, + GAME_SESSION_TENANT_ID, + REQUEST_ID, + REQUEST_DIGEST, + REALM_ID, + PLAYABLE_NAMESPACE_ID, + "SHARED", + true, + CATALOG_REVISION, + GAME_INSTANCE_ID, + PUBLISHED_VERSION_ID, + ACTIVE_LIFECYCLE_EPOCH, + HOLD_ID, + HOLD_FENCE, + Status.COMMITTED, + 501L, + POINTER_AUDIT_ID, + createdAt, + createdAt, + createdAt, + catalogSourceKind, + NAMESPACE, + CANONICAL_TENANT_ID, + 55L, + "launch-earth-v44", + 810L, + "gd://tenant/44/release/810", + 6L); + } + + private static InitialAdmissionBindHoldBinding binding(InitialAdmissionBindAttempt attempt) { + return new InitialAdmissionBindHoldBinding( + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.tenantId(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.gameInstanceId(), + attempt.versionId(), + attempt.activeLifecycleEpoch(), + attempt.initialAdmissionRequestId(), + attempt.requestDigest(), + attempt.expectedNoPriorPointer(), + attempt.catalogRevision()); + } + + private static InitialAdmissionBindOwnerProof ownerProof() { + return new InitialAdmissionBindOwnerProof( + InitialAdmissionBindOwnerProof.Outcome.COMMITTED, + HOLD_ID.toString(), + HOLD_FENCE.toString(), + GAME_SESSION_TENANT_ID, + REALM_ID.toString(), + PLAYABLE_NAMESPACE_ID.toString(), + "SHARED", + GAME_INSTANCE_ID, + PUBLISHED_VERSION_ID, + ACTIVE_LIFECYCLE_EPOCH, + REQUEST_ID, + REQUEST_DIGEST, + true, + CATALOG_REVISION, + ATTEMPT_ID.toString(), + Long.toString(POINTER_AUDIT_ID), + 1L, + REQUEST_DIGEST, + false); + } +} From 8ccabc41a1cc1fefd56620a5ced7e52ab1ddf423 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:45:12 +1300 Subject: [PATCH 080/105] Validate published policy sets before mutation and prove admission source decoding --- .../game-design-service/README.md | 2 +- .../game-design-service/api-contracts.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 +- .../PublishedReleaseBundleServiceImpl.java | 12 +++ .../V31__published_realm_entry_policy.sql | 4 +- ...PublishedReleaseBundleServiceImplTest.java | 50 ++++++++++- ...InitialAdmissionBindAttemptRepository.java | 6 +- ...blishedRealmAdmissionOwnerReadService.java | 10 ++- ...dRealmInitialAdmissionBindCoordinator.java | 59 ++++++++----- ...abaseInitialAdmissionBindOwnerService.java | 28 ++++--- .../V15__published_initial_admission_bind.sql | 4 +- ...lAdmissionBindPostgresIntegrationTest.java | 3 +- ...ialAdmissionBindAttemptRepositoryTest.java | 84 ++++++++++++++++++- ...hedRealmAdmissionOwnerReadServiceTest.java | 20 +++-- ...lmInitialAdmissionBindCoordinatorTest.java | 3 +- 16 files changed, 232 insertions(+), 59 deletions(-) diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 2c88de1b49..4b521a52d0 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -16,7 +16,7 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved, because `GameAssetServiceImpl` uses `MultipartFile.getBytes()` without matching limits in `AssetStoreProperties`; upload admission and resource-safety readiness remain blocked. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. Publish/export later writes version-prefix objects and a manifest through the private object-store endpoint; target private-candidate/content-addressed publication and approved public `/assets/**` delivery remain unimplemented. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). -The owner-local tenant UUID read is implemented, but published realm-entry policy/descriptor/template production and Game Session/Entity admission composition remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused proof passed for the service (6/6), auth wiring (3/3), and shared evidence (2/2); the PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. See the exact API boundary and current proof record in [API Contracts](./api-contracts.md#runtime-tenant-identity-owner-read) and the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). +The owner-local tenant UUID read and the closed-v1 `REALM_ENTRY_POLICY` publication producer are implemented. The producer freezes policy revisions with full-version release evidence, rejecting tenant/version `realmSlug` duplicates and sets without exactly one visible public-production policy before mutation. Descriptor/template production and composition with Game Session's live catalog, pointer, namespace/scope, and Entity actor-entry paths remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Local PostgreSQL migration/readback execution remains unproved; no Docker or PostgreSQL runtime validation is claimed. See the exact API boundary in [API Contracts](./api-contracts.md#published-realm-entry-policy-owner-read) and the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). ## Responsibilities diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 38a97c65f5..e0f30a878b 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -121,7 +121,7 @@ Bounded transport outcomes are: `NOT_FOUND` when no owner row exists for the exa `SaveRevision` accepts `revisionKind=REALM_ENTRY_POLICY` only when `data` is one closed v1 JSON object containing exactly `schemaVersion`, `worldSlug`, `worldDisplayName`, `realmSlug`, `realmDisplayName`, `visible`, `publicProduction`, `stateScope`, and `entryPolicy`. The schema version is the integer `1`; every listed field is required and typed, booleans have no defaults, slugs are canonical lower-case ASCII selectors of at most 64 characters, and display names are trimmed, control-free text of at most 128 Unicode code points. The UTF-8 JSON document is bounded to 4096 bytes. Unknown fields, duplicate JSON keys, malformed values, and unsupported entry policies fail with `INVALID_ARGUMENT`. V1 accepts only `entryPolicy=PRESEEDED_ONLY`, with `stateScope=SHARED|ISOLATED`; descriptor and template fields are not valid for this policy. Other policy kinds remain unsupported until their artifacts are implemented. Realm policy revisions require a full DRAFT version and inherit their tenant/version from the existing revision transaction. The normal published-version immutability rule then prevents later edits. -When a full-version `PublishedReleaseBundle` is created, Game Design freezes every matching policy revision in the same transaction as the bundle, in separate insert-only policy rows. The write rechecks each exact source revision's tenant, version, kind, and positive owner-local revision ID; rejects duplicate `(worldSlug, realmSlug)` selector definitions; resolves the canonical tenant UUID, source game row, retained tenant key, and provenance kind through the exact Game Design `game` row; and allocates a separate UUID for each persisted policy. It does not guess or translate tenant identifiers. Policy JSON is stored in RFC 8785 canonical form. `release_bundle_identity` is `sha256:` over RFC 8785 canonical JSON containing the canonical tenant UUID, exact version ID, publish workflow ID, and manifest hash. `policy_digest` is `sha256:` over RFC 8785 canonical evidence binding the policy UUID, canonical tenant UUID and source provenance, exact version ID/number, source revision ID, release-bundle identity and its workflow/manifest values, and the canonical policy object. Database constraints reject duplicate selectors; update and delete attempts against frozen policy rows fail. +When a full-version `PublishedReleaseBundle` is created, Game Design freezes every matching policy revision in the same transaction as the bundle, in separate insert-only policy rows. Before any publication mutation, the write rechecks each exact source revision's tenant, version, kind, and positive owner-local revision ID; rejects duplicate `(worldSlug, realmSlug)` selectors and repeated `realmSlug` values across worlds; and requires exactly one policy with both `visible=true` and `publicProduction=true`. It then resolves the canonical tenant UUID, source game row, retained tenant key, and provenance kind through the exact Game Design `game` row, and allocates a separate UUID for each persisted policy. It does not guess or translate tenant identifiers. Policy JSON is stored in RFC 8785 canonical form. `release_bundle_identity` is `sha256:` over RFC 8785 canonical JSON containing the canonical tenant UUID, exact version ID, publish workflow ID, and manifest hash. `policy_digest` is `sha256:` over RFC 8785 canonical evidence binding the policy UUID, canonical tenant UUID and source provenance, exact version ID/number, source revision ID, release-bundle identity and its workflow/manifest values, and the canonical policy object. Database constraints reject duplicate selectors and repeated tenant/version `realmSlug` values; update and delete attempts against frozen policy rows fail. Publication without a `REALM_ENTRY_POLICY` revision remains valid for unrelated legacy publication behavior, but creates no realm-policy evidence. `ResolvePublishedRealmEntryPolicy` never infers policy from a release bundle or from current mutable revision data. It accepts exactly a canonical nonnil `canonical_tenant_id`, positive `version_id`, and the exact canonical `world_slug`/`realm_slug` selector pair. This selector read proves only that row; it is not a complete catalog, addressability-cardinality, or admission proof. Only the verified same-namespace Game Session workload may call it; the mTLS listener remains required, and the full method name is exempted from bearer-token validation in both base and production configuration. 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 8e34d6c70e..49ea9f3778 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. -Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; the issuance and source provenance are immutable. Reported focused V29 proof remains `TenantIdentityGrpcServiceTest` 6/6, `TenantIdentityGrpcAuthWiringTest` 3/3, and `RuntimeTenantIdentityEvidenceTest` 2/2; the PostgreSQL migration/readback test compiled but was not executed locally because Docker was unavailable. The current bounded owner-producer slice adds a closed-v1 `REALM_ENTRY_POLICY` revision path, transactionally frozen immutable policy rows at full-version release-bundle creation, a same-namespace authenticated exact-row read, and a complete-set read capped at 128 rows with owner-bound set identity/count. The latest locked validation passed the focused common evidence tests (4/4), Game Design `RevisionServiceImplTest` (15/15), `PublishedReleaseBundleServiceImplTest` (15/15), `TenantIdentityGrpcServiceTest` (12/12), and `TenantIdentityGrpcAuthWiringTest` (8/8), plus `generateJooq`, `compileIntegrationTestJava`, Java formatting checks, `linkCheck`, and Markdown lint. The migration/readback integration test was compiled but not executed; no Docker or PostgreSQL runtime validation was performed. Only complete-set evidence can establish the authored set's exactly-one-visible-publicProduction cardinality; neither it nor the selector read proves current Game Session catalog validity, pointer/namespace/scope composition, descriptor/template identity, Entity actor admission, or actor creation/activation. Target semantics remain in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), and actor-entry target behavior remains [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; issuance and source provenance are immutable. The closed-v1 `REALM_ENTRY_POLICY` owner producer accepts version-scoped revisions, freezes immutable policy rows transactionally with full-version release-bundle creation, and exposes same-namespace authenticated exact-row and bounded complete-set reads with owner-bound evidence. Publication preparation rejects repeated tenant/version `realmSlug` values across worlds and policy sets without exactly one visible public-production entry before persisting publication evidence. Local PostgreSQL migration/readback execution remains unproved; no Docker or PostgreSQL runtime validation is claimed. This producer and complete-set evidence do not establish current Game Session catalog validity, pointer/namespace/scope composition, descriptor/template identity, Entity actor admission, or actor creation/activation. Target semantics remain in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), and actor-entry behavior remains incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). The separate retained Game Session tenant-association prerequisite keeps immutable source-row/key/provenance and namespace/canonical/private-key claims while V32 moves signed approval labels, signature, and source-linked digests into an owner-local 30-day capture-expiring payload. V2 evidence binds the exact GS source capture time and both snapshot digests; retries do not renew expiry. Automatic bounded cleanup preserves terminal anti-reassignment rows. Hold audit references the immutable association claim, not erasable raw payload, and therefore survives payload cleanup. Under ADR 0050/0163 it is separate purpose-bound safety evidence requiring finite post-release retention/export/erasure policy; that schedule and a trusted authenticated owner policy are not implemented, so hold create/release remain fail-closed with no generic audit exemption. Test fixtures prove cleanup/reference behavior only, not authorization. Game Session's mapping-only internal read remains independent of expired/erased raw evidence. This prerequisite is not runtime catalog/admission authority and does not enable activation or public endpoints. Its focused validation and PostgreSQL/restore-proof limits are recorded in the owning service docs and [Player Access and Session](./player-access-and-session.md#current-status). 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 d2597ae4c5..5af3e40bd5 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 @@ -16,7 +16,7 @@ Admission-catalog foundation status: Game Session pointer and audit rows now per Published realm-policy receiving/catalog preparation: the lazy internal owner stages immutable snapshots from the complete Game Design policy set plus the committed local tenant association, with source-provenance validation and distinct local-private-tenant versus source-row identities. Tenant-wide `realmSlug` identity supports stable opaque namespaces for proven `SHARED` entries; catalog-only policy/display changes advance `catalogRevision` while preserving exact prior snapshots. Lifecycle resolution gates only the selected entry: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation has no namespace or initial-bind read, without blocking a proven shared entry. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md), [owner service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java), [snapshot](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java), and [owner-service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). -Published-snapshot initial-bind composition: the explicit internal coordinator consumes that immutable V14 snapshot and exact visible public `SHARED` `PRESEEDED_ONLY` entry, then cross-checks authored launch and World's exact ACTIVE lifecycle readback, including template, descriptor, version, release-bundle ID/reference, version-state epoch, and lifecycle epoch. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID: the existing authored-launch API passes one numeric tenant ID to both local ownership and Game Design descriptor lookup, so a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is retained as separate launch evidence alongside the V14 release digest, without inferred identity conversion. V15 links new `V14_PUBLISHED` attempts to the exact snapshot and entry while retaining historical V9 attempts as `V9_FIXTURE`; the owner writes `PRESEEDED_ONLY` directly and conservatively sets the legacy `requiresCharacterSelection` pointer field true. No startup/environment trigger or raw fixture promotion is added. Focused source-distinct fail-closed and PostgreSQL bind proofs are authored but this worktree has not run validation; restart/lost-response/finalize ambiguity remains for the consolidated proof. This code does not implement strict Account `JOIN`, actor/roster validation, or `PLAY` admission. See the [coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java), [V15 migration](../../../services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql), and [API contract status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). +Published-snapshot initial-bind composition: the explicit internal coordinator consumes that immutable V14 snapshot and exact visible public `SHARED` `PRESEEDED_ONLY` entry, then cross-checks authored launch and World's exact ACTIVE lifecycle readback, including template, descriptor, version, release-bundle ID/reference, version-state epoch, and lifecycle epoch. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID: the existing authored-launch API passes one numeric tenant ID to both local ownership and Game Design descriptor lookup, so a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is retained as separate launch evidence alongside the V14 release digest, without inferred identity conversion. V15 links new `V14_PUBLISHED` attempts to the exact snapshot and entry while retaining historical V9 attempts as `V9_FIXTURE`; the owner writes `PRESEEDED_ONLY` directly and conservatively sets the legacy `requiresCharacterSelection` pointer field true. No startup/environment trigger or raw fixture promotion is added. Ten focused Game Session tests passed on 2026-10-04, covering bind, historical/published repository decoding, unequal-source launch denial, and owner-read composition; PostgreSQL integration sources compiled, but PostgreSQL execution, restart/lost-response/finalize ambiguity and live World-held bind remain unproved. The internal owner read composes the unchanged first pointer, matching audit and committed published attempt; it is not fresh World ACTIVE proof or a validation-through-commit gate, and authenticated receiving transport remains unwired. This code does not implement strict Account `JOIN`, actor/roster validation, or `PLAY` admission. See the [coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java), [V15 migration](../../../services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql), and [API contract status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Initial-admission owner boundary: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 22ae7e263f..4e396f9c2c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -310,7 +310,9 @@ private List prepareRealmEntryPolicies(VersionDto versio } Set selectorPairs = new HashSet<>(); + Set realmSlugs = new HashSet<>(); List sources = new java.util.ArrayList<>(); + int visiblePublicProductionCount = 0; for (Revision revision : revisions) { if (revision == null || revision.getId() == null @@ -326,8 +328,18 @@ private List prepareRealmEntryPolicies(VersionDto versio if (!selectorPairs.add(pair)) { throw new IllegalStateException("Duplicate published realm-entry policy selector"); } + if (!realmSlugs.add(policy.realmSlug())) { + throw new IllegalStateException("Duplicate published realm-entry policy realm slug"); + } + if (policy.visible() && policy.publicProduction()) { + visiblePublicProductionCount++; + } sources.add(new RealmEntryPolicySource(revision, policy)); } + if (visiblePublicProductionCount != 1) { + throw new IllegalStateException( + "Realm-entry policy set must contain exactly one visible publicProduction realm"); + } return List.copyOf(sources); } diff --git a/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql b/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql index 3e840852fc..b178db85d8 100644 --- a/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql +++ b/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql @@ -32,7 +32,9 @@ CREATE TABLE published_realm_entry_policy ( policy_json TEXT NOT NULL CHECK (octet_length(policy_json) BETWEEN 1 AND 4096), policy_digest VARCHAR(71) NOT NULL CHECK (policy_digest ~ '^sha256:[0-9a-f]{64}$'), CONSTRAINT uq_published_realm_entry_policy_selector - UNIQUE (canonical_tenant_id, version_id, world_slug, realm_slug) + UNIQUE (canonical_tenant_id, version_id, world_slug, realm_slug), + CONSTRAINT uq_published_realm_entry_policy_realm_slug + UNIQUE (canonical_tenant_id, version_id, realm_slug) ); -- [jooq ignore start] diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 865b8bc19c..fb0fced9df 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -42,7 +42,7 @@ class PublishedReleaseBundleServiceImplTest { private static final String VALID_REALM_ENTRY_POLICY = "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main Realm\"," - + "\"visible\":true,\"publicProduction\":false,\"stateScope\":\"SHARED\"," + + "\"visible\":true,\"publicProduction\":true,\"stateScope\":\"SHARED\"," + "\"entryPolicy\":\"PRESEEDED_ONLY\"}"; @Mock private PublishedReleaseBundleRepository repository; @@ -217,6 +217,54 @@ void createFullVersionBundleRejectsWrongTenantVersionSourceAndDuplicateSelectors verify(gameRepository, never()).findRuntimeTenantIdentityByTenantKey("tenant-1"); } + @Test + void createFullVersionBundleRejectsRealmSlugRepeatedAcrossWorldsBeforeMutation() { + assertPolicySetRejectedBeforePublicationMutation( + VALID_REALM_ENTRY_POLICY, + VALID_REALM_ENTRY_POLICY.replace("\"worldSlug\":\"earth\"", "\"worldSlug\":\"mars\"")); + } + + @Test + void createFullVersionBundleRejectsPolicySetWithoutVisiblePublicProductionRealm() { + assertPolicySetRejectedBeforePublicationMutation( + VALID_REALM_ENTRY_POLICY.replace( + "\"publicProduction\":true", "\"publicProduction\":false")); + } + + @Test + void createFullVersionBundleRejectsPolicySetWithMultipleVisiblePublicProductionRealms() { + assertPolicySetRejectedBeforePublicationMutation( + VALID_REALM_ENTRY_POLICY, + VALID_REALM_ENTRY_POLICY + .replace("\"realmSlug\":\"main\"", "\"realmSlug\":\"side\"") + .replace("\"realmDisplayName\":\"Main Realm\"", "\"realmDisplayName\":\"Side Realm\"")); + } + + private void assertPolicySetRejectedBeforePublicationMutation(String... policyJson) { + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + List revisions = + java.util.stream.IntStream.range(0, policyJson.length) + .mapToObj(index -> policyRevision(21L + index, "tenant-1", 7L, policyJson[index])) + .toList(); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) + .thenReturn(revisions); + + assertThrows( + IllegalStateException.class, + () -> + service.createFullVersionBundle( + version(), + "workflow-1", + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of())); + + verify(repository, never()).save(any(PublishedReleaseBundle.class)); + verify(realmEntryPolicyRepository, never()).insert(any(PublishedRealmEntryPolicy.class)); + verify(gameRepository, never()).findRuntimeTenantIdentityByTenantKey("tenant-1"); + } + @Test void publishedPolicyReadRequiresPublishedBundleAndVerifiesFrozenEvidence() { PublishedReleaseBundle bundle = publishedBundle(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java index 067905f79a..0d1d82a9b8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java @@ -7,6 +7,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; +import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -29,7 +30,8 @@ public class InitialAdmissionBindAttemptRepository { private static final String ATTEMPT_LOCK_PREFIX = "initial-admission-bind-attempt:"; private static final String REALM_LOCK_PREFIX = "initial-admission-bind-realm:"; - private static final Field CATALOG_SOURCE_KIND = field("catalog_source_kind", String.class); + private static final Field CATALOG_SOURCE_KIND = + field("catalog_source_kind", String.class); private static final Field FIXTURE_CATALOG_REALM_ID = field("fixture_catalog_realm_id", UUID.class); private static final Field PUBLISHED_TARGET_NAMESPACE = @@ -133,7 +135,7 @@ public InitialAdmissionBindAttempt insertPending(InitialAdmissionBindAttempt att .set( GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT, toLocalDateTime(attempt.updatedAt())) - .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT, null) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT, (LocalDateTime) null) .set(CATALOG_SOURCE_KIND, attempt.catalogSourceKind()) .set( FIXTURE_CATALOG_REALM_ID, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java index db277b1554..a8939f2a0d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadService.java @@ -18,7 +18,9 @@ import org.springframework.stereotype.Service; import tools.jackson.databind.ObjectMapper; -/** Read-only composition of immutable published policy, current pointer, audit, and bind evidence. */ +/** + * Read-only composition of immutable published policy, current pointer, audit, and bind evidence. + */ @Service @Lazy public final class PublishedRealmAdmissionOwnerReadService { @@ -52,7 +54,8 @@ public PublishedRealmAdmissionOwnerReadService( * a currently unchanged version-1 pointer: this first-bind proof does not authorize a later, * unproved pointer cutover. */ - public PublishedRealmAdmissionOwnerReadProof read(PublishedRealmAdmissionOwnerReadRequest request) { + public PublishedRealmAdmissionOwnerReadProof read( + PublishedRealmAdmissionOwnerReadRequest request) { Objects.requireNonNull(request, "request"); PublishedRealmCatalogSnapshot snapshot = catalogRepository @@ -60,8 +63,7 @@ public PublishedRealmAdmissionOwnerReadProof read(PublishedRealmAdmissionOwnerRe request.targetNamespace(), request.gameSessionTenantId(), request.expectedCatalogRevision()) - .orElseThrow( - () -> unresolved("PUBLISHED_REALM_ADMISSION_SNAPSHOT_MISSING")); + .orElseThrow(() -> unresolved("PUBLISHED_REALM_ADMISSION_SNAPSHOT_MISSING")); requireSnapshotMatchesRequest(snapshot, request); PublishedRealmCatalogEntry entry = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java index 943d0e0040..f1625656cc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java @@ -18,15 +18,17 @@ import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; -import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; -/** Explicit internal composition of one immutable published realm with the World initial-bind hold. */ +/** + * Explicit internal composition of one immutable published realm with the World initial-bind hold. + */ @Service @Lazy public final class PublishedRealmInitialAdmissionBindCoordinator { @@ -84,7 +86,8 @@ public Result coordinate(PublishedRealmInitialAdmissionBindCommand command) { command.initialAdmissionRequestId(), command.ownerAccountId())); GameInstanceDto target = requireExactActiveLaunch(launch, command, snapshot); - WorldInstanceLifecycleSnapshot lifecycle = requireExactWorldLifecycle(target, command, snapshot); + WorldInstanceLifecycleSnapshot lifecycle = + requireExactWorldLifecycle(target, command, snapshot); if (launch.activeLifecycleEpoch() != lifecycle.getLifecycleEpoch()) { throw unresolved( "INITIAL_ADMISSION_WORLD_LIFECYCLE_MISMATCH: ACTIVE epoch differs from authored launch proof"); @@ -102,7 +105,9 @@ public Result coordinate(PublishedRealmInitialAdmissionBindCommand command) { command.publishedVersionId(), lifecycleEpoch, new InitialAdmissionBindRequest.PublishedCatalogBinding( - snapshot.targetNamespace(), snapshot.canonicalTenantId(), snapshot.catalogRevision()), + snapshot.targetNamespace(), + snapshot.canonicalTenantId(), + snapshot.catalogRevision()), new InitialAdmissionBindRequest.LaunchEvidence( command.gameTemplateId(), lifecycle.getLaunchDescriptorId(), @@ -125,24 +130,30 @@ public Result coordinate(PublishedRealmInitialAdmissionBindCommand command) { PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, snapshot.catalogRevision()); if (acquire == null || acquire.hasError() || !acquire.hasHold()) { - throw unresolved("INITIAL_ADMISSION_WORLD_HOLD_UNRESOLVED: World did not return the exact hold"); + throw unresolved( + "INITIAL_ADMISSION_WORLD_HOLD_UNRESOLVED: World did not return the exact hold"); } InitialAdmissionBindHold hold = acquire.getHold(); InitialAdmissionBindHoldBinding binding = requireExactHold(hold, request, entry, snapshot.catalogRevision()); - if (hold.getStatus() == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED - || hold.getStatus() == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED) { + if (hold.getStatus() + == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED + || hold.getStatus() + == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED) { return terminalResult(ownerService.read(binding), binding, attempt); } if (!isRetryable(hold.getStatus())) { - throw unresolved("INITIAL_ADMISSION_WORLD_HOLD_UNRESOLVED: World returned an unknown hold state"); + throw unresolved( + "INITIAL_ADMISSION_WORLD_HOLD_UNRESOLVED: World returned an unknown hold state"); } InitialAdmissionBindAttempt attached = ownerService.attachHold(binding); requireExactAttempt(attached, request, entry); InitialAdmissionBindOwnerProof proof = - attached.status() == net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status.PENDING + attached.status() + == net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status + .PENDING ? ownerService.commit(binding) : ownerService.read(binding); return terminalResult(proof, binding, attached); @@ -184,10 +195,12 @@ private WorldInstanceLifecycleSnapshot requireExactWorldLifecycle( try { response = worldManagementClient.getWorldInstanceLifecycle(snapshot.tenantId(), target.id()); } catch (RuntimeException exception) { - throw unresolved("INITIAL_ADMISSION_WORLD_LIFECYCLE_UNAVAILABLE: exact launch readback failed"); + throw unresolved( + "INITIAL_ADMISSION_WORLD_LIFECYCLE_UNAVAILABLE: exact launch readback failed"); } if (response == null || response.hasError() || !response.hasWorldInstance()) { - throw unresolved("INITIAL_ADMISSION_WORLD_LIFECYCLE_INVALID: exact launch readback is absent"); + throw unresolved( + "INITIAL_ADMISSION_WORLD_LIFECYCLE_INVALID: exact launch readback is absent"); } WorldInstanceLifecycleSnapshot lifecycle = response.getWorldInstance(); if (parsePositiveId(lifecycle.getTenantId(), "tenantId") != snapshot.tenantId() @@ -263,9 +276,11 @@ private static String sha256(String... fields) { output.write(encoded); } } - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); } catch (IOException | NoSuchAlgorithmException exception) { - throw new IllegalStateException("Initial admission request digest could not be computed", exception); + throw new IllegalStateException( + "Initial admission request digest could not be computed", exception); } } @@ -292,12 +307,14 @@ private static void requireExactAttempt( || !Objects.equals( attempt.canonicalTenantId(), request.publishedCatalog().canonicalTenantId()) || !Objects.equals(attempt.gameTemplateId(), request.launchEvidence().gameTemplateId()) - || !Objects.equals(attempt.launchDescriptorId(), request.launchEvidence().launchDescriptorId()) + || !Objects.equals( + attempt.launchDescriptorId(), request.launchEvidence().launchDescriptorId()) || !Objects.equals(attempt.releaseBundleId(), request.launchEvidence().releaseBundleId()) || !Objects.equals( attempt.publishedReleaseBundleRef(), request.launchEvidence().publishedReleaseBundleRef()) - || !Objects.equals(attempt.versionStateEpoch(), request.launchEvidence().versionStateEpoch())) { + || !Objects.equals( + attempt.versionStateEpoch(), request.launchEvidence().versionStateEpoch())) { throw unresolved("INITIAL_ADMISSION_ATTEMPT_READBACK_MISMATCH: durable intent changed"); } } @@ -322,7 +339,8 @@ private static InitialAdmissionBindHoldBinding requireExactHold( || hold.getExpectedCatalogRevision() != catalogRevision || hold.getStatus() == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED) { - throw unresolved("INITIAL_ADMISSION_WORLD_HOLD_MISMATCH: World returned a different hold tuple"); + throw unresolved( + "INITIAL_ADMISSION_WORLD_HOLD_MISMATCH: World returned a different hold tuple"); } return new InitialAdmissionBindHoldBinding( hold.getHoldId(), @@ -373,14 +391,15 @@ private Result terminalResult( && proof.pointerAuditId() == null) { return new Result(TerminalOutcome.ABORTED, proof); } - throw unresolved("INITIAL_ADMISSION_OWNER_PROOF_UNRESOLVED: exact terminal owner proof is absent"); + throw unresolved( + "INITIAL_ADMISSION_OWNER_PROOF_UNRESOLVED: exact terminal owner proof is absent"); } private static boolean isRetryable(InitialAdmissionBindHoldStatus status) { - return status - == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING + return status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING || status - == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED; + == InitialAdmissionBindHoldStatus + .INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED; } private static boolean isCanonicalUuid(String value) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java index c9212ec953..c8cd0a3f61 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java @@ -146,15 +146,21 @@ public InitialAdmissionBindAttempt beginIntent(InitialAdmissionBindRequest reque now, null, request.isPublishedCatalogRequest() ? PUBLISHED_SOURCE : FIXTURE_SOURCE, - request.publishedCatalog() == null ? null : request.publishedCatalog().targetNamespace(), - request.publishedCatalog() == null ? null : request.publishedCatalog().canonicalTenantId(), + request.publishedCatalog() == null + ? null + : request.publishedCatalog().targetNamespace(), + request.publishedCatalog() == null + ? null + : request.publishedCatalog().canonicalTenantId(), request.launchEvidence() == null ? null : request.launchEvidence().gameTemplateId(), request.launchEvidence() == null ? null : request.launchEvidence().launchDescriptorId(), request.launchEvidence() == null ? null : request.launchEvidence().releaseBundleId(), request.launchEvidence() == null ? null : request.launchEvidence().publishedReleaseBundleRef(), - request.launchEvidence() == null ? null : request.launchEvidence().versionStateEpoch())); + request.launchEvidence() == null + ? null + : request.launchEvidence().versionStateEpoch())); } @Override @@ -414,12 +420,13 @@ private InitialAdmissionBindCatalog requireCatalogForAttempt( () -> new IllegalStateException( "INITIAL_ADMISSION_PUBLISHED_ENTRY_MISSING: durable attempt lost its selected entry")); - InitialAdmissionBindCatalog catalog = requirePublishedCatalog( - snapshot, - entry, - attempt.gameTemplateId() == null ? 0L : attempt.gameTemplateId(), - entry.policyEvidence().policy().worldSlug(), - entry.policyEvidence().policy().realmSlug()); + InitialAdmissionBindCatalog catalog = + requirePublishedCatalog( + snapshot, + entry, + attempt.gameTemplateId() == null ? 0L : attempt.gameTemplateId(), + entry.policyEvidence().policy().worldSlug(), + entry.policyEvidence().policy().realmSlug()); if (!entry.playableStateNamespaceId().equals(attempt.playableStateNamespaceId()) || !catalog.stateScope().equals(attempt.playableStateScope()) || !PUBLISHED_SOURCE.equals(attempt.catalogSourceKind())) { @@ -609,8 +616,7 @@ private boolean matchesCatalogSource( && Objects.equals(attempt.gameTemplateId(), launch.gameTemplateId()) && Objects.equals(attempt.launchDescriptorId(), launch.launchDescriptorId()) && Objects.equals(attempt.releaseBundleId(), launch.releaseBundleId()) - && Objects.equals( - attempt.publishedReleaseBundleRef(), launch.publishedReleaseBundleRef()) + && Objects.equals(attempt.publishedReleaseBundleRef(), launch.publishedReleaseBundleRef()) && Objects.equals(attempt.versionStateEpoch(), launch.versionStateEpoch()); } return FIXTURE_SOURCE.equals(attempt.catalogSourceKind()) diff --git a/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql index 255861d6d1..d18f6828f6 100644 --- a/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql +++ b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql @@ -19,7 +19,9 @@ UPDATE gameplay_initial_admission_bind_attempt SET fixture_catalog_realm_id = realm_id; ALTER TABLE gameplay_initial_admission_bind_attempt - DROP CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_fk, + DROP CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_fk; + +ALTER TABLE gameplay_initial_admission_bind_attempt ADD CONSTRAINT gameplay_initial_admission_bind_attempt_fixture_catalog_fk FOREIGN KEY (tenant_id, fixture_catalog_realm_id, playable_state_namespace_id, catalog_revision) REFERENCES gameplay_initial_admission_bind_catalog diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 7f13030618..7e606844cc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -3,8 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.nio.file.Path; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -16,7 +16,6 @@ import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; import net.firedevops.firemud.gamesession.service.impl.DatabaseInitialAdmissionBindOwnerService; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java index 491f933d07..b3f93a1205 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java @@ -16,6 +16,84 @@ import org.junit.jupiter.api.Test; class InitialAdmissionBindAttemptRepositoryTest { + @Test + void insertAndReadPreservesHistoricalAndPublishedCatalogSources() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:initial-admission-catalog-sources;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + InitialAdmissionBindAttemptRepository repository = + new InitialAdmissionBindAttemptRepository(dsl); + + UUID historicalRealmId = UUID.randomUUID(); + InitialAdmissionBindAttempt historical = + repository.insertPending(attempt("request-historical", historicalRealmId)); + + assertEquals("V9_FIXTURE", historical.catalogSourceKind()); + assertEquals(Instant.parse("2026-10-01T00:00:00Z"), historical.createdAt()); + assertNull(historical.publishedTargetNamespace()); + assertNull(historical.canonicalTenantId()); + assertEquals( + historicalRealmId, + dsl.fetchOne( + "SELECT fixture_catalog_realm_id FROM gameplay_initial_admission_bind_attempt " + + "WHERE initial_admission_request_id = ?", + "request-historical") + .get(0, UUID.class)); + + UUID publishedRealmId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + InitialAdmissionBindAttempt published = + repository.insertPending( + new InitialAdmissionBindAttempt( + UUID.randomUUID(), + 17L, + "request-published", + "b".repeat(64), + publishedRealmId, + UUID.randomUUID(), + "SHARED", + true, + 3L, + 93L, + 44L, + 8L, + null, + null, + Status.PENDING, + null, + null, + Instant.parse("2026-10-03T00:00:00Z"), + Instant.parse("2026-10-03T00:00:00Z"), + null, + "V14_PUBLISHED", + "prod-west", + canonicalTenantId, + 51L, + "launch-descriptor-51", + 62L, + "bundle-ref-62", + 9L)); + + assertEquals("V14_PUBLISHED", published.catalogSourceKind()); + assertEquals(Instant.parse("2026-10-03T00:00:00Z"), published.createdAt()); + assertNull( + dsl.fetchOne( + "SELECT fixture_catalog_realm_id FROM gameplay_initial_admission_bind_attempt " + + "WHERE initial_admission_request_id = ?", + "request-published") + .get(0, UUID.class)); + assertEquals("prod-west", published.publishedTargetNamespace()); + assertEquals(canonicalTenantId, published.canonicalTenantId()); + assertEquals(51L, published.gameTemplateId()); + assertEquals("launch-descriptor-51", published.launchDescriptorId()); + assertEquals(62L, published.releaseBundleId()); + assertEquals("bundle-ref-62", published.publishedReleaseBundleRef()); + assertEquals(9L, published.versionStateEpoch()); + } + } + @Test void attachHoldOnlyAttachesToPendingAttemptWithNoExistingHold() throws Exception { try (Connection connection = @@ -112,6 +190,9 @@ playable_state_scope VARCHAR(32) NOT NULL, status VARCHAR(16) NOT NULL, pointer_id BIGINT, audit_event_id BIGINT, + created_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP NOT NULL, + terminal_at TIMESTAMP, catalog_source_kind VARCHAR(16) NOT NULL DEFAULT 'V9_FIXTURE', fixture_catalog_realm_id UUID, published_target_namespace VARCHAR(63), @@ -121,9 +202,6 @@ launch_descriptor_id VARCHAR(128), release_bundle_id BIGINT, published_release_bundle_ref VARCHAR(200), version_state_epoch BIGINT, - created_at TIMESTAMP NOT NULL, - updated_at TIMESTAMP NOT NULL, - terminal_at TIMESTAMP, UNIQUE (tenant_id, initial_admission_request_id) ) """); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java index 4cbdf40f22..7074c7d9c3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmAdmissionOwnerReadServiceTest.java @@ -25,6 +25,12 @@ import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProofReader; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadProof; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadService; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; @@ -39,13 +45,10 @@ class PublishedRealmAdmissionOwnerReadServiceTest { private static final UUID REALM_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final UUID PLAYABLE_NAMESPACE_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); - private static final UUID ATTEMPT_ID = - UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID ATTEMPT_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final UUID HOLD_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); - private static final UUID HOLD_FENCE = - UUID.fromString("77777777-7777-4777-8777-777777777777"); - private static final String REQUEST_ID = - "88888888-8888-4888-8888-888888888888"; + private static final UUID HOLD_FENCE = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final String REQUEST_ID = "88888888-8888-4888-8888-888888888888"; private static final String REQUEST_DIGEST = "a".repeat(64); private static final long PUBLISHED_VERSION_ID = 44L; private static final int PUBLISHED_VERSION_NUMBER = 3; @@ -77,7 +80,7 @@ class PublishedRealmAdmissionOwnerReadServiceTest { void composesPublishedPolicyCurrentPointerAuditAndCommittedPublishedAttempt() { PublishedRealmCatalogSnapshot snapshot = snapshot(); PublishedRealmCatalogEntry entry = snapshot.entries().get(0); - GameplayAdmissionPointerSnapshot pointer = pointer(); + GameplayAdmissionPointer pointer = pointer(); GameplayAdmissionPointerEvent audit = audit(); InitialAdmissionBindAttempt attempt = attempt("V14_PUBLISHED"); InitialAdmissionBindHoldBinding binding = binding(attempt); @@ -190,7 +193,8 @@ void rejectsMissingOwnerProofAfterAllLocalTuplesMatch() { } private void stubSnapshot(PublishedRealmCatalogSnapshot snapshot) { - when(catalogRepository.findPublishedSnapshot(NAMESPACE, GAME_SESSION_TENANT_ID, CATALOG_REVISION)) + when(catalogRepository.findPublishedSnapshot( + NAMESPACE, GAME_SESSION_TENANT_ID, CATALOG_REVISION)) .thenReturn(Optional.of(snapshot)); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java index 60ecb67f9f..55de829fbb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java @@ -27,8 +27,7 @@ class PublishedRealmInitialAdmissionBindCoordinatorTest { private static final UUID CANONICAL_TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final UUID REALM_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); - private static final UUID NAMESPACE_ID = - UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final long LOCAL_GAME_SESSION_TENANT_ID = 41L; private static final long SOURCE_GAME_ROW_ID = 731L; private static final long PUBLISHED_VERSION_ID = 902L; From 438301bb146db9df5ca23ce2a5b1174bcfcbf0b8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:00:18 +1300 Subject: [PATCH 081/105] Expose exact authenticated published realm owner read to Entity --- .../game-session-service/api-contracts.md | 2 + .../v1/game_session_service.proto | 55 ++++ .../GameSessionControlPlaneGrpcService.java | 294 +++++++++++++++++ ...dRealmAdmissionOwnerReadWorkloadGuard.java | 46 +++ ...ealmAdmissionOwnerReadGrpcServiceTest.java | 306 ++++++++++++++++++ ...lmAdmissionOwnerReadWorkloadGuardTest.java | 101 ++++++ 6 files changed, 804 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuard.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 29b7304e8f..343003e95f 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -16,6 +16,8 @@ V12 retains the immutable tenant-association claim; V13 separates its account-li Published realm-policy receiving/catalog preparation: the lazy internal [catalog owner](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java) reads the committed minimal Game Session tenant association and complete Game Design policy set before its local transaction, rejects source-provenance mismatches, and freezes the exact owner evidence into an immutable [catalog snapshot](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java) using the local private tenant ID rather than the Game Design source row ID. Durable realm identity is canonical tenant plus tenant-wide unique `realmSlug`; proven `SHARED` entries retain a stable opaque playable-state namespace, and policy/display-only changes advance `catalogRevision` without changing pointer version or old snapshot reads. Lifecycle resolution is selected-entry scoped: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation exposes no namespace or initial-bind read, while an unrelated unresolved private entry does not block a proven shared-entry read. An explicit internal [published bind coordinator](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java) selects an exact V14 snapshot/entry, then cross-checks authored launch and World lifecycle readback before persisting a V14-linked intent and acquiring/attaching the World hold; its GS transaction commits pointer, audit, and outcome together. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID because the existing launch API uses one numeric ID for both roles; a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is validated against authored launch readback and stored separately from the V14 release digest; no identity translation is inferred. New attempts retain the configured target namespace, canonical tenant UUID, retained local GS tenant ID, selected realm/namespace/revision, published version/release evidence, and exact local launch tuple; V9 fixture attempts remain separately identified historical evidence. The new composition and focused proof have not yet been run in this worktree. It does not establish actor validation, roster cardinality, strict Account `JOIN`, or `PLAY` admission. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), the [policy client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and focused [client](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) and [owner-service tests](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). +The internal `GameSessionControlPlaneService.GetPublishedRealmAdmissionOwnerRead` RPC returns this composed, point-in-time owner read to Entity Management. It requires the exact Entity Management SPIFFE peer URI in the configured workload namespace, a matching target namespace, and no authenticated caller context; it is not part of the player-facing `GameSessionService.GetAdmissionPointer` surface. Its typed response carries the complete Game Design policy-set/selected-policy evidence plus the validated unchanged pointer, published runtime tuple, committed initial-bind attempt identity/status/digest, and pointer-audit ID with its matching request identity/digest. The read confirms the existing first pointer bind only: it is not a fresh World `ACTIVE` observation or validation-through-commit admission gate. Malformed selectors fail with gRPC `INVALID_ARGUMENT`, unauthorized peers/targets with `PERMISSION_DENIED`, and mismatched, missing, or unavailable owner evidence with `UNAVAILABLE`; failures have no proof payload. The Entity client and focused receiver/guard validation remain pending and are not established by this receiving surface. + This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: - the shipped pause/resume control path is `PauseTicksForScope` / `ResumeTicksForScope` at the current `{tenantId, gameInstanceId}` runtime boundary; diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index adf1810f08..c868ca2163 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -4,6 +4,7 @@ package game_session.v1; import "entity-management/v1/entity_management_service.proto"; import "game-design/v1/game_design_service.proto"; +import "game-design/v1/tenant_identity_service.proto"; import "shared/v1/errors.proto"; option java_package = "net.firedevops.firemud.gamesession.v1"; @@ -41,6 +42,9 @@ service GameSessionControlPlaneService { // Read exact durable owner proof for a World-owned initial-admission hold. rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) returns (GetInitialAdmissionBindProofResponse); + // Read the exact point-in-time published-realm admission owner composition for Entity. + rpc GetPublishedRealmAdmissionOwnerRead(GetPublishedRealmAdmissionOwnerReadRequest) + returns (GetPublishedRealmAdmissionOwnerReadResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -500,6 +504,57 @@ message GetInitialAdmissionBindProofResponse { shared.v1.ErrorDetail error = 20; } +message GetPublishedRealmAdmissionOwnerReadRequest { + string target_namespace = 1; + string canonical_tenant_id = 2; + string game_session_tenant_id = 3; + string world_slug = 4; + string realm_slug = 5; + int64 expected_catalog_revision = 6; + int64 expected_pointer_version = 7; +} + +message PublishedRealmAdmissionOwnerReadEvidence { + string target_namespace = 1; + string canonical_tenant_id = 2; + string game_session_tenant_id = 3; + string world_slug = 4; + string realm_slug = 5; + int64 catalog_revision = 6; + int64 expected_pointer_version = 7; + string realm_id = 8; + string playable_state_namespace_id = 9; + gamedesign.v1.PublishedRealmEntryStateScope playable_state_scope = 10; + gamedesign.v1.ListPublishedRealmEntryPoliciesResponse published_policy_set = 11; + gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse selected_policy_evidence = 12; + int64 pointer_version = 13; + string game_instance_id = 14; + string published_version_id = 15; + int64 active_lifecycle_epoch = 16; + string game_template_id = 17; + string launch_descriptor_id = 18; + string release_bundle_id = 19; + string published_release_bundle_ref = 20; + int64 version_state_epoch = 21; + string initial_admission_request_id = 22; + string request_digest = 23; + string initial_admission_attempt_id = 24; + string pointer_audit_id = 25; + PublishedRealmAdmissionAttemptStatus initial_admission_attempt_status = 26; + string pointer_audit_request_id = 27; + string pointer_audit_request_digest = 28; +} + +enum PublishedRealmAdmissionAttemptStatus { + PUBLISHED_REALM_ADMISSION_ATTEMPT_STATUS_UNSPECIFIED = 0; + PUBLISHED_REALM_ADMISSION_ATTEMPT_STATUS_COMMITTED = 1; +} + +message GetPublishedRealmAdmissionOwnerReadResponse { + // Present only when the complete owner composition was read and validated. + PublishedRealmAdmissionOwnerReadEvidence proof = 1; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index bfe78ed281..e50d38e488 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -14,13 +15,24 @@ import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyKind; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryStateScope; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProofReader; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadProof; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadService; import net.firedevops.firemud.gamesession.service.impl.GameSessionAdmissionPointerControlPlaneService.AdmissionPointerMutationPreconditionException; import net.firedevops.firemud.gamesession.v1.EnqueueAutomationCommandIfAbsentRequest; import net.firedevops.firemud.gamesession.v1.EnqueueAutomationCommandIfAbsentResponse; @@ -37,6 +49,8 @@ import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofResponse; import net.firedevops.firemud.gamesession.v1.GetPinnedScriptPatchVersionRequest; import net.firedevops.firemud.gamesession.v1.GetPinnedScriptPatchVersionResponse; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; import net.firedevops.firemud.gamesession.v1.GetPreparedVersionUpgradeRequest; import net.firedevops.firemud.gamesession.v1.GetPreparedVersionUpgradeResponse; import net.firedevops.firemud.gamesession.v1.GetRemoteCommandCoordinatorRequest; @@ -62,6 +76,8 @@ import net.firedevops.firemud.gamesession.v1.PauseTicksForScopeResponse; import net.firedevops.firemud.gamesession.v1.PrepareVersionUpgradeRequest; import net.firedevops.firemud.gamesession.v1.PrepareVersionUpgradeResponse; +import net.firedevops.firemud.gamesession.v1.PublishedRealmAdmissionOwnerReadEvidence; +import net.firedevops.firemud.gamesession.v1.PublishedRealmAdmissionAttemptStatus; import net.firedevops.firemud.gamesession.v1.PurgeQueuedTickCommandsForPluginVersionRequest; import net.firedevops.firemud.gamesession.v1.PurgeQueuedTickCommandsForPluginVersionResponse; import net.firedevops.firemud.gamesession.v1.PurgeQueuedTickCommandsForScriptPatchRequest; @@ -112,8 +128,11 @@ public final class GameSessionControlPlaneGrpcService private final MeterRegistry meterRegistry; private InitialAdmissionBindOwnerProofReader initialAdmissionBindOwnerProofReader; private InitialAdmissionBindOwnerReadWorkloadGuard initialAdmissionBindOwnerReadWorkloadGuard; + private PublishedRealmAdmissionOwnerReadService publishedRealmAdmissionOwnerReadService; + private PublishedRealmAdmissionOwnerReadWorkloadGuard publishedRealmAdmissionOwnerReadWorkloadGuard; private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); + private static final int MAX_PUBLISHED_REALM_ADMISSION_OWNER_READ_REQUEST_BYTES = 512; @Value("${game.tick-duration-ms:1000}") private long tickDurationMs = 1000L; @@ -145,6 +164,15 @@ public void configureInitialAdmissionBindOwnerReadBoundary( new InitialAdmissionBindOwnerReadWorkloadGuard(workloadNamespace); } + @Autowired + public void configurePublishedRealmAdmissionOwnerReadBoundary( + PublishedRealmAdmissionOwnerReadService ownerReadService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.publishedRealmAdmissionOwnerReadService = ownerReadService; + this.publishedRealmAdmissionOwnerReadWorkloadGuard = + new PublishedRealmAdmissionOwnerReadWorkloadGuard(workloadNamespace); + } + private long parseTenantId(String tenantId) { return ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_id"); } @@ -285,6 +313,106 @@ public void getInitialAdmissionBindProof( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamesessionGrpc.controlPlane.getPublishedRealmAdmissionOwnerRead") + public void getPublishedRealmAdmissionOwnerRead( + GetPublishedRealmAdmissionOwnerReadRequest request, + StreamObserver responseObserver) { + if (request == null) { + failPublishedRealmAdmissionOwnerRead( + responseObserver, + Status.INVALID_ARGUMENT, + "Invalid published realm admission owner read request"); + return; + } + + try { + if (publishedRealmAdmissionOwnerReadWorkloadGuard == null) { + throw new AdminAuthorizationException( + "Published realm admission owner read boundary is not configured"); + } + publishedRealmAdmissionOwnerReadWorkloadGuard.requireEntityManagementOwnerReadCaller(); + } catch (AdminAuthorizationException exception) { + failPublishedRealmAdmissionOwnerRead( + responseObserver, + Status.PERMISSION_DENIED, + "Published realm admission owner read caller is not authorized"); + return; + } + + PublishedRealmAdmissionOwnerReadRequest target; + try { + target = parsePublishedRealmAdmissionOwnerReadRequest(request); + } catch (IllegalArgumentException exception) { + failPublishedRealmAdmissionOwnerRead( + responseObserver, + Status.INVALID_ARGUMENT, + "Invalid published realm admission owner read request"); + return; + } + try { + publishedRealmAdmissionOwnerReadWorkloadGuard.requireConfiguredTargetNamespace( + target.targetNamespace()); + } catch (AdminAuthorizationException exception) { + failPublishedRealmAdmissionOwnerRead( + responseObserver, + Status.PERMISSION_DENIED, + "Published realm admission owner read target namespace is not authorized"); + return; + } + + if (publishedRealmAdmissionOwnerReadService == null) { + failPublishedRealmAdmissionOwnerRead( + responseObserver, + Status.UNAVAILABLE, + "Published realm admission owner authority is unavailable"); + return; + } + + PublishedRealmAdmissionOwnerReadEvidence wireProof; + try { + PublishedRealmAdmissionOwnerReadProof proof = + publishedRealmAdmissionOwnerReadService.read(target); + if (proof == null || !matchesPublishedRealmAdmissionOwnerReadRequest(target, proof)) { + throw new IllegalStateException( + "Published realm admission owner read returned mismatched authority"); + } + wireProof = toWirePublishedRealmAdmissionOwnerReadEvidence(request, proof); + } catch (IllegalArgumentException | IllegalStateException exception) { + failPublishedRealmAdmissionOwnerRead( + responseObserver, + Status.UNAVAILABLE, + "Published realm admission owner authority is unavailable"); + return; + } catch (Exception exception) { + logger.error("GetPublishedRealmAdmissionOwnerRead failed", exception); + boolean unavailable = isPersistenceAvailabilityFailure(exception); + failPublishedRealmAdmissionOwnerRead( + responseObserver, + unavailable ? Status.UNAVAILABLE : Status.INTERNAL, + unavailable + ? "Published realm admission owner authority is unavailable" + : "Published realm admission owner read failed"); + return; + } + responseObserver.onNext( + GetPublishedRealmAdmissionOwnerReadResponse.newBuilder().setProof(wireProof).build()); + responseObserver.onCompleted(); + } + + private void failPublishedRealmAdmissionOwnerRead( + StreamObserver responseObserver, + Status status, + String description) { + GrpcAppErrors.error( + meterRegistry, + logger, + "GetPublishedRealmAdmissionOwnerRead", + status.getCode().name(), + description); + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + private GetInitialAdmissionBindProofResponse.Builder echoInitialAdmissionBindTuple( GetInitialAdmissionBindProofRequest request) { return GetInitialAdmissionBindProofResponse.newBuilder() @@ -373,6 +501,172 @@ private String requireCanonicalUuid(String value, String fieldName) { } } + private PublishedRealmAdmissionOwnerReadRequest parsePublishedRealmAdmissionOwnerReadRequest( + GetPublishedRealmAdmissionOwnerReadRequest request) { + if (request.getSerializedSize() > MAX_PUBLISHED_REALM_ADMISSION_OWNER_READ_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("request is oversized or contains unsupported fields"); + } + String targetNamespace = request.getTargetNamespace(); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("target_namespace is invalid"); + } + if (request.getCanonicalTenantId().length() != 36) { + throw new IllegalArgumentException("canonical_tenant_id must be a canonical UUID"); + } + String canonicalTenantId = + requireCanonicalUuid(request.getCanonicalTenantId(), "canonical_tenant_id"); + long gameSessionTenantId = + parseCanonicalPositiveLong(request.getGameSessionTenantId(), "game_session_tenant_id"); + if (!RealmEntryPolicy.isCanonicalSlug(request.getWorldSlug())) { + throw new IllegalArgumentException("world_slug must be a canonical published realm selector"); + } + if (!RealmEntryPolicy.isCanonicalSlug(request.getRealmSlug())) { + throw new IllegalArgumentException("realm_slug must be a canonical published realm selector"); + } + return new PublishedRealmAdmissionOwnerReadRequest( + targetNamespace, + UUID.fromString(canonicalTenantId), + gameSessionTenantId, + request.getWorldSlug(), + request.getRealmSlug(), + ControlPlaneRequestParser.requirePositive( + request.getExpectedCatalogRevision(), "expected_catalog_revision"), + ControlPlaneRequestParser.requirePositive( + request.getExpectedPointerVersion(), "expected_pointer_version")); + } + + private long parseCanonicalPositiveLong(String value, String fieldName) { + if (value == null || value.isBlank() || value.length() > 19) { + throw new IllegalArgumentException(fieldName + " is invalid"); + } + long parsed = ControlPlaneRequestParser.parsePositiveLong(value, fieldName); + if (!Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(fieldName + " must use canonical decimal form"); + } + return parsed; + } + + private boolean matchesPublishedRealmAdmissionOwnerReadRequest( + PublishedRealmAdmissionOwnerReadRequest request, + PublishedRealmAdmissionOwnerReadProof proof) { + return request.canonicalTenantId().equals(proof.canonicalTenantId()) + && request.gameSessionTenantId() == proof.gameSessionTenantId() + && request.expectedCatalogRevision() == proof.catalogRevision() + && request.expectedPointerVersion() == proof.pointerVersion() + && request.worldSlug().equals(proof.selectedPolicyEvidence().policy().worldSlug()) + && request.realmSlug().equals(proof.selectedPolicyEvidence().policy().realmSlug()) + && proof.publishedVersionId() == proof.publishedPolicySet().versionId() + && proof.publishedPolicySet().canonicalTenantId().equals(request.canonicalTenantId()) + && proof.publishedPolicySet().policies().contains(proof.selectedPolicyEvidence()); + } + + private PublishedRealmAdmissionOwnerReadEvidence toWirePublishedRealmAdmissionOwnerReadEvidence( + GetPublishedRealmAdmissionOwnerReadRequest request, + PublishedRealmAdmissionOwnerReadProof proof) { + return PublishedRealmAdmissionOwnerReadEvidence.newBuilder() + .setTargetNamespace(request.getTargetNamespace()) + .setCanonicalTenantId(proof.canonicalTenantId().toString()) + .setGameSessionTenantId(Long.toString(proof.gameSessionTenantId())) + .setWorldSlug(proof.selectedPolicyEvidence().policy().worldSlug()) + .setRealmSlug(proof.selectedPolicyEvidence().policy().realmSlug()) + .setCatalogRevision(proof.catalogRevision()) + .setExpectedPointerVersion(proof.pointerVersion()) + .setRealmId(proof.realmId().toString()) + .setPlayableStateNamespaceId(proof.playableStateNamespaceId().toString()) + .setPlayableStateScope(toWireStateScope(proof.playableStateScope())) + .setPublishedPolicySet( + toWirePublishedPolicySet(request.getTargetNamespace(), proof.publishedPolicySet())) + .setSelectedPolicyEvidence( + toWirePublishedRealmAdmissionPolicy( + request.getTargetNamespace(), proof.selectedPolicyEvidence())) + .setPointerVersion(proof.pointerVersion()) + .setGameInstanceId(Long.toString(proof.gameInstanceId())) + .setPublishedVersionId(Long.toString(proof.publishedVersionId())) + .setActiveLifecycleEpoch(proof.activeLifecycleEpoch()) + .setGameTemplateId(Long.toString(proof.gameTemplateId())) + .setLaunchDescriptorId(proof.launchDescriptorId()) + .setReleaseBundleId(Long.toString(proof.releaseBundleId())) + .setPublishedReleaseBundleRef(proof.publishedReleaseBundleRef()) + .setVersionStateEpoch(proof.versionStateEpoch()) + .setInitialAdmissionRequestId(proof.initialAdmissionRequestId()) + .setRequestDigest(proof.requestDigest()) + .setInitialAdmissionAttemptId(proof.initialAdmissionAttemptId().toString()) + .setPointerAuditId(Long.toString(proof.pointerAuditId())) + .setPointerAuditRequestId(proof.initialAdmissionRequestId()) + .setPointerAuditRequestDigest(proof.requestDigest()) + .setInitialAdmissionAttemptStatus( + PublishedRealmAdmissionAttemptStatus + .PUBLISHED_REALM_ADMISSION_ATTEMPT_STATUS_COMMITTED) + .build(); + } + + private ListPublishedRealmEntryPoliciesResponse toWirePublishedPolicySet( + String targetNamespace, PublishedRealmEntryPolicySetEvidence evidence) { + ListPublishedRealmEntryPoliciesResponse.Builder result = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setSchemaVersion(RealmEntryPolicy.SCHEMA_VERSION) + .setTargetNamespace(targetNamespace) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setVersionId(evidence.versionId()) + .setVersionNumber(evidence.versionNumber()) + .setReleaseBundleIdentity(evidence.releaseBundleIdentity()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setManifestHash(evidence.manifestHash()) + .setPolicyCount(evidence.policies().size()) + .setPolicySetDigest(evidence.policySetDigest()); + evidence + .policies() + .forEach( + policy -> + result.addPolicies(toWirePublishedRealmAdmissionPolicy(targetNamespace, policy))); + return result.build(); + } + + private ResolvePublishedRealmEntryPolicyResponse toWirePublishedRealmAdmissionPolicy( + String targetNamespace, PublishedRealmEntryPolicyEvidence evidence) { + RealmEntryPolicy policy = evidence.policy(); + return ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setSchemaVersion(policy.schemaVersion()) + .setTargetNamespace(targetNamespace) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setVersionId(evidence.versionId()) + .setVersionNumber(evidence.versionNumber()) + .setPolicyId(evidence.policyId().toString()) + .setSourceRevisionId(evidence.sourceRevisionId()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setTenantIdentityProvenanceKind(evidence.tenantIdentityProvenanceKind()) + .setReleaseBundleIdentity(evidence.releaseBundleIdentity()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setManifestHash(evidence.manifestHash()) + .setWorldSlug(policy.worldSlug()) + .setWorldDisplayName(policy.worldDisplayName()) + .setRealmSlug(policy.realmSlug()) + .setRealmDisplayName(policy.realmDisplayName()) + .setVisible(policy.visible()) + .setPublicProduction(policy.publicProduction()) + .setStateScope(toWireStateScope(policy.stateScope())) + .setEntryPolicy(toWireEntryPolicy(policy.entryPolicy())) + .setPolicyJson(policy.canonicalJson()) + .setPolicyDigest(evidence.policyDigest()) + .build(); + } + + private PublishedRealmEntryStateScope toWireStateScope(RealmEntryPolicy.StateScope scope) { + return switch (scope) { + case SHARED -> PublishedRealmEntryStateScope.PUBLISHED_REALM_ENTRY_STATE_SCOPE_SHARED; + case ISOLATED -> PublishedRealmEntryStateScope.PUBLISHED_REALM_ENTRY_STATE_SCOPE_ISOLATED; + }; + } + + private PublishedRealmEntryPolicyKind toWireEntryPolicy(RealmEntryPolicy.EntryPolicy policy) { + return switch (policy) { + case PRESEEDED_ONLY -> + PublishedRealmEntryPolicyKind.PUBLISHED_REALM_ENTRY_POLICY_KIND_PRESEEDED_ONLY; + }; + } + private InitialAdmissionBindOwnerProofOutcome toWireOutcome( InitialAdmissionBindOwnerProof.Outcome outcome) { if (outcome == null) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuard.java new file mode 100644 index 0000000000..bcdc7fc30d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuard.java @@ -0,0 +1,46 @@ +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.GameSessionControlPlaneServiceGrpc; + +/** Exact method-local Entity Management workload authorization for published owner readback. */ +public final class PublishedRealmAdmissionOwnerReadWorkloadGuard { + private static final String METHOD_NAME = + "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead"; + private static final String ENTITY_MANAGEMENT_SERVICE = "entity-management-service"; + + private final String trustedNamespace; + + public PublishedRealmAdmissionOwnerReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireEntityManagementOwnerReadCaller() { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (!METHOD_NAME.equals( + GameSessionControlPlaneServiceGrpc.getGetPublishedRealmAdmissionOwnerReadMethod() + .getFullMethodName()) + || trustedNamespace == null + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peerIdentity == null + || !ENTITY_MANAGEMENT_SERVICE.equals(peerIdentity.service()) + || !trustedNamespace.equals(peerIdentity.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + ENTITY_MANAGEMENT_SERVICE) + .equals(peerIdentity.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Published realm admission owner read requires the authenticated Entity Management workload peer identity"); + } + } + + public void requireConfiguredTargetNamespace(String targetNamespace) { + if (trustedNamespace == null + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Published realm admission owner read requires the configured target namespace"); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java new file mode 100644 index 0000000000..af9499cc19 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java @@ -0,0 +1,306 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.security.SessionContext; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadProof; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadService; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.PublishedRealmAdmissionAttemptStatus; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmAdmissionOwnerReadGrpcServiceTest { + private static final String NAMESPACE = "gameplay"; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_STATE_NAMESPACE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID ATTEMPT_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String REQUEST_ID = "88888888-8888-4888-8888-888888888888"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final long GAME_SESSION_TENANT_ID = 70123L; + private static final long PUBLISHED_VERSION_ID = 44L; + private static final long CATALOG_REVISION = 8L; + private static final long POINTER_VERSION = 1L; + private static final long POINTER_AUDIT_ID = 601L; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final PublishedRealmAdmissionOwnerReadService ownerReadService = + mock(PublishedRealmAdmissionOwnerReadService.class); + private GameSessionControlPlaneGrpcService grpcService; + + @BeforeEach + void setUp() { + SessionContext.clear(); + grpcService = + new GameSessionControlPlaneGrpcService( + null, null, null, null, null, null, new SimpleMeterRegistry()); + grpcService.configurePublishedRealmAdmissionOwnerReadBoundary(ownerReadService, NAMESPACE); + } + + @AfterEach + void tearDown() { + SessionContext.clear(); + } + + @Test + void returnsTheCompleteTypedOwnerCompositionForTheExactRequest() { + PublishedRealmAdmissionOwnerReadProof proof = proof(POINTER_VERSION); + when(ownerReadService.read(any(PublishedRealmAdmissionOwnerReadRequest.class))) + .thenReturn(proof); + CapturingObserver response = + new CapturingObserver<>(); + + runAsEntityManagementPeer( + () -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(response))); + + GetPublishedRealmAdmissionOwnerReadResponse result = response.value; + assertThat(response.failure).isNull(); + assertThat(result).isNotNull(); + assertThat(result.getProof().getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(result.getProof().getCanonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID.toString()); + assertThat(result.getProof().getGameSessionTenantId()) + .isEqualTo(Long.toString(GAME_SESSION_TENANT_ID)); + assertThat(result.getProof().getCatalogRevision()).isEqualTo(CATALOG_REVISION); + assertThat(result.getProof().getExpectedPointerVersion()).isEqualTo(POINTER_VERSION); + assertThat(result.getProof().getRealmId()).isEqualTo(REALM_ID.toString()); + assertThat(result.getProof().getPlayableStateNamespaceId()) + .isEqualTo(PLAYABLE_STATE_NAMESPACE_ID.toString()); + assertThat(result.getProof().getPublishedPolicySet().getPolicyCount()).isEqualTo(1); + assertThat(result.getProof().getPublishedPolicySet().getPolicies(0).getSourceGameRowId()) + .isEqualTo(91L); + assertThat(result.getProof().getPublishedPolicySet().getPolicies(0).getPolicyDigest()) + .isEqualTo(proof.selectedPolicyEvidence().policyDigest()); + assertThat(result.getProof().getSelectedPolicyEvidence().getWorldSlug()).isEqualTo("earth"); + assertThat(result.getProof().getGameInstanceId()).isEqualTo("93"); + assertThat(result.getProof().getPublishedVersionId()) + .isEqualTo(Long.toString(PUBLISHED_VERSION_ID)); + assertThat(result.getProof().getActiveLifecycleEpoch()).isEqualTo(12L); + assertThat(result.getProof().getGameTemplateId()).isEqualTo("55"); + assertThat(result.getProof().getLaunchDescriptorId()).isEqualTo("launch-earth-v44"); + assertThat(result.getProof().getReleaseBundleId()).isEqualTo("810"); + assertThat(result.getProof().getPublishedReleaseBundleRef()).isEqualTo("world-release-ref"); + assertThat(result.getProof().getVersionStateEpoch()).isEqualTo(6L); + assertThat(result.getProof().getInitialAdmissionRequestId()).isEqualTo(REQUEST_ID); + assertThat(result.getProof().getRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(result.getProof().getInitialAdmissionAttemptId()).isEqualTo(ATTEMPT_ID.toString()); + assertThat(result.getProof().getPointerAuditId()).isEqualTo(Long.toString(POINTER_AUDIT_ID)); + assertThat(result.getProof().getInitialAdmissionAttemptStatus()) + .isEqualTo( + PublishedRealmAdmissionAttemptStatus + .PUBLISHED_REALM_ADMISSION_ATTEMPT_STATUS_COMMITTED); + assertThat(result.getProof().getPointerAuditRequestId()).isEqualTo(REQUEST_ID); + assertThat(result.getProof().getPointerAuditRequestDigest()).isEqualTo(REQUEST_DIGEST); + verify(ownerReadService) + .read( + new PublishedRealmAdmissionOwnerReadRequest( + NAMESPACE, + CANONICAL_TENANT_ID, + GAME_SESSION_TENANT_ID, + "earth", + "main", + CATALOG_REVISION, + POINTER_VERSION)); + } + + @Test + void rejectsMalformedOrNonCanonicalTargetWithoutCallingOwnerAuthority() { + CapturingObserver response = + new CapturingObserver<>(); + GetPublishedRealmAdmissionOwnerReadRequest malformed = + request().toBuilder().setGameSessionTenantId("070123").build(); + + runAsEntityManagementPeer( + () -> grpcService.getPublishedRealmAdmissionOwnerRead(malformed, capture(response))); + + assertThat(response.value).isNull(); + assertThat(Status.fromThrowable(response.failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(ownerReadService); + } + + @Test + void rejectsMismatchedOrUnavailableOwnerEvidenceWithoutReturningPartialProof() { + when(ownerReadService.read(any(PublishedRealmAdmissionOwnerReadRequest.class))) + .thenReturn(proof(2L)); + CapturingObserver response = + new CapturingObserver<>(); + + runAsEntityManagementPeer( + () -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(response))); + + assertThat(response.value).isNull(); + assertThat(Status.fromThrowable(response.failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + void rejectsWrongPeerAndMissingOwnerDependencyWithoutReturningProof() { + CapturingObserver denied = + new CapturingObserver<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + NAMESPACE, + "world-management-service")) + .run(() -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(denied))); + assertThat(denied.value).isNull(); + assertThat(Status.fromThrowable(denied.failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + CapturingObserver wrongTarget = + new CapturingObserver<>(); + runAsEntityManagementPeer( + () -> + grpcService.getPublishedRealmAdmissionOwnerRead( + request().toBuilder().setTargetNamespace("other-namespace").build(), + capture(wrongTarget))); + assertThat(wrongTarget.value).isNull(); + assertThat(Status.fromThrowable(wrongTarget.failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(ownerReadService); + + grpcService.configurePublishedRealmAdmissionOwnerReadBoundary(null, NAMESPACE); + CapturingObserver unavailable = + new CapturingObserver<>(); + runAsEntityManagementPeer( + () -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(unavailable))); + assertThat(unavailable.value).isNull(); + assertThat(Status.fromThrowable(unavailable.failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } + + private static StreamObserver capture( + CapturingObserver response) { + return response; + } + + private static final class CapturingObserver implements StreamObserver { + private T value; + private Throwable failure; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable throwable) { + failure = throwable; + } + + @Override + public void onCompleted() {} + } + + private static GetPublishedRealmAdmissionOwnerReadRequest request() { + return GetPublishedRealmAdmissionOwnerReadRequest.newBuilder() + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setGameSessionTenantId(Long.toString(GAME_SESSION_TENANT_ID)) + .setWorldSlug("earth") + .setRealmSlug("main") + .setExpectedCatalogRevision(CATALOG_REVISION) + .setExpectedPointerVersion(POINTER_VERSION) + .build(); + } + + private static PublishedRealmAdmissionOwnerReadProof proof(long pointerVersion) { + String workflow = "publish:published-admission-owner-read-test"; + String manifest = "manifest-published-admission-owner-read-test"; + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, PUBLISHED_VERSION_ID, workflow, manifest, JSON); + String policyJson = + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + PublishedRealmEntryPolicyEvidence selected = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + CANONICAL_TENANT_ID, + "RETAINED_GAME_V29", + 91L, + "gd-tenant-91", + PUBLISHED_VERSION_ID, + 3, + 301L, + releaseIdentity, + workflow, + manifest, + RealmEntryPolicy.parse(policyJson, JSON), + JSON); + PublishedRealmEntryPolicySetEvidence policySet = + PublishedRealmEntryPolicySetEvidence.create( + CANONICAL_TENANT_ID, + PUBLISHED_VERSION_ID, + 3, + releaseIdentity, + workflow, + manifest, + List.of(selected), + JSON); + return new PublishedRealmAdmissionOwnerReadProof( + GAME_SESSION_TENANT_ID, + CANONICAL_TENANT_ID, + 91L, + "gd-tenant-91", + "RETAINED_GAME_V29", + policySet, + selected, + CATALOG_REVISION, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + PLAYABLE_STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + pointerVersion, + 93L, + PUBLISHED_VERSION_ID, + 12L, + 55L, + "launch-earth-v44", + 810L, + "world-release-ref", + 6L, + REQUEST_ID, + REQUEST_DIGEST, + ATTEMPT_ID, + POINTER_AUDIT_ID); + } + + private static void runAsEntityManagementPeer(Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + ENTITY_SERVICE, + NAMESPACE, + ENTITY_SERVICE)) + .run(action); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java new file mode 100644 index 0000000000..f27415c606 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java @@ -0,0 +1,101 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class PublishedRealmAdmissionOwnerReadWorkloadGuardTest { + private static final String NAMESPACE = "gameplay"; + private static final String ENTITY_SERVICE = "entity-management-service"; + + @AfterEach + void tearDown() { + SessionContext.clear(); + } + + @Test + void acceptsOnlyTheConfiguredEntityManagementWorkloadPeer() { + PublishedRealmAdmissionOwnerReadWorkloadGuard guard = + new PublishedRealmAdmissionOwnerReadWorkloadGuard(NAMESPACE); + + assertThatCode( + () -> + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> { + guard.requireEntityManagementOwnerReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) + .doesNotThrowAnyException(); + } + + @Test + void rejectsOtherWorkloadsNamespacesMissingPeersAndInvalidConfiguration() { + PublishedRealmAdmissionOwnerReadWorkloadGuard guard = + new PublishedRealmAdmissionOwnerReadWorkloadGuard(NAMESPACE); + + assertDenied( + () -> + runAsPeer( + "world-management-service", + NAMESPACE, + guard::requireEntityManagementOwnerReadCaller)); + assertDenied( + () -> + runAsPeer( + ENTITY_SERVICE, + "other-namespace", + guard::requireEntityManagementOwnerReadCaller)); + assertDenied(() -> guard.requireEntityManagementOwnerReadCaller()); + assertDenied( + () -> + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> guard.requireConfiguredTargetNamespace("other-namespace"))); + assertDenied( + () -> + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> + new PublishedRealmAdmissionOwnerReadWorkloadGuard("Invalid_Namespace") + .requireEntityManagementOwnerReadCaller())); + } + + @Test + void rejectsAuthenticatedCallerContextEvenWithTheExpectedPeerCertificate() { + PublishedRealmAdmissionOwnerReadWorkloadGuard guard = + new PublishedRealmAdmissionOwnerReadWorkloadGuard(NAMESPACE); + SessionContext.setContext("account", List.of("player"), Map.of()); + + assertDenied( + () -> + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + guard::requireEntityManagementOwnerReadCaller)); + } + + private static void assertDenied(Runnable action) { + assertThatThrownBy(() -> action.run()).isInstanceOf(AdminAuthorizationException.class); + } + + private static void runAsPeer(String service, String namespace, Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service)) + .run(action); + } +} From 0d324defad83ed545cd7f37d69bd8547de61b106 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:30:35 +1300 Subject: [PATCH 082/105] test: keep Account runtime fixtures on canonical UUID carriers --- .../test/AccountRuntimeStubServerTest.java | 85 +++++++++++++++++-- .../test/AccountRuntimeStubServer.java | 50 ++++++++++- ...ionAccountCrossServiceIntegrationTest.java | 42 ++++++--- 3 files changed, 155 insertions(+), 22 deletions(-) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index abc3e59a76..39f0649066 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -31,7 +31,7 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .setPassword("password") .build()) .getAccountId()) - .isEqualTo("7"); + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); server.setMembershipExists(false); @@ -58,11 +58,16 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); + server.mapAccountId("demo@example.com", 7L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); AccountProfileJson initialProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(initialProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -71,7 +76,7 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(accountUuid) .setProfileJson( """ {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} @@ -83,7 +88,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { AccountProfileJson updatedProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(updatedProfile.presenceVisibilityPolicy()).isEqualTo("PRIVATE"); @@ -101,12 +109,14 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); + server.setDefaultAccountId(7L); + String accountUuid = authenticate(stub); assertThat( stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(accountUuid) .setProfileJson( """ {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} @@ -116,11 +126,21 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { .isTrue(); server.resetRuntimeState(); + var deniedAfterReset = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build()); + assertThat(deniedAfterReset.getProfileJson()).isEmpty(); + assertThat(deniedAfterReset.getError().getCode()).isEqualTo("ACCOUNT_NOT_FOUND"); + + accountUuid = authenticate(stub); AccountProfileJson resetProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(resetProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -129,4 +149,57 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { } } } + + @Test + void profileReadAndWriteRejectUnknownAndMalformedAccountUuids() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + String unregisteredUuid = AccountRuntimeStubServer.accountUuidForTestFixture(9L); + + for (String accountId : new String[] {unregisteredUuid, "9", "not-a-uuid"}) { + var read = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountId).build()); + assertThat(read.getProfileJson()).isEmpty(); + assertThat(read.getError().getCode()).isEqualTo("ACCOUNT_NOT_FOUND"); + + var write = + stub.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountId) + .setProfileJson( + "{\"displayName\":\"Changed\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build()); + assertThat(write.getSuccess()).isFalse(); + assertThat(write.getError().getCode()).isEqualTo("ACCOUNT_NOT_FOUND"); + } + + server.setDefaultAccountId(9L); + String authenticatedUuid = authenticate(stub); + AccountProfileJson profile = + AccountProfileJson.parse( + stub.getProfile( + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(authenticatedUuid) + .build()) + .getProfileJson(), + "FRIENDS_ONLY"); + assertThat(profile.displayName()).isEqualTo("Demo-9"); + assertThat(profile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); + } finally { + channel.shutdownNow(); + } + } + } + + private static String authenticate(AccountServiceGrpc.AccountServiceBlockingStub stub) { + return stub.authenticate(AuthenticateRequest.newBuilder().setEmail("demo@example.com").build()) + .getAccountId(); + } } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 4bb8d1f7a5..cf165ca8b3 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -4,6 +4,7 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; import java.util.Map; @@ -61,6 +62,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final AtomicLong defaultAccountId = new AtomicLong(1L); private final AtomicLong nextConnectScopeId = new AtomicLong(1L); private final Map accountIdsByEmail = new ConcurrentHashMap<>(); + private final Map accountIdsByUuid = new ConcurrentHashMap<>(); private final Map profilesByAccountId = new ConcurrentHashMap<>(); private final Map connectScopesById = new ConcurrentHashMap<>(); @@ -84,8 +86,19 @@ public void setDefaultAccountId(long accountId) { defaultAccountId.set(accountId); } + /** Returns the stable UUID used by this fake for a numeric test account key. */ + public static String accountUuidForTestFixture(long accountId) { + if (accountId <= 0L) { + throw new IllegalArgumentException("accountId must be positive"); + } + return UUID.nameUUIDFromBytes( + ("firemud-test-account:" + accountId).getBytes(StandardCharsets.UTF_8)) + .toString(); + } + public void mapAccountId(String email, long accountId) { accountIdsByEmail.put(EmailCanonicalization.normalize(email), accountId); + accountIdsByUuid.put(accountUuidForTestFixture(accountId), accountId); } public void setPresenceVisibilityPolicy(long accountId, String visibilityPolicy) { @@ -137,6 +150,7 @@ public void resetRuntimeState() { allowPublicJoin.set(true); realmAccessGranted.set(true); profilesByAccountId.clear(); + accountIdsByUuid.clear(); connectScopesById.clear(); } @@ -153,9 +167,11 @@ public void authenticate( String canonicalEmail = EmailCanonicalization.normalize(request.getEmail()); long accountId = accountIdsByEmail.getOrDefault(canonicalEmail, defaultAccountId.get()); profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); + String accountUuid = accountUuidForTestFixture(accountId); + accountIdsByUuid.put(accountUuid, accountId); responseObserver.onNext( AuthenticateResponse.newBuilder() - .setAccountId(Long.toString(accountId)) + .setAccountId(accountUuid) .setAuthToken("stub-token-" + accountId) .build()); responseObserver.onCompleted(); @@ -338,7 +354,15 @@ public void joinPublicProductionMembership( @Override public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { - long accountId = Long.parseLong(request.getAccountId()); + Long accountId = resolveRegisteredAccountId(request.getAccountId()); + if (accountId == null) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("ACCOUNT_NOT_FOUND")) + .build()); + responseObserver.onCompleted(); + return; + } StubProfile profile = profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); try { responseObserver.onNext( @@ -359,7 +383,15 @@ public void getProfile( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { - long accountId = Long.parseLong(request.getAccountId()); + Long accountId = resolveRegisteredAccountId(request.getAccountId()); + if (accountId == null) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("ACCOUNT_NOT_FOUND")) + .build()); + responseObserver.onCompleted(); + return; + } AccountProfileJson profile = AccountProfileJson.parse(request.getProfileJson(), StubProfile.DEFAULT_VISIBILITY_POLICY); StubProfile existing = @@ -380,6 +412,18 @@ public void updateProfile( } } + private Long resolveRegisteredAccountId(String accountUuid) { + try { + UUID parsed = UUID.fromString(accountUuid); + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(accountUuid)) { + return null; + } + return accountIdsByUuid.get(accountUuid); + } catch (IllegalArgumentException ex) { + return null; + } + } + @Override public void close() { server.shutdownNow(); diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index e31cced2fc..26cedaf6f0 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.net.URI; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Objects; import net.firedevops.firemud.cache.ScreenBufferService; @@ -126,6 +127,18 @@ static synchronized void stopTestServices() { void clearSharedRuntimeState() throws Exception { ensureTestServicesStarted(); STACK.freshGameplayBaseline(TENANT_ID, DEFAULT_GAME_INSTANCE_ID, ACCOUNT_ID, 7L, ACCOUNT_ID); + entityStub() + .setCharacters( + List.of("Emberline", "Sora", "Nyx").stream() + .map(ChatTestFixtures::characterByName) + .map( + character -> + character.toBuilder() + .setAccountId( + AccountRuntimeStubServer.accountUuidForTestFixture( + Long.parseLong(character.getAccountId()))) + .build()) + .toList()); } @Test @@ -789,19 +802,22 @@ private static void awaitGameSessionReadiness(int gameSessionPort) { private void seedLiveTargetSession() { STACK.seedLiveSession( - 90210L, - TENANT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - "sora@example.com", - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - "Sora", - DEMO_WORLD_INSTANCE_ID, - LookTestFixtures.ROOM_ID, - "target-jwt", - "demo", - "production", - 1L, - "SHARED"); + new SessionContext( + 90210L, + TENANT_ID, + AccountRuntimeStubServer.accountUuidForTestFixture(SORA_ACCOUNT_ID), + "sora@example.com", + SORA_ACCOUNT_ID, + "Sora", + DEMO_WORLD_INSTANCE_ID, + LookTestFixtures.ROOM_ID, + "target-jwt", + null, + DEMO_WORLD_INSTANCE_ID, + "demo", + "production", + 1L, + "SHARED")); } private static GatewayHolder startGateway(int gameSessionPort) { From 1ed62f75988fceaee252711004dc18a7acc45718 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:31:20 +1300 Subject: [PATCH 083/105] fix: close published realm owner-read and retention review gaps --- .../game-design-service/README.md | 2 +- .../game-design-service/api-contracts.md | 4 +- .../game-session-service/api-contracts.md | 6 +- ...ame-authoring-publishing-and-activation.md | 6 +- ...nTenantAssociationPayloadRetentionJob.java | 4 - .../PublishedReleaseBundleServiceImpl.java | 56 ++- .../impl/TenantIdentityGrpcService.java | 26 +- .../V31__published_realm_entry_policy.sql | 2 +- ...tAssociationRepositoryIntegrationTest.java | 24 +- ...nantIdentityRepositoryIntegrationTest.java | 5 +- ...emptServiceTransactionIntegrationTest.java | 28 ++ .../GameSessionTenantAssociationGrpcTest.java | 33 +- ...PublishedReleaseBundleServiceImplTest.java | 150 +++++- .../impl/TenantIdentityGrpcServiceTest.java | 14 + ...InitialAdmissionBindCatalogRepository.java | 2 +- ...sionRetainedTenantPayloadRetentionJob.java | 5 + .../PublishedRealmCatalogOwnerService.java | 6 - .../GameSessionControlPlaneGrpcService.java | 12 +- .../src/main/resources/application.yml | 2 + ...V13__retained_tenant_payload_retention.sql | 2 +- ...tAssociationRepositoryIntegrationTest.java | 4 +- ...RealmCatalogRepositoryIntegrationTest.java | 111 ++++- ...lAdmissionBindPostgresIntegrationTest.java | 31 +- ...itialAdmissionOwnerReadAuthWiringTest.java | 440 ++++++++++++++++++ ...ealmAdmissionOwnerReadGrpcServiceTest.java | 5 +- ...lmAdmissionOwnerReadWorkloadGuardTest.java | 11 +- 26 files changed, 886 insertions(+), 105 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 4b521a52d0..ccc0808efa 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -16,7 +16,7 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved, because `GameAssetServiceImpl` uses `MultipartFile.getBytes()` without matching limits in `AssetStoreProperties`; upload admission and resource-safety readiness remain blocked. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. Publish/export later writes version-prefix objects and a manifest through the private object-store endpoint; target private-candidate/content-addressed publication and approved public `/assets/**` delivery remain unimplemented. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). -The owner-local tenant UUID read and the closed-v1 `REALM_ENTRY_POLICY` publication producer are implemented. The producer freezes policy revisions with full-version release evidence, rejecting tenant/version `realmSlug` duplicates and sets without exactly one visible public-production policy before mutation. Descriptor/template production and composition with Game Session's live catalog, pointer, namespace/scope, and Entity actor-entry paths remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Local PostgreSQL migration/readback execution remains unproved; no Docker or PostgreSQL runtime validation is claimed. See the exact API boundary in [API Contracts](./api-contracts.md#published-realm-entry-policy-owner-read) and the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). +The owner-local tenant UUID read and the closed-v1 `REALM_ENTRY_POLICY` publication producer are implemented. Because `SaveRevision` appends policy history, publication now resolves each realm selector to its effective latest revision, so editing an existing policy does not create duplicate published rows or let older visibility flags affect the current publication. Full-version publication with no authored realm-policy revisions remains permitted for legacy behavior and provides no policy proof. Descriptor/template production and composition with Game Session's live catalog, pointer, namespace/scope, and Entity actor-entry paths remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused producer and schema-capacity cases are added but remain unrun; local PostgreSQL migration/readback execution remains unproved. See the exact API boundary in [API Contracts](./api-contracts.md#published-realm-entry-policy-owner-read) and the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). ## Responsibilities diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index e0f30a878b..8633b000ae 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -35,7 +35,7 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and the first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are live in the current proto/service path. Full-version publish has a Temporal `publish` workflow path when Temporal is enabled. Its four owner-to-owner digest reads now use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding; the authorization seam no longer depends on an empty-role JWT or an Automation admin-role fallback. End-to-end full-version publication remains blocked: the Game Logic owner digest fails closed because owner-local manifest and provenance for the version's rule inputs are absent, Automation's full-version content mapping remains broader than the requested version, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see the explicit status below and [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). When the Temporal beans are disabled or absent, the synchronous `PublishVersion` path returns success only after its local terminal publish gates, release-attestation commit, Version finalization, and artifact publication complete; ordinary validation/export failures are surfaced explicitly. After a downstream exception, exact readback determines the outcome: if it proves that no release bundle or artifact exists and the candidate Version remains `DRAFT`, the service commits a terminal `FAILED` attempt under the game-row lock and retains the candidate Version row; best-effort object-store cleanup can still be uncertain. Complete release evidence is reconciled to success, while partial evidence remains pending for reconciliation. Restart-independent workflow durability and workflow runtime metadata are target/conditional properties of the Temporal path when its authorization, worker, and readback proofs are live; they are not properties of this synchronous fallback. `UploadPluginBundle` now parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` publication row. The live intake currently selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; current proto/storage also expose no append-only signature-evidence ledger or append RPC. `PublishPluginVersion` validates the uploaded bundle and requires a published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and makes a best-effort attempt to supersede older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; the target contract requires the dedicated Game Logic-owned ability-schema attestation for the same base version, so exact ability-schema compatibility remains unproved until the release bundle and validator converge. Explicit design-time revoke transitions and a durable append-only plugin publication-event read surface are live too through `RevokePluginVersion` and `ListPluginVersionStatusEvents`; the main remaining follow-through includes the dedicated ability-schema proof and broader activation-time alias/binding validation in owning runtime services. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for any creator mutation class. -Game Design now issues a canonical tenant UUID on its owner `game` row and serves the authenticated owner-local `ResolveRuntimeTenantIdentity` read. Migration V29 records exact source-row/key provenance for valid retained keys and leaves blank or out-of-bounds retained keys quarantined without a canonical identity; row identity and provenance are immutable after issuance. This evidence is only a tenant-owner read: it does not publish realm-entry policy or resolve a realm descriptor/template, current realm pointer, playable-state namespace/scope, or actor admission. Reported focused proof: compilation and `generateJooq` succeeded, `TenantIdentityGrpcServiceTest` passed 6/6, `TenantIdentityGrpcAuthWiringTest` passed 3/3, and `RuntimeTenantIdentityEvidenceTest` passed 2/2; the PostgreSQL integration test compiled, but PostgreSQL execution remains unproved because Docker was unavailable. +Game Design now issues a canonical tenant UUID on its owner `game` row and serves the authenticated owner-local `ResolveRuntimeTenantIdentity` read. Migration V29 records exact source-row/key provenance for valid retained keys and leaves blank or out-of-bounds retained keys quarantined without a canonical identity; row identity and provenance are immutable after issuance. This evidence is only a tenant-owner read: it does not publish realm-entry policy or resolve a realm descriptor/template, current realm pointer, playable-state namespace/scope, or actor admission. Reported focused proof covers compilation, `generateJooq`, owner-read service behavior, authentication wiring, and the shared runtime tenant-identity evidence checks. The PostgreSQL integration test compiled, but PostgreSQL execution remains unproved because Docker was unavailable. Migration V30 added immutable namespace-scoped Game Design association claims; forward migration V32 separates signed approval labels, signature, and source-linked digests into an erasable owner-local payload table. Closed evidence schema 2 binds the exact Game Session source capture time, projection digest, and full snapshot digest. New applies reject source captures at or beyond 30 days using database time; retries do not renew expiry. A bounded owner scheduler deletes up to 100 expired terminal approval payloads per pass; no asynchronous approval-payload consumer or second derived copy exists in this inactive path, while immutable namespace/UUID/private-key/provenance claims remain to prevent reassignment. `TenantIdentityService.ResolveLegacyGameSessionTenantAssociation` remains a same-namespace Game Session mTLS receipt read; after raw expiry it fails closed and is not a public approval route, key generator, or runtime catalog/admission authority. The exact-scope hold audit row references the immutable operation claim rather than the erasable payload, so payload expiry cannot cascade away hold/release evidence. This is separate purpose-bound safety evidence, not an extension of RAW payload retention; ADR 0050 and ADR 0163 require its own finite retention, export/erasure treatment, and access policy. That schedule and a trusted authenticated owner authorization policy are not yet implemented, so hold create/release remain non-operational; supplied principal text or generic DB write access is not accepted. PostgreSQL fixtures seed hold state only to prove owner cleanup/reference behavior, not to prove authorization. Restore must apply owner erasure/cleanup before raw reads; no backup in-place edit or restore traffic-gate proof is claimed. PostgreSQL migration/readback execution remains unproved locally while Docker is disabled. @@ -121,7 +121,7 @@ Bounded transport outcomes are: `NOT_FOUND` when no owner row exists for the exa `SaveRevision` accepts `revisionKind=REALM_ENTRY_POLICY` only when `data` is one closed v1 JSON object containing exactly `schemaVersion`, `worldSlug`, `worldDisplayName`, `realmSlug`, `realmDisplayName`, `visible`, `publicProduction`, `stateScope`, and `entryPolicy`. The schema version is the integer `1`; every listed field is required and typed, booleans have no defaults, slugs are canonical lower-case ASCII selectors of at most 64 characters, and display names are trimmed, control-free text of at most 128 Unicode code points. The UTF-8 JSON document is bounded to 4096 bytes. Unknown fields, duplicate JSON keys, malformed values, and unsupported entry policies fail with `INVALID_ARGUMENT`. V1 accepts only `entryPolicy=PRESEEDED_ONLY`, with `stateScope=SHARED|ISOLATED`; descriptor and template fields are not valid for this policy. Other policy kinds remain unsupported until their artifacts are implemented. Realm policy revisions require a full DRAFT version and inherit their tenant/version from the existing revision transaction. The normal published-version immutability rule then prevents later edits. -When a full-version `PublishedReleaseBundle` is created, Game Design freezes every matching policy revision in the same transaction as the bundle, in separate insert-only policy rows. Before any publication mutation, the write rechecks each exact source revision's tenant, version, kind, and positive owner-local revision ID; rejects duplicate `(worldSlug, realmSlug)` selectors and repeated `realmSlug` values across worlds; and requires exactly one policy with both `visible=true` and `publicProduction=true`. It then resolves the canonical tenant UUID, source game row, retained tenant key, and provenance kind through the exact Game Design `game` row, and allocates a separate UUID for each persisted policy. It does not guess or translate tenant identifiers. Policy JSON is stored in RFC 8785 canonical form. `release_bundle_identity` is `sha256:` over RFC 8785 canonical JSON containing the canonical tenant UUID, exact version ID, publish workflow ID, and manifest hash. `policy_digest` is `sha256:` over RFC 8785 canonical evidence binding the policy UUID, canonical tenant UUID and source provenance, exact version ID/number, source revision ID, release-bundle identity and its workflow/manifest values, and the canonical policy object. Database constraints reject duplicate selectors and repeated tenant/version `realmSlug` values; update and delete attempts against frozen policy rows fail. +When a full-version `PublishedReleaseBundle` is created, Game Design validates every matching source revision's exact tenant, version, kind, and positive owner-local revision ID, then normalizes append-only history to the highest persisted revision ID for each `(worldSlug, realmSlug)` selector. Older revisions remain in Game Design's owner-local history; normalization does not delete or rewrite them. Equal revision IDs with conflicting source data fail closed. Only this effective policy set is frozen in the same transaction as the bundle, in separate insert-only policy rows; the published-set bound, tenant/version-wide `realmSlug` uniqueness across worlds, and exactly-one `visible=true && publicProduction=true` cardinality apply to those effective rows. A superseded revision does not add another published policy or affect that cardinality. Game Design then resolves the canonical tenant UUID, source game row, retained tenant key, and provenance kind through the exact Game Design `game` row, and allocates a separate UUID for each persisted policy. It does not guess or translate tenant identifiers. Policy JSON is stored in RFC 8785 canonical form. `release_bundle_identity` is `sha256:` over RFC 8785 canonical JSON containing the canonical tenant UUID, exact version ID, publish workflow ID, and manifest hash. `policy_digest` is `sha256:` over RFC 8785 canonical evidence binding the policy UUID, canonical tenant UUID and source provenance, exact version ID/number, source revision ID, release-bundle identity and its workflow/manifest values, and the canonical policy object. Database constraints reject duplicate selectors and repeated tenant/version `realmSlug` values; update and delete attempts against frozen policy rows fail. Publication without a `REALM_ENTRY_POLICY` revision remains valid for unrelated legacy publication behavior, but creates no realm-policy evidence. `ResolvePublishedRealmEntryPolicy` never infers policy from a release bundle or from current mutable revision data. It accepts exactly a canonical nonnil `canonical_tenant_id`, positive `version_id`, and the exact canonical `world_slug`/`realm_slug` selector pair. This selector read proves only that row; it is not a complete catalog, addressability-cardinality, or admission proof. Only the verified same-namespace Game Session workload may call it; the mTLS listener remains required, and the full method name is exempted from bearer-token validation in both base and production configuration. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 343003e95f..ca7087ae05 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -14,9 +14,11 @@ Realm-catalog identity status: Game Session pointer and audit rows persist a sep V12 retains the immutable tenant-association claim; V13 separates its account-linked approval and raw-snapshot payload into an owner-local erasable table. The candidate remains explicitly unwired. Snapshot schema 4 binds the authoritative database capture time; signed approval schema 2 binds that same capture time, the canonical projection digest, and the complete snapshot digest. Registration recaptures under the owner fence, compares the current projection, and verifies the signed full digest after rebinding only the unchanged rows to the original source capture time. Missing/ambiguous legacy capture evidence fails closed and requires new capture; approval, consume, and retry do not renew the 30-day lifetime. `owner_account_id` remains the actual required numeric field; no canonical Account UUID is inferred. The mapping is identity evidence only, not a pointer seed, admission result, membership, actor promotion, or `PLAY` authorization. Focused proof and PostgreSQL limits are recorded below; raw backup edits and restore-gate proof are not claimed. -Published realm-policy receiving/catalog preparation: the lazy internal [catalog owner](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java) reads the committed minimal Game Session tenant association and complete Game Design policy set before its local transaction, rejects source-provenance mismatches, and freezes the exact owner evidence into an immutable [catalog snapshot](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java) using the local private tenant ID rather than the Game Design source row ID. Durable realm identity is canonical tenant plus tenant-wide unique `realmSlug`; proven `SHARED` entries retain a stable opaque playable-state namespace, and policy/display-only changes advance `catalogRevision` without changing pointer version or old snapshot reads. Lifecycle resolution is selected-entry scoped: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation exposes no namespace or initial-bind read, while an unrelated unresolved private entry does not block a proven shared-entry read. An explicit internal [published bind coordinator](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java) selects an exact V14 snapshot/entry, then cross-checks authored launch and World lifecycle readback before persisting a V14-linked intent and acquiring/attaching the World hold; its GS transaction commits pointer, audit, and outcome together. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID because the existing launch API uses one numeric ID for both roles; a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is validated against authored launch readback and stored separately from the V14 release digest; no identity translation is inferred. New attempts retain the configured target namespace, canonical tenant UUID, retained local GS tenant ID, selected realm/namespace/revision, published version/release evidence, and exact local launch tuple; V9 fixture attempts remain separately identified historical evidence. The new composition and focused proof have not yet been run in this worktree. It does not establish actor validation, roster cardinality, strict Account `JOIN`, or `PLAY` admission. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), the [policy client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and focused [client](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) and [owner-service tests](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). +Published realm-policy receiving/catalog preparation: the lazy internal [catalog owner](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java) reads the committed minimal Game Session tenant association and complete Game Design policy set before its local transaction, rejects source-provenance mismatches, and freezes the exact owner evidence into an immutable [catalog snapshot](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java) using the local private tenant ID rather than the Game Design source row ID. Durable realm identity is canonical tenant plus tenant-wide unique `realmSlug`; proven `SHARED` entries retain a stable opaque playable-state namespace, and policy/display-only changes advance `catalogRevision` without changing pointer version or old snapshot reads. Lifecycle resolution is selected-entry scoped: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation exposes no namespace or initial-bind read, while an unrelated unresolved private entry does not block a proven shared-entry read. An explicit internal [published bind coordinator](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java) selects an exact V14 snapshot/entry, then cross-checks authored launch and World lifecycle readback before persisting a V14-linked intent and acquiring/attaching the World hold; its GS transaction commits pointer, audit, and outcome together. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID because the existing launch API uses one numeric ID for both roles; a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is validated against authored launch readback and stored separately from the V14 release digest; no identity translation is inferred. New attempts retain the configured target namespace, canonical tenant UUID, retained local GS tenant ID, selected realm/namespace/revision, published version/release evidence, and exact local launch tuple; V9 fixture attempts remain separately identified historical evidence. Focused Game Session receiver/guard and Game Design identity-owner tests have passed; the shared-interceptor auth-wiring proof remains pending. Cross-service PostgreSQL race/restart proof and live Compose execution remain unestablished; see the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md). It does not establish actor validation, roster cardinality, strict Account `JOIN`, or `PLAY` admission. See the canonical [Game Design published policy owner contract](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), the [policy client](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java), and focused [client](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java) and [owner-service tests](../../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). -The internal `GameSessionControlPlaneService.GetPublishedRealmAdmissionOwnerRead` RPC returns this composed, point-in-time owner read to Entity Management. It requires the exact Entity Management SPIFFE peer URI in the configured workload namespace, a matching target namespace, and no authenticated caller context; it is not part of the player-facing `GameSessionService.GetAdmissionPointer` surface. Its typed response carries the complete Game Design policy-set/selected-policy evidence plus the validated unchanged pointer, published runtime tuple, committed initial-bind attempt identity/status/digest, and pointer-audit ID with its matching request identity/digest. The read confirms the existing first pointer bind only: it is not a fresh World `ACTIVE` observation or validation-through-commit admission gate. Malformed selectors fail with gRPC `INVALID_ARGUMENT`, unauthorized peers/targets with `PERMISSION_DENIED`, and mismatched, missing, or unavailable owner evidence with `UNAVAILABLE`; failures have no proof payload. The Entity client and focused receiver/guard validation remain pending and are not established by this receiving surface. +The internal `GameSessionControlPlaneService.GetPublishedRealmAdmissionOwnerRead` RPC returns this composed, point-in-time owner read to Entity Management. It requires the exact Entity Management SPIFFE peer URI in the configured workload namespace, a matching target namespace, and no authenticated caller context; it is not part of the player-facing `GameSessionService.GetAdmissionPointer` surface. Its typed response carries the complete Game Design policy-set/selected-policy evidence plus the validated unchanged pointer, published runtime tuple, committed initial-bind attempt identity/status/digest, and pointer-audit ID with its matching request identity/digest. The read confirms the existing first pointer bind only: it is not a fresh World `ACTIVE` observation or validation-through-commit admission gate. Malformed selectors fail with gRPC `INVALID_ARGUMENT`, unauthorized peers/targets with `PERMISSION_DENIED`, and mismatched, missing, or unavailable owner evidence with `UNAVAILABLE`; failures have no proof payload. The Entity client and end-to-end admission remain pending. + +`GetInitialAdmissionBindProof` and `GetPublishedRealmAdmissionOwnerRead` are exact workload-only exceptions to the shared `AuthTokenInterceptor` bearer-token check, configured under `firemud.auth.grpc.public-methods`. This legacy property name does not make either RPC publicly reachable: the Game Session gRPC listener requires mTLS, each handler enforces its exact World Management or Entity Management SPIFFE URI and configured namespace, and both reject authenticated caller context. Production configuration inherits these exact base entries while overriding unrelated gRPC settings; no wildcard exception is used, and other control-plane methods remain bearer-protected. This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: 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 49ea9f3778..162a74406b 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. -Game Design now issues an owner-local canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; issuance and source provenance are immutable. The closed-v1 `REALM_ENTRY_POLICY` owner producer accepts version-scoped revisions, freezes immutable policy rows transactionally with full-version release-bundle creation, and exposes same-namespace authenticated exact-row and bounded complete-set reads with owner-bound evidence. Publication preparation rejects repeated tenant/version `realmSlug` values across worlds and policy sets without exactly one visible public-production entry before persisting publication evidence. Local PostgreSQL migration/readback execution remains unproved; no Docker or PostgreSQL runtime validation is claimed. This producer and complete-set evidence do not establish current Game Session catalog validity, pointer/namespace/scope composition, descriptor/template identity, Entity actor admission, or actor creation/activation. Target semantics remain in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), and actor-entry behavior remains incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +Game Design issues a canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; issuance and source provenance are immutable. The closed-v1 `REALM_ENTRY_POLICY` producer accepts version-scoped revisions, freezes immutable policy rows transactionally with full-version release-bundle creation, and exposes same-namespace authenticated exact-row and bounded complete-set reads with owner-bound evidence. The canonical producer rules are in the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read); focused proof status and anchors are recorded under `AR-1.5` below. Local PostgreSQL migration/readback execution remains unproved. This producer and complete-set evidence do not establish current Game Session catalog validity, pointer/namespace/scope composition, descriptor/template identity, Entity actor admission, or actor creation/activation. Actor-entry behavior remains incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). The separate retained Game Session tenant-association prerequisite keeps immutable source-row/key/provenance and namespace/canonical/private-key claims while V32 moves signed approval labels, signature, and source-linked digests into an owner-local 30-day capture-expiring payload. V2 evidence binds the exact GS source capture time and both snapshot digests; retries do not renew expiry. Automatic bounded cleanup preserves terminal anti-reassignment rows. Hold audit references the immutable association claim, not erasable raw payload, and therefore survives payload cleanup. Under ADR 0050/0163 it is separate purpose-bound safety evidence requiring finite post-release retention/export/erasure policy; that schedule and a trusted authenticated owner policy are not implemented, so hold create/release remain fail-closed with no generic audit exemption. Test fixtures prove cleanup/reference behavior only, not authorization. Game Session's mapping-only internal read remains independent of expired/erased raw evidence. This prerequisite is not runtime catalog/admission authority and does not enable activation or public endpoints. Its focused validation and PostgreSQL/restore-proof limits are recorded in the owning service docs and [Player Access and Session](./player-access-and-session.md#current-status). @@ -54,7 +54,7 @@ These links add decision provenance only; they do not change existing implementa | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and typed generation mutation seams; LLM-assisted authoring, typed generation ingress, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and typed generation mutations exist. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. Accepted procedural-generation decisions now define one World-owned engine, request-bounded replay, bounded persistence, previewed replacement, and sparse/full-grid semantics; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.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) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.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) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: export, artifact-state, manifest-hashing, repair, and purge seams exist, but the required fail-closed version-scoped publication gate is not implemented. The `version_asset` mapping table and its Draft-version authoring path are absent; `AssetExportServiceImpl` exports every tenant asset, and publication does not prove that only mapped assets were selected. The release bundle also lacks canonical target-commit, manifest-schema, and applicable artifact-digest fields. Release readiness cannot be claimed until the mapping/authoring path and guard exist with focused proof. Normalized asset/history and derived-artifact substrates plus complete creator asset UX remain absent. Accepted asset/publication decisions now define content-addressed bytes, fail-closed attestation, and version-scoped publication; version-scoped asset mapping and complete release-bundle digest fields remain incomplete. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for current revision/version publication, the fail-closed publish gate, and happy-path release-bundle and participant-digest seams; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.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 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.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: revision/version publication and fail-closed gate seams exist, but participant tokens are synthetic, World emits schema 2 while the gate accepts schema 1, and the release bundle is still minimal, so actual same-commit attestation convergence is not established. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for current revision/version publication, the fail-closed publish gate, and happy-path release-bundle and participant-digest seams; this does not prove historical revision/version lineage. The published realm-policy producer and tenant-identity read are implemented; 42 focused producer, tenant-read, and association tests passed, including QueryTimeout mapping and effective-policy revision cases; jOOQ generation and integration-source compilation passed, while the PostgreSQL workflow-capacity case remains unexecuted, and PostgreSQL migration/readback remains unproved. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read); [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 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [TenantIdentityGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V29 canonical tenant identity](../../../services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql); [V31 published realm-entry policy](../../../services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishAttemptServiceTransactionIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java); [TenantIdentityGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java); [GameTenantIdentityRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.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: revision/version publication and fail-closed gate seams exist, but participant tokens are synthetic, World emits schema 2 while the gate accepts schema 1, and the release bundle is still minimal, so actual same-commit attestation convergence is not established. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `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. | @@ -182,7 +182,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the current participant observations and first World mutation handoff do not yet establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. The current implementation lacks the version-scoped asset mapping/authoring path and corresponding publication/export guard; purge and publication recovery also lack complete durable operation, CAS, and exact readback proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. -- Game Design now accepts the closed v1 `PRESEEDED_ONLY` realm policy through its version-scoped revision path, freezes exact source-revision and canonical-tenant provenance with full-version release-bundle creation, and exposes same-namespace Game Session selector and complete-set reads of immutable policy/version/digest evidence. Missing policy remains unavailable, and unrelated legacy publication without authored policy remains valid but supplies no policy proof. The complete-set read enforces its 128-row bound and exactly-one-visible-publicProduction rule; neither owner read activates runtime state or proves current catalog/pointer validity. Realm-authored actor entry remains incomplete: `PLAYER_CREATED` and `AUTO_PROVISIONED` artifacts are unsupported, and Game Session catalog, pointer, namespace, and scope ownership is not composed with Entity admission or creation. No `PLAY` readiness is established. +- Realm-authored runtime entry remains incomplete: Game Session has bounded catalog/first-bind composition, but source-aware launch, Entity actor admission/materialization, and end-to-end runtime proof remain unfinished; no `PLAY` readiness is established. The implemented producer/read boundary, proof status, and API/service anchors are maintained in the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), and [PublishedReleaseBundleServiceImpl](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java). - Normalized-template cutover phase is target-only: no tenant-scoped `GetTemplateReferencePhase` RPC, durable phase authority, or `BACKFILLING`/`VALIDATED`/`ENFORCED` consumer contract exists in the current slice; live launch checks only the per-template `ENFORCED`/`LEGACY` field. The target API and fail-before-launch behavior remain unimplemented and unproved. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. - World design authoring currently has the first typed revision-to-World handoff, including the transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. Broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain outside the current seam. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java index 20eda90f55..04826198cb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationPayloadRetentionJob.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.gamedesign.maintenance; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -17,9 +16,6 @@ name = "firemud.retained-tenant.payload-retention.enabled", havingValue = "true", matchIfMissing = true) -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected repository is an owner-local Spring-managed collaborator.") public class GameSessionTenantAssociationPayloadRetentionJob { private static final Logger LOG = LoggerFactory.getLogger(GameSessionTenantAssociationPayloadRetentionJob.class); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 4e396f9c2c..f4909909c7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -299,9 +300,6 @@ private List prepareRealmEntryPolicies(VersionDto versio if (revisions.isEmpty()) { return List.of(); } - if (revisions.size() > PublishedRealmEntryPolicySetEvidence.MAX_POLICIES) { - throw new IllegalStateException("Realm-entry policy set exceeds the v1 complete-read bound"); - } if (version.scriptOnly()) { throw new IllegalStateException("Script-only publication cannot freeze realm-entry policy"); } @@ -309,10 +307,8 @@ private List prepareRealmEntryPolicies(VersionDto versio throw new IllegalStateException("Realm-entry policy requires an exact owner version"); } - Set selectorPairs = new HashSet<>(); - Set realmSlugs = new HashSet<>(); - List sources = new java.util.ArrayList<>(); - int visiblePublicProductionCount = 0; + Map sourcesById = new HashMap<>(); + Map latestBySelector = new HashMap<>(); for (Revision revision : revisions) { if (revision == null || revision.getId() == null @@ -323,18 +319,43 @@ private List prepareRealmEntryPolicies(VersionDto versio throw new IllegalStateException( "Realm-entry policy source revision is outside its owner scope"); } + + Revision priorSource = sourcesById.putIfAbsent(revision.getId(), revision); + if (priorSource != null) { + if (!samePolicySource(priorSource, revision)) { + throw new IllegalStateException( + "Conflicting realm-entry policy sources share a revision ID"); + } + continue; + } + RealmEntryPolicy policy = RealmEntryPolicy.parse(revision.getData(), objectMapper); - String pair = policy.worldSlug() + "\u0000" + policy.realmSlug(); - if (!selectorPairs.add(pair)) { - throw new IllegalStateException("Duplicate published realm-entry policy selector"); + PolicySelector selector = new PolicySelector(policy.worldSlug(), policy.realmSlug()); + RealmEntryPolicySource previous = latestBySelector.get(selector); + if (previous == null || revision.getId() > previous.revision().getId()) { + latestBySelector.put(selector, new RealmEntryPolicySource(revision, policy)); } + } + + List sources = + latestBySelector.values().stream() + .sorted( + Comparator.comparing((RealmEntryPolicySource source) -> source.policy().worldSlug()) + .thenComparing(source -> source.policy().realmSlug())) + .toList(); + if (sources.size() > PublishedRealmEntryPolicySetEvidence.MAX_POLICIES) { + throw new IllegalStateException("Realm-entry policy set exceeds the v1 complete-read bound"); + } + Set realmSlugs = new HashSet<>(); + int visiblePublicProductionCount = 0; + for (RealmEntryPolicySource source : sources) { + RealmEntryPolicy policy = source.policy(); if (!realmSlugs.add(policy.realmSlug())) { throw new IllegalStateException("Duplicate published realm-entry policy realm slug"); } if (policy.visible() && policy.publicProduction()) { visiblePublicProductionCount++; } - sources.add(new RealmEntryPolicySource(revision, policy)); } if (visiblePublicProductionCount != 1) { throw new IllegalStateException( @@ -343,6 +364,17 @@ private List prepareRealmEntryPolicies(VersionDto versio return List.copyOf(sources); } + private boolean samePolicySource(Revision left, Revision right) { + return Objects.equals(left.getId(), right.getId()) + && Objects.equals(left.getTenantId(), right.getTenantId()) + && Objects.equals(left.getVersionId(), right.getVersionId()) + && Objects.equals(left.getAuthorAccountId(), right.getAuthorAccountId()) + && Objects.equals(left.getRevisionKind(), right.getRevisionKind()) + && Objects.equals(left.getLogicalRevisionId(), right.getLogicalRevisionId()) + && Objects.equals(left.getData(), right.getData()) + && Objects.equals(left.getCreatedAt(), right.getCreatedAt()); + } + private void freezeRealmEntryPolicies( VersionDto version, PublishedReleaseBundle bundle, List sources) { if (sources.isEmpty()) { @@ -450,6 +482,8 @@ private boolean versionIdEquals(long requestedVersionId, Long persistedVersionId private record RealmEntryPolicySource(Revision revision, RealmEntryPolicy policy) {} + private record PolicySelector(String worldSlug, String realmSlug) {} + private record PolicyOwnerContext( GameTenantIdentity tenantIdentity, net.firedevops.firemud.gamedesign.entity.Version version, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index a540b7d4d8..c9dab9f26a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -32,6 +32,7 @@ import org.jooq.exception.TooManyRowsException; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; import org.springframework.grpc.server.service.GrpcService; import tools.jackson.databind.ObjectMapper; @@ -95,7 +96,7 @@ public void resolveRuntimeTenantIdentity( .withDescription("Game Design tenant identity provenance is ambiguous or invalid") .asRuntimeException()); return; - } catch (DataAccessResourceFailureException ex) { + } catch (DataAccessResourceFailureException | TransientDataAccessException ex) { responseObserver.onError( Status.UNAVAILABLE .withDescription("Game Design tenant identity is temporarily unavailable") @@ -205,12 +206,29 @@ public void resolveLegacyGameSessionTenantAssociation( .withDescription("Retained Game Session association evidence is inconsistent") .asRuntimeException()); return; - } catch (DataAccessException ex) { + } catch (DataAccessResourceFailureException | TransientDataAccessException ex) { responseObserver.onError( Status.UNAVAILABLE .withDescription("Retained Game Session association could not be read") .asRuntimeException()); return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Retained Game Session association could not be read" + : "Retained Game Session association evidence could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Retained Game Session association evidence could not be read") + .asRuntimeException()); + return; } if (resolved.isEmpty()) { responseObserver.onError( @@ -305,7 +323,7 @@ public void resolvePublishedRealmEntryPolicy( .withDescription("Published realm-entry policy evidence is inconsistent") .asRuntimeException()); return; - } catch (DataAccessResourceFailureException ex) { + } catch (DataAccessResourceFailureException | TransientDataAccessException ex) { responseObserver.onError( Status.UNAVAILABLE .withDescription("Published realm-entry policy is temporarily unavailable") @@ -398,7 +416,7 @@ public void listPublishedRealmEntryPolicies( "Complete published realm-entry policy set is inconsistent or unsupported") .asRuntimeException()); return; - } catch (DataAccessResourceFailureException ex) { + } catch (DataAccessResourceFailureException | TransientDataAccessException ex) { responseObserver.onError( Status.UNAVAILABLE .withDescription("Published realm-entry policy set is temporarily unavailable") diff --git a/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql b/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql index b178db85d8..957c20cae6 100644 --- a/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql +++ b/services/game-design-service/src/main/resources/db/migration/V31__published_realm_entry_policy.sql @@ -13,7 +13,7 @@ CREATE TABLE published_realm_entry_policy ( source_revision_id BIGINT NOT NULL REFERENCES revision(id), release_bundle_identity VARCHAR(71) NOT NULL CHECK (release_bundle_identity ~ '^sha256:[0-9a-f]{64}$'), - publish_workflow_id VARCHAR(64) NOT NULL CHECK (publish_workflow_id <> ''), + publish_workflow_id VARCHAR(1024) NOT NULL CHECK (publish_workflow_id <> ''), manifest_hash VARCHAR(128) NOT NULL CHECK (manifest_hash <> ''), world_slug VARCHAR(64) NOT NULL CHECK (world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index e166fd751c..71d71c97a2 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -7,6 +7,7 @@ import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Signature; +import java.time.temporal.ChronoUnit; import java.util.Base64; import java.util.Map; import java.util.Objects; @@ -57,8 +58,6 @@ class GameSessionTenantAssociationRepositoryIntegrationTest { DSL.field(DSL.name("description"), String.class); private static final org.jooq.Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); - private static final org.jooq.Field APPROVED_BY = - DSL.field(DSL.name("approved_by"), String.class); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -423,7 +422,9 @@ void databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInse fixture .dsl() .update(ASSOCIATIONS) - .set(APPROVED_BY, "changed-owner") + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "changed-owner") .where(OPERATION_ID.eq(receipt.manifest().operationId())) .execute()) .isInstanceOf(DataAccessException.class) @@ -451,14 +452,7 @@ void databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInse .dsl() .insertInto(ASSOCIATIONS) .set(OPERATION_ID, uuid(81)) - .set(DSL.field(DSL.name("schema_version"), Integer.class), 1) .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) - .set(DSL.field(DSL.name("signer_key_id"), String.class), SIGNER_KEY_ID) - .set(DSL.field(DSL.name("approved_by"), String.class), "owner@example.test") - .set( - DSL.field(DSL.name("approval_reference"), String.class), - "source-contradiction-test") - .set(DSL.field(DSL.name("signed_at"), String.class), "2026-10-01T00:00:00Z") .set(DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class), 981L) .set( DSL.field(DSL.name("canonical_tenant_id"), UUID.class), @@ -470,13 +464,6 @@ void databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInse DSL.field(DSL.name("source_game_tenant_key"), String.class), "contradictory-source-key") .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") - .set( - DSL.field(DSL.name("game_session_evidence_digest"), String.class), - GAME_SESSION_EVIDENCE_DIGEST) - .set( - DSL.field(DSL.name("manifest_digest"), String.class), - receipt.manifestDigest()) - .set(DSL.field(DSL.name("signature"), String.class), receipt.ed25519Signature()) .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("does not match its Game Design row"); @@ -766,7 +753,8 @@ GameSessionTenantAssociationEvidence evidence( long sourceGameRowId, String sourceGameTenantKey, String provenanceKind) { - java.time.Instant sourceCapturedAt = java.time.Instant.now().minusSeconds(2); + java.time.Instant sourceCapturedAt = + java.time.Instant.now().minusSeconds(2).truncatedTo(ChronoUnit.MICROS); return new GameSessionTenantAssociationEvidence( 2, operationId, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java index 19fd7faabf..9fa6495e3e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.file.Path; import java.sql.Connection; import java.sql.Statement; import java.util.Map; @@ -167,7 +168,9 @@ private void migrate(DriverManagerDataSource dataSource, MigrationVersion target .defaultSchema(SERVICE_SCHEMA) .table(FLYWAY_TABLE) .placeholders(Map.of("serviceSchema", SERVICE_SCHEMA)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); if (target != null) { configuration.target(target); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 50c9ecee7e..f0e2538ac2 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -39,6 +39,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; @@ -77,6 +78,7 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private GameRepository gameRepository; + @Autowired private JdbcTemplate jdbcTemplate; @Autowired private PublishAttemptServiceImpl publishAttemptService; @Autowired private VersionPublishCommandServiceImpl versionPublishCommandService; @Autowired private PublishAttemptRepository publishAttemptRepository; @@ -89,6 +91,32 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @MockitoSpyBean private VersionAssetArtifactService versionAssetArtifactService; + @Test + void publishedRealmEntryPolicyWorkflowIdentityColumnMatchesReleaseBundleCapacity() { + Integer policyWorkflowIdCapacity = + jdbcTemplate.queryForObject( + """ + SELECT character_maximum_length + FROM information_schema.columns + WHERE table_schema = current_schema() + AND table_name = 'published_realm_entry_policy' + AND column_name = 'publish_workflow_id' + """, + Integer.class); + Integer bundleWorkflowIdCapacity = + jdbcTemplate.queryForObject( + """ + SELECT character_maximum_length + FROM information_schema.columns + WHERE table_schema = current_schema() + AND table_name = 'published_release_bundle' + AND column_name = 'publish_workflow_id' + """, + Integer.class); + + assertThat(policyWorkflowIdCapacity).isEqualTo(1024).isEqualTo(bundleWorkflowIdCapacity); + } + @Test void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { Game game = new Game(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java index 46a24f8ea7..56ed9e11b0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java @@ -9,6 +9,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.Base64; import java.util.HashSet; import java.util.Optional; @@ -26,6 +27,7 @@ import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.FileSystemResource; +import org.springframework.dao.DataAccessResourceFailureException; class GameSessionTenantAssociationGrpcTest { private static final UUID OPERATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -132,17 +134,36 @@ void exactReadCarriesCompleteImmutableManifestAndSeparateReadEcho() { } @Test - void absentContradictoryAndUnavailableEvidenceNeverReturnsPartialContent() { + void absentContradictoryAndUnexpectedStorageEvidenceNeverReturnsPartialContent() { when(repository.read(OPERATION, TENANT, 41L, "test")) .thenReturn(Optional.empty()) .thenThrow(new IllegalStateException("contradictory stored evidence")) - .thenThrow(new org.jooq.exception.DataAccessException("storage unavailable")); + .thenThrow(new org.jooq.exception.DataAccessException("non-connection storage failure")) + .thenThrow(new UnsupportedOperationException("unexpected repository failure")); assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.NOT_FOUND); assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.FAILED_PRECONDITION); - Observer unavailable = call(request(), GAME_SESSION); - assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(unavailable.value).isNull(); - assertThat(unavailable.completed).isFalse(); + for (int index = 0; index < 2; index++) { + Observer internal = call(request(), GAME_SESSION); + assertThat(internal.error).isEqualTo(Status.Code.INTERNAL); + assertThat(internal.value).isNull(); + assertThat(internal.completed).isFalse(); + } + } + + @Test + void mapsUnavailableAssociationStorageFailuresWithoutReturningPartialContent() { + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenThrow(new DataAccessResourceFailureException("unavailable")) + .thenThrow( + new org.jooq.exception.DataAccessException( + "connection failure", new SQLException("database unavailable", "08006"))); + + for (int index = 0; index < 2; index++) { + Observer unavailable = call(request(), GAME_SESSION); + assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.value).isNull(); + assertThat(unavailable.completed).isFalse(); + } } @Test diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index fb0fced9df..e6b5af53d0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -182,11 +182,14 @@ void createFullVersionBundlePreservesLegacyPublicationWhenNoPolicyExists() { } @Test - void createFullVersionBundleRejectsWrongTenantVersionSourceAndDuplicateSelectors() { + void createFullVersionBundleRejectsInvalidHistoricalSourceBeforeNormalizing() { when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) - .thenReturn(List.of(policyRevision(21L, "tenant-2", 7L, VALID_REALM_ENTRY_POLICY))); + .thenReturn( + List.of( + policyRevision(21L, "tenant-2", 7L, VALID_REALM_ENTRY_POLICY), + policyRevision(22L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY))); assertThrows( IllegalStateException.class, @@ -199,12 +202,18 @@ void createFullVersionBundleRejectsWrongTenantVersionSourceAndDuplicateSelectors List.of())); verify(repository, never()).save(any(PublishedReleaseBundle.class)); + verify(gameRepository, never()).findRuntimeTenantIdentityByTenantKey("tenant-1"); + } + + @Test + void createFullVersionBundleRejectsConflictingSourcesWithTheSameRevisionId() { + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) .thenReturn( List.of( policyRevision(21L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY), - policyRevision(22L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY))); + policyRevision(21L, "tenant-1", 7L, policyJson("main", false, false)))); assertThrows( IllegalStateException.class, () -> @@ -215,6 +224,128 @@ void createFullVersionBundleRejectsWrongTenantVersionSourceAndDuplicateSelectors "genrev-1", List.of())); verify(gameRepository, never()).findRuntimeTenantIdentityByTenantKey("tenant-1"); + verify(repository, never()).save(any(PublishedReleaseBundle.class)); + } + + @Test + void createFullVersionBundleUsesLatestPolicyForEachSelectorAndItsWorkflowIdentity() { + String longWorkflowId = "w".repeat(900); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) + .thenReturn( + List.of( + policyRevision(21L, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY), + policyRevision(22L, "tenant-1", 7L, policyJson("main", false, false)), + policyRevision(23L, "tenant-1", 7L, policyJson("side", true, true)))); + when(gameRepository.findRuntimeTenantIdentityByTenantKey("tenant-1")) + .thenReturn(Optional.of(tenantIdentity("tenant-1"))); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle entity = invocation.getArgument(0); + entity.setId(11L); + return entity; + }); + + service.createFullVersionBundle( + version(), + longWorkflowId, + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of()); + + org.mockito.ArgumentCaptor bundleCaptor = + org.mockito.ArgumentCaptor.forClass(PublishedReleaseBundle.class); + verify(repository).save(bundleCaptor.capture()); + assertEquals(longWorkflowId, bundleCaptor.getValue().getPublishWorkflowId()); + + org.mockito.ArgumentCaptor policyCaptor = + org.mockito.ArgumentCaptor.forClass(PublishedRealmEntryPolicy.class); + verify(realmEntryPolicyRepository, org.mockito.Mockito.times(2)).insert(policyCaptor.capture()); + assertEquals( + List.of(22L, 23L), + policyCaptor.getAllValues().stream() + .map(PublishedRealmEntryPolicy::sourceRevisionId) + .sorted() + .toList()); + assertEquals( + List.of("main", "side"), + policyCaptor.getAllValues().stream() + .map(PublishedRealmEntryPolicy::realmSlug) + .sorted() + .toList()); + assertEquals( + List.of(longWorkflowId, longWorkflowId), + policyCaptor.getAllValues().stream() + .map(PublishedRealmEntryPolicy::publishWorkflowId) + .toList()); + } + + @Test + void createFullVersionBundleBoundsEffectivePoliciesRatherThanRevisionHistory() { + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + List history = + java.util.stream.IntStream.range(0, PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1) + .mapToObj( + index -> policyRevision(21L + index, "tenant-1", 7L, VALID_REALM_ENTRY_POLICY)) + .toList(); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) + .thenReturn(history); + when(gameRepository.findRuntimeTenantIdentityByTenantKey("tenant-1")) + .thenReturn(Optional.of(tenantIdentity("tenant-1"))); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle entity = invocation.getArgument(0); + entity.setId(11L); + return entity; + }); + + service.createFullVersionBundle( + version(), + "workflow-1", + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of()); + + org.mockito.ArgumentCaptor policyCaptor = + org.mockito.ArgumentCaptor.forClass(PublishedRealmEntryPolicy.class); + verify(realmEntryPolicyRepository).insert(policyCaptor.capture()); + assertEquals( + 21L + PublishedRealmEntryPolicySetEvidence.MAX_POLICIES, + policyCaptor.getValue().sourceRevisionId()); + } + + @Test + void createFullVersionBundleRejectsMoreThanTheEffectivePolicyBound() { + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + List policies = + java.util.stream.IntStream.range(0, PublishedRealmEntryPolicySetEvidence.MAX_POLICIES + 1) + .mapToObj( + index -> + policyRevision( + 21L + index, + "tenant-1", + 7L, + policyJson("realm-" + index, index == 0, index == 0))) + .toList(); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + "tenant-1", 7L, RealmEntryPolicy.REVISION_KIND)) + .thenReturn(policies); + + assertThrows( + IllegalStateException.class, + () -> + service.createFullVersionBundle( + version(), + "workflow-1", + new ExportedAssetManifest("abc123", List.of("manifest.json")), + "genrev-1", + List.of())); + verify(repository, never()).save(any(PublishedReleaseBundle.class)); + verify(realmEntryPolicyRepository, never()).insert(any(PublishedRealmEntryPolicy.class)); } @Test @@ -592,6 +723,19 @@ private static Revision policyRevision( return revision; } + private static String policyJson(String realmSlug, boolean visible, boolean publicProduction) { + return "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"" + + realmSlug + + "\",\"realmDisplayName\":\"" + + realmSlug + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + } + private static GameTenantIdentity tenantIdentity(String tenantKey) { return new GameTenantIdentity( CANONICAL_TENANT_ID, GameTenantIdentity.ProvenanceKind.NEW_GAME_ROW, 42L, tenantKey); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index ce7a2bc81d..397d081b6a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -31,6 +31,7 @@ import org.jooq.exception.TooManyRowsException; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.QueryTimeoutException; import tools.jackson.databind.ObjectMapper; class TenantIdentityGrpcServiceTest { @@ -182,6 +183,19 @@ void mapsUnavailableOwnerReadWithoutReturningPartialEvidence() { assertThat(observer.completed).isFalse(); } + @Test + void mapsQueryTimeoutOwnerReadToUnavailableWithoutReturningPartialEvidence() { + when(repository.findRuntimeTenantIdentityByCanonicalTenantId(TENANT_ID)) + .thenThrow(new QueryTimeoutException("query timed out")); + + TestObserver observer = + call(request(TENANT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + + assertThat(status(observer)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + @Test void resolvesPublishedPolicyForExactSameNamespaceGameSessionPeer() { RealmEntryPolicy policy = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java index 6031bf3073..dd3a258aed 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java @@ -369,7 +369,7 @@ private PublishedRealmCatalogSnapshot toPublishedSnapshot(Record header) { .eq(namespace) .and(TENANT_ID.eq(tenantId)) .and(CATALOG_REVISION.eq(revision))) - .orderBy(WORLD_SLUG.asc(), REALM_SLUG.asc()) + .orderBy(WORLD_SLUG.collate("C").asc(), REALM_SLUG.collate("C").asc()) .fetch(); if (rows.size() != policyCount || rows.isEmpty() || rows.size() > 128) { throw new IllegalStateException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java index e27e3ea613..b9b6b9e1df 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantPayloadRetentionJob.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; import org.jooq.DSLContext; import org.slf4j.Logger; @@ -23,6 +24,10 @@ public class GameSessionRetainedTenantPayloadRetentionJob { private final DSLContext dsl; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The Spring-managed DSLContext is intentionally shared for owner transactions.") public GameSessionRetainedTenantPayloadRetentionJob(DSLContext dsl) { this.dsl = dsl; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java index e66bc69970..a8f9435f24 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.gamesession.service; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -24,11 +23,6 @@ * Internal, non-startup owner path that composes a complete Game Design policy set with the * committed local tenant association before Game Session materializes its immutable catalog. */ -@SuppressFBWarnings( - value = "CT_CONSTRUCTOR_THROW", - justification = - "The workload namespace and collaborators are validated before use; this internal owner" - + " service is intentionally not a startup or public admission trigger.") @Service @Lazy public final class PublishedRealmCatalogOwnerService { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index e50d38e488..fc29a47abf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -49,10 +49,10 @@ import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofResponse; import net.firedevops.firemud.gamesession.v1.GetPinnedScriptPatchVersionRequest; import net.firedevops.firemud.gamesession.v1.GetPinnedScriptPatchVersionResponse; -import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; -import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; import net.firedevops.firemud.gamesession.v1.GetPreparedVersionUpgradeRequest; import net.firedevops.firemud.gamesession.v1.GetPreparedVersionUpgradeResponse; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; import net.firedevops.firemud.gamesession.v1.GetRemoteCommandCoordinatorRequest; import net.firedevops.firemud.gamesession.v1.GetRemoteCommandCoordinatorResponse; import net.firedevops.firemud.gamesession.v1.GetRemoteFollowupRequest; @@ -76,8 +76,8 @@ import net.firedevops.firemud.gamesession.v1.PauseTicksForScopeResponse; import net.firedevops.firemud.gamesession.v1.PrepareVersionUpgradeRequest; import net.firedevops.firemud.gamesession.v1.PrepareVersionUpgradeResponse; -import net.firedevops.firemud.gamesession.v1.PublishedRealmAdmissionOwnerReadEvidence; import net.firedevops.firemud.gamesession.v1.PublishedRealmAdmissionAttemptStatus; +import net.firedevops.firemud.gamesession.v1.PublishedRealmAdmissionOwnerReadEvidence; import net.firedevops.firemud.gamesession.v1.PurgeQueuedTickCommandsForPluginVersionRequest; import net.firedevops.firemud.gamesession.v1.PurgeQueuedTickCommandsForPluginVersionResponse; import net.firedevops.firemud.gamesession.v1.PurgeQueuedTickCommandsForScriptPatchRequest; @@ -129,7 +129,8 @@ public final class GameSessionControlPlaneGrpcService private InitialAdmissionBindOwnerProofReader initialAdmissionBindOwnerProofReader; private InitialAdmissionBindOwnerReadWorkloadGuard initialAdmissionBindOwnerReadWorkloadGuard; private PublishedRealmAdmissionOwnerReadService publishedRealmAdmissionOwnerReadService; - private PublishedRealmAdmissionOwnerReadWorkloadGuard publishedRealmAdmissionOwnerReadWorkloadGuard; + private PublishedRealmAdmissionOwnerReadWorkloadGuard + publishedRealmAdmissionOwnerReadWorkloadGuard; private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); private static final int MAX_PUBLISHED_REALM_ADMISSION_OWNER_READ_REQUEST_BYTES = 512; @@ -596,8 +597,7 @@ private PublishedRealmAdmissionOwnerReadEvidence toWirePublishedRealmAdmissionOw .setPointerAuditRequestId(proof.initialAdmissionRequestId()) .setPointerAuditRequestDigest(proof.requestDigest()) .setInitialAdmissionAttemptStatus( - PublishedRealmAdmissionAttemptStatus - .PUBLISHED_REALM_ADMISSION_ATTEMPT_STATUS_COMMITTED) + PublishedRealmAdmissionAttemptStatus.PUBLISHED_REALM_ADMISSION_ATTEMPT_STATUS_COMMITTED) .build(); } diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 085467d1a1..dc9b6da02f 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -129,6 +129,8 @@ firemud: force-internal-service-outbound: true public-methods: - game_session.v1.GameSessionService/Ping + - game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof + - game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql index 79baf46583..185fd8f07f 100644 --- a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql +++ b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql @@ -44,7 +44,7 @@ CREATE TABLE game_session_retained_tenant_association_payload ( AND game_session_projection_digest IS NOT NULL AND game_session_projection_digest ~ '^sha256:[0-9a-f]{64}$') ), - CONSTRAINT chk_gs_retained_tenant_association_payload_approval_operation_id CHECK ( + CONSTRAINT chk_gs_retained_assoc_payload_approval_operation_id CHECK ( approval_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID ), CONSTRAINT chk_gs_retained_tenant_association_payload_digests CHECK ( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index d509056d3c..a29dea29d5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -151,7 +151,7 @@ void migrationPreservesNonNilAssociationAndApprovalOperationIdsAfterPayloadSplit fixture.insertAssociationMapping(payloadOperationId, uuid(935), uuid(936), 934L); assertThatThrownBy(() -> fixture.insertExpiredPayload(payloadOperationId, nilUuid)) .isInstanceOf(DataAccessException.class) - .hasMessageContaining("chk_gs_retained_tenant_association_payload_approval_operation_id"); + .hasMessageContaining("chk_gs_retained_assoc_payload_approval_operation_id"); } @Test @@ -546,7 +546,7 @@ void persistedRowsRejectUpdateDeleteAndTruncateThroughTheirOwnImmutableTriggers( assertCheckViolation( () -> fixture.dsl.execute( - "UPDATE game_session_retained_tenant_association SET approved_by = ? " + "UPDATE game_session_retained_tenant_association SET source_game_tenant_key = ? " + "WHERE operation_id = ?", "changed", operationId)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java index ea0c1e0919..70e8550468 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java @@ -183,6 +183,96 @@ void snapshotsRetryExactlyKeepStableRealmAndSharedIdentityAndGateLifecycleTransi assertThat(fixture.dsl().fetchCount(ADMISSION_POINTER)).isEqualTo(originalPointerCount); } + @Test + void persistedSnapshotOrdersAsciiPunctuationByWorldThenRealmSlug() { + Fixture fixture = fixture(); + fixture.seedAssociation(TENANT_ID, CANONICAL_TENANT_ID, 501L, "source-game-501"); + + PublishedRealmEntryPolicySetEvidence policySet = + punctuationEvidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501"); + PublishedRealmCatalogSnapshot snapshot = fixture.materialize(TENANT_ID, policySet); + PublishedRealmCatalogSnapshot readback = + fixture + .repository + .findPublishedSnapshot(NAMESPACE, TENANT_ID, snapshot.catalogRevision()) + .orElseThrow(); + + assertThat(readback.entries()) + .extracting( + entry -> + entry.policyEvidence().policy().worldSlug() + + "/" + + entry.policyEvidence().policy().realmSlug()) + .containsExactly("a-b/x-z", "a0/x-a", "a0/x0"); + } + + private static PublishedRealmEntryPolicySetEvidence punctuationEvidenceSet( + UUID canonicalTenantId, long sourceGameRowId, String sourceGameTenantKey) { + long versionId = 300L; + int versionNumber = 1; + String workflow = WORKFLOW + ":" + versionId; + String manifest = "manifest-" + versionId; + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + canonicalTenantId, versionId, workflow, manifest, JSON); + List policies = + List.of( + evidence( + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + workflow, + manifest, + releaseIdentity, + "x-a", + "Punctuation", + true, + false, + "SHARED", + "a0"), + evidence( + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + workflow, + manifest, + releaseIdentity, + "x0", + "Punctuation", + true, + false, + "SHARED", + "a0"), + evidence( + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + versionId, + versionNumber, + workflow, + manifest, + releaseIdentity, + "x-z", + "Punctuation", + true, + true, + "SHARED", + "a-b")); + return PublishedRealmEntryPolicySetEvidence.create( + canonicalTenantId, + versionId, + versionNumber, + releaseIdentity, + workflow, + manifest, + policies, + JSON); + } + private static PublishedRealmEntryPolicySetEvidence evidenceSet( UUID canonicalTenantId, long sourceGameRowId, @@ -382,29 +472,18 @@ void seedAssociation( long tenantId, UUID canonicalTenantId, long sourceGameRowId, String sourceGameTenantKey) { dsl.execute( "INSERT INTO game_session_retained_tenant_association " - + "(operation_id, approval_schema_version, target_namespace, association_request_id, " - + "request_digest, approval_operation_id, signer_key_id, approved_by, " - + "approval_reference, signed_at, legacy_game_session_tenant_id, canonical_tenant_id, " - + "source_game_row_id, source_game_tenant_key, provenance_kind, " - + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " - + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " - + "VALUES (?, 1, ?, ?, ?, ?, 'fixture-key', 'fixture-owner', 'fixture-approval', " - + "'2026-01-01T00:00:00Z', ?, ?, ?, ?, ?, ?, ?, ?, '{}', ?, ?)", + + "(operation_id, target_namespace, association_request_id, " + + "legacy_game_session_tenant_id, canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, captured_at, terminal_outcome) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, clock_timestamp(), 'ASSOCIATED')", UUID.randomUUID(), NAMESPACE, UUID.randomUUID(), - DIGEST, - UUID.randomUUID(), tenantId, canonicalTenantId, sourceGameRowId, sourceGameTenantKey, - PROVENANCE_KIND, - DIGEST, - DIGEST, - SIGNATURE, - DIGEST, - DIGEST); + PROVENANCE_KIND); } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 7e606844cc..93229f3ab2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -46,8 +46,9 @@ class InitialAdmissionBindPostgresIntegrationTest { @Test void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFailsClosed() { - DriverManagerDataSource dataSource = dataSource(); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + String schema = schemaName(); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); TransactionTemplate transactionTemplate = @@ -160,8 +161,9 @@ void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFails @Test void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { - DriverManagerDataSource dataSource = dataSource(); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + String schema = schemaName(); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); TransactionTemplate transactionTemplate = @@ -214,6 +216,7 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { 810L, "published-launch-v1", 77L, "prb:41:902:77", 4L)); assertThat(dsl.fetchCount(DSL.table("gameplay_initial_admission_bind_catalog"))).isZero(); + var attempt = transactionTemplate.execute(status -> service.beginIntent(request)); assertThatThrownBy( () -> transactionTemplate.execute( @@ -235,7 +238,6 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); - var attempt = transactionTemplate.execute(status -> service.beginIntent(request)); assertThat(attempt.catalogSourceKind()).isEqualTo("V14_PUBLISHED"); assertThat(attempt.tenantId()).isEqualTo(41L); assertThat(attempt.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); @@ -263,6 +265,7 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { var proof = transactionTemplate.execute(status -> service.commit(binding)); assertThat(proof.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.COMMITTED); assertThat(proof.pointerAuditRequestDigest()).isEqualTo(digest); + assertThat(dsl.fetchCount(DSL.table("gameplay_initial_admission_bind_catalog"))).isZero(); assertThat( dsl.fetchOne( "SELECT character_creation_policy, requires_character_selection, state_scope " @@ -279,15 +282,31 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isEqualTo(1); } - private static DriverManagerDataSource dataSource() { + private static String schemaName() { + return "gs_initial_admission_bind_" + UUID.randomUUID().toString().replace("-", ""); + } + + private static DriverManagerDataSource dataSource(String schema) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl(postgres.getJdbcUrl()); dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); return dataSource; } + private static void migrate(DriverManagerDataSource dataSource, String schema) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + private static GameInstance gameInstance() { GameInstance gameInstance = new GameInstance(); gameInstance.setTenantId(41L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java new file mode 100644 index 0000000000..6167b64a2e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java @@ -0,0 +1,440 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProofReader; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadService; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofRequest; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofResponse; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.SetPinnedScriptPatchVersionRequest; +import net.firedevops.firemud.gamesession.v1.SetPinnedScriptPatchVersionResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class InitialAdmissionOwnerReadAuthWiringTest { + private static final String NAMESPACE = "test"; + private static final String INITIAL_METHOD = + "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof"; + private static final String PUBLISHED_METHOD = + "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead"; + private static final String PING_METHOD = "game_session.v1.GameSessionService/Ping"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String HOLD_ID = "00000000-0000-0000-0000-000000000003"; + private static final String HOLD_FENCE = "00000000-0000-0000-0000-000000000004"; + private static final String REALM_UUID = "00000000-0000-0000-0000-000000000001"; + private static final String PLAYABLE_NAMESPACE_UUID = "00000000-0000-0000-0000-000000000002"; + private static final String REQUEST_ID = "initial-admission-1"; + private static final String REQUEST_DIGEST = "a".repeat(64); + + @BeforeEach + void startWithoutSessionContext() { + SessionContext.clear(); + } + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void noTokenReachesEachExactOwnerHandlerForItsSameNamespacePeer() { + withConfiguredInterceptor( + false, + interceptor -> { + InitialAdmissionBindOwnerProofReader proofReader = + mock(InitialAdmissionBindOwnerProofReader.class); + PublishedRealmAdmissionOwnerReadService ownerReadService = + mock(PublishedRealmAdmissionOwnerReadService.class); + GameSessionControlPlaneGrpcService service = service(proofReader, ownerReadService); + + InitialDispatchResult initial = dispatchInitial(interceptor, service, WORLD_URI); + PublishedDispatchResult published = dispatchPublished(interceptor, service, ENTITY_URI); + + assertThat(initial.handlerDispatched()).isTrue(); + assertThat(initial.observer().response.getError().getCode()).isEqualTo("INTERNAL"); + verify(proofReader).read(binding()); + + assertThat(published.handlerDispatched()).isTrue(); + assertThat(published.observer().statusCode).isEqualTo(Status.Code.UNAVAILABLE); + verify(ownerReadService).read(any(PublishedRealmAdmissionOwnerReadRequest.class)); + }); + } + + @Test + void absentOrWrongPeerCannotPassEitherExactOwnerHandler() { + withConfiguredInterceptor( + false, + interceptor -> { + InitialAdmissionBindOwnerProofReader proofReader = + mock(InitialAdmissionBindOwnerProofReader.class); + PublishedRealmAdmissionOwnerReadService ownerReadService = + mock(PublishedRealmAdmissionOwnerReadService.class); + GameSessionControlPlaneGrpcService service = service(proofReader, ownerReadService); + + InitialDispatchResult absentInitial = dispatchInitial(interceptor, service, null); + InitialDispatchResult wrongInitial = dispatchInitial(interceptor, service, ENTITY_URI); + PublishedDispatchResult absentPublished = dispatchPublished(interceptor, service, null); + PublishedDispatchResult wrongPublished = + dispatchPublished( + interceptor, service, "spiffe://firemud/ns/other/sa/entity-management-service"); + + assertThat(absentInitial.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + assertThat(wrongInitial.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + assertThat(absentPublished.observer().statusCode) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongPublished.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(proofReader, ownerReadService); + }); + } + + @Test + void eitherOwnerHandlerRejectsAuthenticatedCallerContextEvenWithTheRightPeer() { + withConfiguredInterceptor( + false, + interceptor -> { + InitialAdmissionBindOwnerProofReader proofReader = + mock(InitialAdmissionBindOwnerProofReader.class); + PublishedRealmAdmissionOwnerReadService ownerReadService = + mock(PublishedRealmAdmissionOwnerReadService.class); + GameSessionControlPlaneGrpcService service = service(proofReader, ownerReadService); + SessionContext.setContext("authenticated-user", List.of(), Map.of()); + + try { + InitialDispatchResult initial = dispatchInitial(interceptor, service, WORLD_URI); + PublishedDispatchResult published = dispatchPublished(interceptor, service, ENTITY_URI); + + assertThat(initial.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + assertThat(published.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(proofReader, ownerReadService); + } finally { + SessionContext.clear(); + } + }); + } + + @Test + void unrelatedControlPlaneMethodStillRequiresBearerToken() { + withConfiguredInterceptor( + false, + interceptor -> { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()) + .thenReturn( + GameSessionControlPlaneServiceGrpc.getSetPinnedScriptPatchVersionMethod()); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler + next = mock(ServerCallHandler.class); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(next, never()).startCall(eq(call), any(Metadata.class)); + }); + } + + @Test + void productionConfigurationInheritsOnlyTheExactBaseOwnerReadExemptions() { + withConfiguredInterceptor( + true, + interceptor -> { + InitialAdmissionBindOwnerProofReader proofReader = + mock(InitialAdmissionBindOwnerProofReader.class); + PublishedRealmAdmissionOwnerReadService ownerReadService = + mock(PublishedRealmAdmissionOwnerReadService.class); + GameSessionControlPlaneGrpcService service = service(proofReader, ownerReadService); + + InitialDispatchResult initial = dispatchInitial(interceptor, service, WORLD_URI); + PublishedDispatchResult published = dispatchPublished(interceptor, service, ENTITY_URI); + + assertThat(initial.handlerDispatched()).isTrue(); + assertThat(published.handlerDispatched()).isTrue(); + verify(proofReader).read(binding()); + verify(ownerReadService).read(any(PublishedRealmAdmissionOwnerReadRequest.class)); + }); + } + + private static GameSessionControlPlaneGrpcService service( + InitialAdmissionBindOwnerProofReader proofReader, + PublishedRealmAdmissionOwnerReadService ownerReadService) { + GameSessionControlPlaneGrpcService service = + new GameSessionControlPlaneGrpcService( + mock(GameSessionCommandControlPlaneService.class), + mock(GameSessionRemoteControlPlaneService.class), + mock(GameSessionRuntimeControlPlaneReadService.class), + mock(GameSessionAdmissionPointerControlPlaneService.class), + mock(GameSessionOperatorControlPlaneService.class), + mock(GameSessionVersionUpgradeControlPlaneService.class), + new SimpleMeterRegistry()); + service.configureInitialAdmissionBindOwnerReadBoundary(proofReader, NAMESPACE); + service.configurePublishedRealmAdmissionOwnerReadBoundary(ownerReadService, NAMESPACE); + return service; + } + + private static InitialDispatchResult dispatchInitial( + AuthTokenInterceptor interceptor, + GameSessionControlPlaneGrpcService service, + String peerUri) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()) + .thenReturn(GameSessionControlPlaneServiceGrpc.getGetInitialAdmissionBindProofMethod()); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + InitialObserver observer = new InitialObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + GetInitialAdmissionBindProofRequest, GetInitialAdmissionBindProofResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(GetInitialAdmissionBindProofRequest request) { + service.getInitialAdmissionBindProof(request, observer); + } + }; + } + }; + withPeer( + peerUri, + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, new Metadata(), next); + listener.onMessage(initialRequest()); + }); + return new InitialDispatchResult(observer, handlerDispatched.get()); + } + + private static PublishedDispatchResult dispatchPublished( + AuthTokenInterceptor interceptor, + GameSessionControlPlaneGrpcService service, + String peerUri) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall< + GetPublishedRealmAdmissionOwnerReadRequest, GetPublishedRealmAdmissionOwnerReadResponse> + call = mock(ServerCall.class); + when(call.getMethodDescriptor()) + .thenReturn( + GameSessionControlPlaneServiceGrpc.getGetPublishedRealmAdmissionOwnerReadMethod()); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + PublishedObserver observer = new PublishedObserver(); + ServerCallHandler< + GetPublishedRealmAdmissionOwnerReadRequest, GetPublishedRealmAdmissionOwnerReadResponse> + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + GetPublishedRealmAdmissionOwnerReadRequest, + GetPublishedRealmAdmissionOwnerReadResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(GetPublishedRealmAdmissionOwnerReadRequest request) { + service.getPublishedRealmAdmissionOwnerRead(request, observer); + } + }; + } + }; + withPeer( + peerUri, + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, new Metadata(), next); + listener.onMessage(publishedRequest()); + }); + return new PublishedDispatchResult(observer, handlerDispatched.get()); + } + + private static void withPeer(String peerUri, Runnable action) { + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(action); + return; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); + } + + private static GetInitialAdmissionBindProofRequest initialRequest() { + return GetInitialAdmissionBindProofRequest.newBuilder() + .setHoldId(HOLD_ID) + .setHoldFence(HOLD_FENCE) + .setTenantId("42") + .setRealmUuid(REALM_UUID) + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE_UUID) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setGameInstanceId("101") + .setVersionId("11") + .setActiveLifecycleEpoch(7L) + .setInitialAdmissionRequestId(REQUEST_ID) + .setRequestDigest(REQUEST_DIGEST) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(1L) + .build(); + } + + private static InitialAdmissionBindHoldBinding binding() { + return new InitialAdmissionBindHoldBinding( + HOLD_ID, + HOLD_FENCE, + 42L, + REALM_UUID, + PLAYABLE_NAMESPACE_UUID, + "SHARED", + 101L, + 11L, + 7L, + REQUEST_ID, + REQUEST_DIGEST, + true, + 1L); + } + + private static GetPublishedRealmAdmissionOwnerReadRequest publishedRequest() { + return GetPublishedRealmAdmissionOwnerReadRequest.newBuilder() + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId("22222222-2222-4222-8222-222222222222") + .setGameSessionTenantId("70123") + .setWorldSlug("earth") + .setRealmSlug("main") + .setExpectedCatalogRevision(8L) + .setExpectedPointerVersion(1L) + .build(); + } + + private static void withConfiguredInterceptor( + boolean productionProfile, java.util.function.Consumer action) { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withInitializer( + context -> { + try { + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + PropertySource application = + loader + .load( + "game-session-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(application); + if (productionProfile) { + PropertySource production = + loader + .load( + "game-session-production", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(production); + } + } catch (IOException exception) { + throw new IllegalStateException( + "Could not load Game Session auth config", exception); + } + }) + .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .containsExactly(PING_METHOD, INITIAL_METHOD, PUBLISHED_METHOD); + action.accept(context.getBean(AuthTokenInterceptor.class)); + }); + } + + private record InitialDispatchResult(InitialObserver observer, boolean handlerDispatched) {} + + private record PublishedDispatchResult(PublishedObserver observer, boolean handlerDispatched) {} + + private static final class InitialObserver + implements StreamObserver { + private GetInitialAdmissionBindProofResponse response; + private Status.Code statusCode; + + @Override + public void onNext(GetInitialAdmissionBindProofResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final class PublishedObserver + implements StreamObserver { + private GetPublishedRealmAdmissionOwnerReadResponse response; + private Status.Code statusCode; + + @Override + public void onNext(GetPublishedRealmAdmissionOwnerReadResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java index af9499cc19..08081166d6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java @@ -12,7 +12,6 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; @@ -22,6 +21,7 @@ import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadProof; import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadRequest; import net.firedevops.firemud.gamesession.service.PublishedRealmAdmissionOwnerReadService; +import net.firedevops.firemud.gamesession.service.impl.GameSessionControlPlaneGrpcService; import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; import net.firedevops.firemud.gamesession.v1.PublishedRealmAdmissionAttemptStatus; @@ -38,8 +38,7 @@ class PublishedRealmAdmissionOwnerReadGrpcServiceTest { private static final UUID REALM_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final UUID PLAYABLE_STATE_NAMESPACE_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); - private static final UUID ATTEMPT_ID = - UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID ATTEMPT_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final String REQUEST_ID = "88888888-8888-4888-8888-888888888888"; private static final String REQUEST_DIGEST = "a".repeat(64); private static final long GAME_SESSION_TENANT_ID = 70123L; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java index f27415c606..c1dbb5c6eb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadWorkloadGuardTest.java @@ -9,6 +9,7 @@ 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.service.impl.PublishedRealmAdmissionOwnerReadWorkloadGuard; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -52,9 +53,7 @@ void rejectsOtherWorkloadsNamespacesMissingPeersAndInvalidConfiguration() { assertDenied( () -> runAsPeer( - ENTITY_SERVICE, - "other-namespace", - guard::requireEntityManagementOwnerReadCaller)); + ENTITY_SERVICE, "other-namespace", guard::requireEntityManagementOwnerReadCaller)); assertDenied(() -> guard.requireEntityManagementOwnerReadCaller()); assertDenied( () -> @@ -79,11 +78,7 @@ void rejectsAuthenticatedCallerContextEvenWithTheExpectedPeerCertificate() { SessionContext.setContext("account", List.of("player"), Map.of()); assertDenied( - () -> - runAsPeer( - ENTITY_SERVICE, - NAMESPACE, - guard::requireEntityManagementOwnerReadCaller)); + () -> runAsPeer(ENTITY_SERVICE, NAMESPACE, guard::requireEntityManagementOwnerReadCaller)); } private static void assertDenied(Runnable action) { From fd3b57ae095e35584884ff033f06d792fcd139fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:46:48 +1300 Subject: [PATCH 084/105] fix: guard runtime entitlement reads with exact workload peers --- .../account-service/api-contracts.md | 2 +- .../player-access-and-session.md | 2 +- .../service/impl/AccountGrpcService.java | 29 ++- .../service/impl/AccountGrpcServiceTest.java | 215 +++++++++++++----- 4 files changed, 189 insertions(+), 59 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 80e67164fe..1afc7684b3 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -270,7 +270,7 @@ The canonical token refresh, replacement, generation, revocation, fencing, logou The canonical membership, entitlement response shape, freshness, and sequence contract is [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). This API document retains only the local surfaces and transport consequences: - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` and `GetTenantEntitlementsForRuntime(tenantId, requestId)` are internal-only workload APIs for gameplay/runtime callers; they are not caller-facing substitutes for the billing-safe membership and entitlement variants listed above. -- Current enforcement differs by method: both remain in Account's gRPC `public-methods` list, but `GetTenantMembershipForRuntime` enforces the exact Game Session workload and privately resolves the canonical Account UUID. `GetTenantEntitlementsForRuntime` still accepts a caller-selected tenant without a workload-peer check or caller-context tenant binding. Its internal-workload boundary and wrong-workload/cross-tenant denial proof remain incomplete. +- Current enforcement differs by method: both remain in Account's gRPC `public-methods` list so workload-only mTLS calls bypass bearer validation. `GetTenantMembershipForRuntime` enforces the exact Game Session workload and privately resolves the canonical Account UUID. `GetTenantEntitlementsForRuntime` now requires the exact same-namespace Game Session or World Management mTLS peer and validates a positive tenant ID plus a required bounded request ID before invoking its owner service. The target caller-context tenant binding remains incomplete: the current tenant-only request does not carry Game Session's typed player context and exact target bundle or World Management's tenant/operation-bound lifecycle context, so this guard does not establish complete admission eligibility or cross-tenant denial. - `GetRealmAccessGrantForRuntime(accountId, tenantId, worldSlug, realmSlug, requestId)` is an internal Game Session-only read for non-public gameplay admission. Its wire `accountId` is the canonical non-nil Account UUID; Account resolves the private row through its provenance-checked UUID resolver, verifies that the grant result still names that exact row and requested tenant/world/realm, and echoes the UUID. It requires the exact same-namespace Game Session mTLS identity without an end-user bearer token. Game Session fails closed unless the response echoes the exact requested UUID and realm scope, has a positive grant version and a parseable current evaluation timestamp, and reports `granted=true`. The existing grant persistence remains limited to the four-field scope; lifecycle-bound grant reads, expiry, revocation propagation, consumer reconciliation, and active-binding ejection remain incomplete. - `GetRealmAccessGrant` and `ListRealmAccessGrantsForAccount` remain Account-owned internal reads for non-public realm discovery and admission; both require `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` and reject an unscoped or tenant-global `realmSlug` lookup. Current implementation is limited to four-field grant persistence/internal lookup and limited text `PLAY` denial; it does not prove lifecycle-bound reads, expiry, revocation propagation, consumer reconciliation, or active-binding ejection. Tenant-admin grant management and user-facing account selection remain incomplete. - `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is consumed by Account through `GameSessionClient`. [Multi-Tenancy's realm-catalog-and-admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns the realm-catalog/admission-pointer identity and `OPEN`/`CLOSED` semantics; Game Session remains the runtime owner that persists, mutates, and serves the pointer read. Account applies a bounded deadline to its gameplay-routing RPCs and translates only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` failures to retryable HTTP `503` / `AUTH_UNAVAILABLE`; other transport statuses retain their transport classification. Reachable application outcomes are not availability failures. Account's local pointer validation requires `stateScope` to be exactly `SHARED` or `ISOLATED`: a complete `CLOSED` pointer becomes `REALM_UNAVAILABLE`, reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid pointer evidence becomes `ADMISSION_POINTER_UNAVAILABLE`, and a valid scope whose exact pair changed becomes `CONNECT_SCOPE_MISMATCH`. Account never treats a timeout as missing pointer evidence, coerces an unknown scope to shared state, or silently re-resolves a stale selector. The current response remains the implemented local pointer shape; target pointer fields and `CLOSED` handling are owned by that canonical runtime routing contract and remain implementation drift where noted there. 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 cbf15dfa60..985eea62cf 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -46,7 +46,7 @@ These links add decision provenance only; they do not upgrade player-access or s The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. -At the Account gRPC boundary, `GetTenantMembershipForRuntime` enforces its exact Game Session peer and resolves the canonical Account UUID before reading the requested membership. The separate `GetTenantEntitlementsForRuntime` handler still lacks a workload-peer check and tenant binding; wrong-workload/cross-tenant denial proof is absent, so its internal runtime authorization boundary remains incomplete. +At the Account gRPC boundary, `GetTenantMembershipForRuntime` enforces its exact Game Session peer and resolves the canonical Account UUID before reading the requested membership. The separate `GetTenantEntitlementsForRuntime` handler now enforces its exact same-namespace Game Session or World Management peer and validates its tenant/request selectors before owner invocation. Focused handler proof covers allowed callers and absent, wrong-workload, cross-namespace, and malformed-request denial; the complete 90-case Account gRPC unit suite passed. The target typed caller/operation-to-tenant binding remains absent from the current tenant-only request, so cross-tenant denial and complete runtime admission eligibility remain unproved. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 983a938543..c1cb7142d9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -214,6 +214,20 @@ private void requireGameSessionPeer() { } } + private void requireRuntimeEntitlementsPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String namespace = workloadNamespace; + if (peer == null + || namespace == null + || namespace.isBlank() + || !(peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service") + || peer.uri() + .equals("spiffe://firemud/ns/" + namespace + "/sa/world-management-service"))) { + throw new AdminAuthorizationException( + "Verified Game Session or World Management workload identity is required"); + } + } + private void requireSocialGroupsPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null @@ -588,9 +602,10 @@ public void getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getTenantEntitlementsForRuntime( - requirePositiveRequestId(request.getTenantId(), "tenantId"), request.getRequestId()); + requireRuntimeEntitlementsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + String requestId = requireText(request.getRequestId(), "requestId"); + var dto = accountService.getTenantEntitlementsForRuntime(tenantId, requestId); GetTenantEntitlementsForRuntimeResponse response = GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId(String.valueOf(dto.tenantId())) @@ -602,6 +617,14 @@ public void getTenantEntitlementsForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + GetTenantEntitlementsForRuntimeResponse response = + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + appError("GetTenantEntitlementsForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetTenantEntitlementsForRuntimeResponse response = GetTenantEntitlementsForRuntimeResponse.newBuilder() diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index fc69de24a6..b6849d344a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -86,6 +86,11 @@ class AccountGrpcServiceTest { "spiffe://firemud/ns/test/sa/social-groups-service", WORKLOAD_NAMESPACE, "social-groups-service"); + private static final GrpcPeerIdentity WORLD_MANAGEMENT_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/world-management-service", + WORKLOAD_NAMESPACE, + "world-management-service"); private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() @@ -1761,32 +1766,126 @@ void getTenantEntitlementsForRuntimeReturnsResponse() { .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertNotNull(observer.response()); + assertEquals("1", observer.response().getTenantId()); + assertTrue(observer.response().getGameplayAvailable()); + assertTrue(observer.response().getAllowPublicJoin()); + assertEquals(19L, observer.response().getEntitlementVersion()); + assertTrue(observer.completed()); + Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-2"); + } - @Override - public void onCompleted() {} - }); + @Test + void getTenantEntitlementsForRuntimeAllowsWorldManagementPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-world")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( + 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - assertNotNull(ref.get()); - assertEquals("1", ref.get().getTenantId()); - assertTrue(ref.get().getGameplayAvailable()); - assertTrue(ref.get().getAllowPublicJoin()); - assertEquals(19L, ref.get().getEntitlementVersion()); + withPeer( + WORLD_MANAGEMENT_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-world") + .build(), + observer)); + + assertEquals("1", observer.response().getTenantId()); + assertTrue(observer.completed()); + Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-world"); + } + + @Test + void getTenantEntitlementsForRuntimeRejectsAbsentWrongAndCrossNamespacePeers() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List rejectedPeers = + java.util.Arrays.asList( + null, + SOCIAL_GROUPS_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/world-management-service", + "other", + "world-management-service")); + + RecordingObserver absentPeerObserver = + new RecordingObserver<>(); + service.getTenantEntitlementsForRuntime(validEntitlementRequest(), absentPeerObserver); + assertEquals("PERMISSION_DENIED", absentPeerObserver.response().getError().getCode()); + for (GrpcPeerIdentity peer : rejectedPeers) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer( + peer, () -> service.getTenantEntitlementsForRuntime(validEntitlementRequest(), observer)); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + Mockito.verifyNoInteractions(accountService); + } + + @Test + void getTenantEntitlementsForRuntimeRejectsMalformedTenantOrRequestBeforeLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List malformedRequests = + List.of( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("0") + .setRequestId("req-1") + .build(), + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId(" ") + .build(), + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("x".repeat(129)) + .build()); + + for (GetTenantEntitlementsForRuntimeRequest request : malformedRequests) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer(GAME_SESSION_PEER, () -> service.getTenantEntitlementsForRuntime(request, observer)); + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + Mockito.verifyNoInteractions(accountService); + } + + private static GetTenantEntitlementsForRuntimeRequest validEntitlementRequest() { + return GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(); } @Test @@ -1798,26 +1897,30 @@ void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-ambiguous") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-ambiguous") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantEntitlementsForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertTrue(ref.get().hasError()); @@ -1828,26 +1931,30 @@ public void onCompleted() {} void getTenantEntitlementsForRuntimeRejectsZeroTenantIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("0") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("0") + .setRequestId("req-2") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantEntitlementsForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); From 151a38c82c7211d69cd6d897e3eb8cd4684d6ea3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:02:16 +1300 Subject: [PATCH 085/105] fix(gameplay): bind published namespace and canonical evidence precision --- .../game-design-service/README.md | 2 +- .../GameSessionTenantAssociationEvidence.java | 15 +++-- ...eSessionTenantAssociationEvidenceTest.java | 16 +++++ ...InitialAdmissionBindCatalogRepository.java | 2 +- .../V15__published_initial_admission_bind.sql | 11 +++- ...lAdmissionBindPostgresIntegrationTest.java | 62 +++++++++++++++---- ...itialAdmissionOwnerReadAuthWiringTest.java | 15 ++++- 7 files changed, 99 insertions(+), 24 deletions(-) diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index ccc0808efa..fff1dab9fb 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -16,7 +16,7 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved, because `GameAssetServiceImpl` uses `MultipartFile.getBytes()` without matching limits in `AssetStoreProperties`; upload admission and resource-safety readiness remain blocked. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. Publish/export later writes version-prefix objects and a manifest through the private object-store endpoint; target private-candidate/content-addressed publication and approved public `/assets/**` delivery remain unimplemented. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). -The owner-local tenant UUID read and the closed-v1 `REALM_ENTRY_POLICY` publication producer are implemented. Because `SaveRevision` appends policy history, publication now resolves each realm selector to its effective latest revision, so editing an existing policy does not create duplicate published rows or let older visibility flags affect the current publication. Full-version publication with no authored realm-policy revisions remains permitted for legacy behavior and provides no policy proof. Descriptor/template production and composition with Game Session's live catalog, pointer, namespace/scope, and Entity actor-entry paths remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused producer and schema-capacity cases are added but remain unrun; local PostgreSQL migration/readback execution remains unproved. See the exact API boundary in [API Contracts](./api-contracts.md#published-realm-entry-policy-owner-read) and the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). +The owner-local tenant UUID read and the closed-v1 `REALM_ENTRY_POLICY` publication producer are implemented. Because `SaveRevision` appends policy history, publication now resolves each realm selector to its effective latest revision, so editing an existing policy does not create duplicate published rows or let older visibility flags affect the current publication. Full-version publication with no authored realm-policy revisions remains permitted for legacy behavior and provides no policy proof. Descriptor/template production and composition with Game Session's live catalog, pointer, namespace/scope, and Entity actor-entry paths remain incomplete under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). Current producer proof status is tracked in the [Game authoring, publishing, and activation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md); local PostgreSQL migration/readback execution remains unproved. See the exact API boundary in [API Contracts](./api-contracts.md#published-realm-entry-policy-owner-read). ## Responsibilities diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java index a1a86bee31..094b4cde65 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java @@ -46,8 +46,8 @@ public record GameSessionTenantAssociationEvidence( requireLabel(signerKeyId, 128, "signerKeyId"); requireLabel(approvedBy, 256, "approvedBy"); requireLabel(approvalReference, 512, "approvalReference"); - requireCanonicalInstant(signedAt); - requireCanonicalInstant(sourceCapturedAt); + requireCanonicalInstant(signedAt, "signedAt"); + requireCanonicalInstant(sourceCapturedAt, "sourceCapturedAt"); if (Instant.parse(sourceCapturedAt).isAfter(Instant.parse(signedAt))) { throw new IllegalArgumentException("sourceCapturedAt may not follow signedAt"); } @@ -144,14 +144,17 @@ private static void requireLabel(String value, int maxUtf8Bytes, String label) { } } - private static void requireCanonicalInstant(String value) { - Objects.requireNonNull(value, "signedAt"); + private static void requireCanonicalInstant(String value, String label) { + Objects.requireNonNull(value, label); try { if (!Instant.parse(value).toString().equals(value)) { - throw new IllegalArgumentException("signedAt must be canonical UTC Instant text"); + throw new IllegalArgumentException(label + " must be canonical UTC Instant text"); + } + if (Instant.parse(value).getNano() % 1_000 != 0) { + throw new IllegalArgumentException(label + " must have microsecond precision"); } } catch (DateTimeParseException exception) { - throw new IllegalArgumentException("signedAt must be canonical UTC Instant text", exception); + throw new IllegalArgumentException(label + " must be canonical UTC Instant text", exception); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java index 73b98c0bf5..ee26feb640 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java @@ -92,6 +92,22 @@ void preservesApprovalTextExactlyAndRequiresCanonicalUtcInstant() { assertInvalid(() -> copySourceCapturedAt(evidence(), "2026-09-30T00:00:00+00:00")); } + @Test + void requiresCanonicalUtcMicrosecondPrecisionForBothEvidenceInstants() { + GameSessionTenantAssociationEvidence source = evidence(); + + assertThat(copySignedAt(source, "2026-10-01T00:00:00.123456Z").signedAt()) + .isEqualTo("2026-10-01T00:00:00.123456Z"); + assertThat(copySourceCapturedAt(source, "2026-09-30T00:00:00.123456Z").sourceCapturedAt()) + .isEqualTo("2026-09-30T00:00:00.123456Z"); + assertThatThrownBy(() -> copySignedAt(source, "2026-10-01T00:00:00.123456001Z")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("signedAt must have microsecond precision"); + assertThatThrownBy(() -> copySourceCapturedAt(source, "2026-09-30T00:00:00.123456001Z")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("sourceCapturedAt must have microsecond precision"); + } + @Test void expiresRawEvidenceAtTheExactThirtyDayCaptureBoundary() { GameSessionTenantAssociationEvidence source = evidence(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java index dd3a258aed..e84daf5e5b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java @@ -213,7 +213,7 @@ public PublishedRealmCatalogSnapshot materializePublishedSnapshot( } /** Reads the exact immutable published snapshot referenced by a catalog revision. */ - @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) + @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public Optional findPublishedSnapshot( String exactNamespace, long tenantId, long catalogRevision) { if (exactNamespace == null diff --git a/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql index d18f6828f6..2fbd6429e1 100644 --- a/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql +++ b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql @@ -4,6 +4,11 @@ ALTER TABLE gameplay_published_realm_catalog_snapshot ADD CONSTRAINT uq_gs_published_realm_catalog_snapshot_bind_identity UNIQUE (target_namespace, tenant_id, catalog_revision, canonical_tenant_id, version_id); +ALTER TABLE gameplay_published_realm_catalog_entry + ADD CONSTRAINT uq_gs_published_realm_catalog_entry_bind_identity + UNIQUE (target_namespace, tenant_id, catalog_revision, realm_id, + playable_state_namespace_id); + ALTER TABLE gameplay_initial_admission_bind_attempt ADD COLUMN catalog_source_kind character varying(16) NOT NULL DEFAULT 'V9_FIXTURE', ADD COLUMN fixture_catalog_realm_id uuid, @@ -32,9 +37,11 @@ ALTER TABLE gameplay_initial_admission_bind_attempt REFERENCES gameplay_published_realm_catalog_snapshot (target_namespace, tenant_id, catalog_revision, canonical_tenant_id, version_id), ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_entry_fk - FOREIGN KEY (published_target_namespace, tenant_id, catalog_revision, realm_id) + FOREIGN KEY (published_target_namespace, tenant_id, catalog_revision, realm_id, + playable_state_namespace_id) REFERENCES gameplay_published_realm_catalog_entry - (target_namespace, tenant_id, catalog_revision, realm_id), + (target_namespace, tenant_id, catalog_revision, realm_id, + playable_state_namespace_id), ADD CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_source_shape CHECK ( (catalog_source_kind = 'V9_FIXTURE' diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 93229f3ab2..fe72388ef3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -25,6 +25,8 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionProxyFactoryBean; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -166,8 +168,8 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { migrate(dataSource, schema); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - TransactionTemplate transactionTemplate = - new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); GameInstanceRepository gameInstanceRepository = new GameInstanceRepository(dsl); GameInstance runtime = gameInstance(); runtime.setLaunchDescriptorId("published-launch-v1"); @@ -179,18 +181,27 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { seedAssociation(dsl, 41L, CANONICAL_TENANT_ID, 731L, "source-game-key-not-local-id"); InitialAdmissionBindCatalogRepository catalogRepository = new InitialAdmissionBindCatalogRepository(dsl); + InitialAdmissionBindCatalogRepository transactionalCatalogRepository = + transactionalRepository(catalogRepository, transactionManager); PublishedRealmEntryPolicySetEvidence policySet = publishedPolicySet(); var snapshot = transactionTemplate.execute( - status -> - catalogRepository.materializePublishedSnapshot( - PUBLISHED_NAMESPACE, - 41L, - CANONICAL_TENANT_ID, - 731L, - "source-game-key-not-local-id", - "NEW_GAME_ROW", - policySet)); + status -> { + var materialized = + catalogRepository.materializePublishedSnapshot( + PUBLISHED_NAMESPACE, + 41L, + CANONICAL_TENANT_ID, + 731L, + "source-game-key-not-local-id", + "NEW_GAME_ROW", + policySet); + assertThat( + transactionalCatalogRepository.findPublishedSnapshot( + PUBLISHED_NAMESPACE, 41L, materialized.catalogRevision())) + .contains(materialized); + return materialized; + }); var entry = Objects.requireNonNull(snapshot).entries().getFirst(); DatabaseInitialAdmissionBindOwnerService service = new DatabaseInitialAdmissionBindOwnerService( @@ -217,6 +228,23 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { assertThat(dsl.fetchCount(DSL.table("gameplay_initial_admission_bind_catalog"))).isZero(); var attempt = transactionTemplate.execute(status -> service.beginIntent(request)); + assertThatThrownBy( + () -> + transactionTemplate.execute( + status -> + dsl.execute( + "UPDATE gameplay_initial_admission_bind_attempt " + + "SET playable_state_namespace_id = ? WHERE attempt_id = ?", + UUID.randomUUID(), + attempt.attemptId()))) + .isInstanceOf(RuntimeException.class); + assertThat( + dsl.fetchOne( + "SELECT playable_state_namespace_id " + + "FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", + attempt.attemptId()) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(entry.playableStateNamespaceId()); assertThatThrownBy( () -> transactionTemplate.execute( @@ -307,6 +335,18 @@ private static void migrate(DriverManagerDataSource dataSource, String schema) { .migrate(); } + private static InitialAdmissionBindCatalogRepository transactionalRepository( + InitialAdmissionBindCatalogRepository target, + DataSourceTransactionManager transactionManager) { + TransactionProxyFactoryBean proxyFactory = new TransactionProxyFactoryBean(); + proxyFactory.setTransactionManager(transactionManager); + proxyFactory.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + proxyFactory.setTarget(target); + proxyFactory.setProxyTargetClass(true); + proxyFactory.afterPropertiesSet(); + return (InitialAdmissionBindCatalogRepository) proxyFactory.getObject(); + } + private static GameInstance gameInstance() { GameInstance gameInstance = new GameInstance(); gameInstance.setTenantId(41L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java index 6167b64a2e..54511ebbd6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java @@ -371,7 +371,7 @@ private static void withConfiguredInterceptor( "game-session-application", new FileSystemResource("src/main/resources/application.yml")) .get(0); - context.getEnvironment().getPropertySources().addLast(application); + context.getEnvironment().getPropertySources().addFirst(application); if (productionProfile) { PropertySource production = loader @@ -379,17 +379,26 @@ private static void withConfiguredInterceptor( "game-session-production", new FileSystemResource("src/main/resources/application-prod.yml")) .get(0); - context.getEnvironment().getPropertySources().addLast(production); + context + .getEnvironment() + .getPropertySources() + .addBefore("game-session-application", production); } } catch (IOException exception) { throw new IllegalStateException( "Could not load Game Session auth config", exception); } }) - .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .withPropertyValues( + "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", + productionProfile ? "GAME_TICK_DURATION_MS=2500" : "GAME_TICK_DURATION_MS=1000") .run( context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + if (productionProfile) { + assertThat(context.getEnvironment().getProperty("game.tick-duration-ms")) + .isEqualTo("2500"); + } assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) .containsExactly(PING_METHOD, INITIAL_METHOD, PUBLISHED_METHOD); action.accept(context.getBean(AuthTokenInterceptor.class)); From 9efbab273ba196762804fe992678511a1b47d1fe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:17:55 +1300 Subject: [PATCH 086/105] fix(ci): carry Validation triggers to stacked JOIN PR --- .github/workflows/ci.yml | 1 - .../tests/pr-retarget-workflow-contract.sh | 21 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7031ff3417..d30a730f81 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..ccbb89354c 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,27 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Stacked feature-base PRs must reach normal Validation on every supported +# event; push scope and metadata/base-retarget job guards remain unchanged. +python3 - "$ci_path" <<'PYTHON' +import sys +from pathlib import Path + +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) +events = workflow["on"] +pr = events["pull_request"] +if set(pr) != {"types"}: + raise SystemExit("Validation PR triggers must not filter base branches or paths") +if set(pr["types"]) != {"opened", "synchronize", "reopened", "edited"}: + raise SystemExit("Validation must cover opens, new commits, reopenings, and base/metadata edits") +if events["push"] != {"branches": ["main", "develop"]}: + raise SystemExit("Validation push scope must remain main/develop only") +if "workflow_dispatch" not in events: + raise SystemExit("Validation must retain manual dispatch") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. From da91d4d78bda225840945cc96e255f368d357a59 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:33:16 +1300 Subject: [PATCH 087/105] fix: validate gameplay attestation account UUID identity --- .../GameplaySessionAttestationService.java | 15 +- ...GameplaySessionAttestationServiceTest.java | 145 ++++++++++++++---- 2 files changed, 130 insertions(+), 30 deletions(-) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java index 3a88de579d..4adf9db1e2 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java @@ -166,13 +166,15 @@ public void requireGameplaySessionMatch( } requirePositiveId(claims.tenantId(), "tenantId"); requirePositiveId(claims.sessionId(), "sessionId"); - requirePositiveId(claims.accountId(), "accountId"); + String accountUuid = requireCanonicalAccountUuid(claims.accountId(), "accountId"); requirePositiveId(claims.characterId(), "characterId"); requirePositiveId(claims.gameInstanceId(), "gameInstanceId"); requirePositiveId(claims.pointerVersion(), "pointerVersion"); requirePositiveEquals(claims.tenantId(), tenantId, "tenantId"); requireOptionalPositiveEquals(claims.sessionId(), sessionId, "sessionId"); - requireOptionalPositiveEquals(claims.accountId(), accountId, "accountId"); + if (StringUtils.hasText(accountId)) { + requireEquals(accountUuid, requireCanonicalAccountUuid(accountId, "accountId"), "accountId"); + } requireOptionalPositiveEquals(claims.characterId(), characterId, "characterId"); requireOptionalPositiveEquals(claims.gameInstanceId(), gameInstanceId, "gameInstanceId"); // roomInstanceId remains a routed room identifier string; keep text equality here. @@ -245,6 +247,15 @@ private long requirePositiveId(String value, String fieldName) { } } + private String requireCanonicalAccountUuid(String value, String fieldName) { + try { + return JwtClaims.requireCanonicalAccountUuid(value, fieldName); + } catch (IllegalArgumentException ex) { + throw new GameplaySessionAttestationException( + "SESSION_ATTESTATION_INVALID", ex.getMessage(), ex); + } + } + private String requireClaim(Claims claims, String name) { try { return JwtClaims.requireClaim(claims, name); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java index dd54a8783c..d29ee259f1 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java @@ -10,6 +10,8 @@ class GameplaySessionAttestationServiceTest { + private static final String ACCOUNT_UUID = "4a2df976-17b8-4c41-8d39-afe974913c16"; + private final JwtUtil jwtUtil; private final GameplaySessionAttestationService service; @@ -18,11 +20,34 @@ class GameplaySessionAttestationServiceTest { service = new GameplaySessionAttestationService(jwtUtil); } + @Test + void requireGameplaySessionMatchAcceptsCanonicalNonNilAccountUuid() { + String token = + service.issueGameplaySessionAttestation( + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + + assertDoesNotThrow( + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); + } + + @Test + void requireGameplaySessionMatchRejectsNumericMalformedNoncanonicalAndNilAccountClaims() { + assertInvalidAccountIdClaim(7, "Malformed claim: accountId"); + assertInvalidAccountIdClaim("7", "Malformed claim: accountId"); + assertInvalidAccountIdClaim("not-a-uuid", "Malformed claim: accountId"); + assertInvalidAccountIdClaim( + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), "Malformed claim: accountId"); + assertInvalidAccountIdClaim( + "00000000-0000-0000-0000-000000000000", "Malformed claim: accountId"); + } + @Test void requireGameplaySessionMatchAllowsOmittedOptionalDimensions() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); assertDoesNotThrow( () -> service.requireGameplaySessionMatch(token, "22", null, null, "123", "1", "R-1021")); @@ -32,13 +57,20 @@ void requireGameplaySessionMatchAllowsOmittedOptionalDimensions() { void requireGameplaySessionMatchStillRejectsProvidedMismatchedDimensions() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "99", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, + "22", + "41", + "78947a2b-1da8-4663-adb1-718fe4ff79aa", + "123", + "1", + "R-1021")); assertEquals("SESSION_ATTESTATION_MISMATCH", ex.getCode()); assertEquals("Gameplay session attestation does not match accountId", ex.getMessage()); @@ -48,23 +80,26 @@ void requireGameplaySessionMatchStillRejectsProvidedMismatchedDimensions() { void requireGameplaySessionMatchAllowsAlphanumericRoomInstanceId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); assertDoesNotThrow( - () -> service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); } @Test void requireGameplaySessionMatchRejectsMismatchedAlphanumericRoomInstanceId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-2045")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-2045")); assertEquals("SESSION_ATTESTATION_MISMATCH", ex.getCode()); assertEquals("Gameplay session attestation does not match roomInstanceId", ex.getMessage()); @@ -79,7 +114,7 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "room-1021"), @@ -92,7 +127,8 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("roomInstanceId must be a runtime room id like R-1021", ex.getMessage()); @@ -102,7 +138,7 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( @@ -112,7 +148,7 @@ void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { token, "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "R-1021", @@ -129,12 +165,14 @@ void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { void requireGameplaySessionMatchRejectsZeroTenantIdClaim() { String token = service.issueGameplaySessionAttestation( - "0", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "0", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, - () -> service.requireGameplaySessionMatch(token, "0", "41", "7", "123", "1", "R-1021")); + () -> + service.requireGameplaySessionMatch( + token, "0", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Invalid claim: tenantId", ex.getMessage()); @@ -144,13 +182,14 @@ void requireGameplaySessionMatchRejectsZeroTenantIdClaim() { void requireGameplaySessionMatchRejectsZeroPointerVersionClaim() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "0", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "0", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Invalid claim: pointerVersion", ex.getMessage()); @@ -165,7 +204,7 @@ void requireGameplaySessionMatchRejectsNonNumericClaimId() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "abc"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -178,7 +217,8 @@ void requireGameplaySessionMatchRejectsNonNumericClaimId() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Malformed claim: characterId", ex.getMessage()); @@ -193,7 +233,7 @@ void requireGameplaySessionMatchRejectsSubjectClaimMismatch() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -206,26 +246,57 @@ void requireGameplaySessionMatchRejectsSubjectClaimMismatch() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Gameplay session attestation subject does not match claims", ex.getMessage()); } @Test - void requireGameplaySessionMatchRejectsNonPositiveExpectedAccountId() { + void requireGameplaySessionMatchRejectsNumericExpectedAccountId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", null, "0", "123", "1", "R-1021")); + service.requireGameplaySessionMatch(token, "22", null, "7", "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); - assertEquals("Invalid claim: accountId", ex.getMessage()); + assertEquals("Malformed claim: accountId", ex.getMessage()); + } + + private void assertInvalidAccountIdClaim(Object accountId, String expectedMessage) { + String token = tokenWithAccountId(accountId); + GameplaySessionAttestationException ex = + assertThrows( + GameplaySessionAttestationException.class, + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); + + assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); + assertEquals(expectedMessage, ex.getMessage()); + } + + private String tokenWithAccountId(Object accountId) { + return jwtUtil.generateToken( + "gameplay-session:41", + Map.ofEntries( + Map.entry("attestationType", "GAMEPLAY_SESSION"), + Map.entry("tenantId", "22"), + Map.entry("sessionId", "41"), + Map.entry("accountId", accountId), + Map.entry("characterId", "123"), + Map.entry("gameInstanceId", "1"), + Map.entry("roomInstanceId", "R-1021"), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("pointerVersion", "17"), + Map.entry("playableStateScope", "SHARED"))); } @Test @@ -331,7 +402,7 @@ void issueGameplaySessionAttestationRejectsLegacyRuntimeRoomId() { service.issueGameplaySessionAttestation( "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "room-1021", @@ -371,7 +442,16 @@ void requireAdmittedRoutingBundleAcceptsGameplayAttestationWithRoutingClaims() { GameplaySessionAttestationClaims claims = service.requireValid( service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED")); + "22", + "41", + ACCOUNT_UUID, + "123", + "1", + "R-1021", + "demo", + "production", + "17", + "SHARED")); assertDoesNotThrow(() -> service.requireAdmittedRoutingBundle(claims)); } @@ -386,7 +466,7 @@ void requireAdmittedRoutingBundleRejectsGameplayAttestationMissingPointerVersion Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -411,7 +491,16 @@ void issueGameplaySessionAttestationRejectsMissingRoutingBundleClaims() { IllegalArgumentException.class, () -> service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", null, "production", null, "SHARED")); + "22", + "41", + ACCOUNT_UUID, + "123", + "1", + "R-1021", + null, + "production", + null, + "SHARED")); assertEquals("worldSlug must not be blank", ex.getMessage()); } @@ -425,7 +514,7 @@ void requireValidUsesCanonicalIterableClaimParsing() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", List.of(" ", "22")), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", List.of("", "R-1021")), From 989e08f1f1aea5d2c8fcb65a70bcbf44eab486a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:42:11 +1300 Subject: [PATCH 088/105] fix(gameplay): resolve shared namespace transitions and prove bind outcomes --- ...ame-authoring-publishing-and-activation.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 4 +- .../player-access-and-session.md | 4 +- ...tAssociationRepositoryIntegrationTest.java | 13 +- ...InitialAdmissionBindCatalogRepository.java | 44 +- ...tAssociationRepositoryIntegrationTest.java | 6 +- ...RealmCatalogRepositoryIntegrationTest.java | 124 +++- ...lmInitialAdmissionBindCoordinatorTest.java | 614 ++++++++++++++++++ 8 files changed, 791 insertions(+), 20 deletions(-) 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 162a74406b..00b286f1db 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 @@ -10,7 +10,7 @@ This tracker consolidates Game Design authoring, settings, publication, release Game Design issues a canonical tenant UUID with exact Game row/source-key provenance and exposes the authenticated `ResolveRuntimeTenantIdentity` read. V29 assigns retained identities only to bounded, nonblank owner keys and leaves malformed retained rows quarantined; issuance and source provenance are immutable. The closed-v1 `REALM_ENTRY_POLICY` producer accepts version-scoped revisions, freezes immutable policy rows transactionally with full-version release-bundle creation, and exposes same-namespace authenticated exact-row and bounded complete-set reads with owner-bound evidence. The canonical producer rules are in the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read); focused proof status and anchors are recorded under `AR-1.5` below. Local PostgreSQL migration/readback execution remains unproved. This producer and complete-set evidence do not establish current Game Session catalog validity, pointer/namespace/scope composition, descriptor/template identity, Entity actor admission, or actor creation/activation. Actor-entry behavior remains incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). -The separate retained Game Session tenant-association prerequisite keeps immutable source-row/key/provenance and namespace/canonical/private-key claims while V32 moves signed approval labels, signature, and source-linked digests into an owner-local 30-day capture-expiring payload. V2 evidence binds the exact GS source capture time and both snapshot digests; retries do not renew expiry. Automatic bounded cleanup preserves terminal anti-reassignment rows. Hold audit references the immutable association claim, not erasable raw payload, and therefore survives payload cleanup. Under ADR 0050/0163 it is separate purpose-bound safety evidence requiring finite post-release retention/export/erasure policy; that schedule and a trusted authenticated owner policy are not implemented, so hold create/release remain fail-closed with no generic audit exemption. Test fixtures prove cleanup/reference behavior only, not authorization. Game Session's mapping-only internal read remains independent of expired/erased raw evidence. This prerequisite is not runtime catalog/admission authority and does not enable activation or public endpoints. Its focused validation and PostgreSQL/restore-proof limits are recorded in the owning service docs and [Player Access and Session](./player-access-and-session.md#current-status). +The retained Game Session tenant-association prerequisite now has a signed Game Design owner receipt/read and a Game Session immutable mapping receiver. Focused tests cover provenance, bounded cleanup, and retained mapping behavior; PostgreSQL migration/readback and restore proof remain outstanding. Hold create/release remain fail-closed pending finite post-release retention policy and authenticated owner authorization; cleanup fixtures do not prove authorization. The mapping is identity evidence only and does not establish runtime catalog/admission authority or activation. See the canonical [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#audited-retained-game-session-tenant-association), [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#audited-retained-tenant-association-nonactivating), and [Player Access and Session](./player-access-and-session.md#current-status). 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. 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 5af3e40bd5..7e69ffd388 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,9 +14,9 @@ Retained bootstrap correction: V8 recognizes only the unchanged, provenance-back Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. -Published realm-policy receiving/catalog preparation: the lazy internal owner stages immutable snapshots from the complete Game Design policy set plus the committed local tenant association, with source-provenance validation and distinct local-private-tenant versus source-row identities. Tenant-wide `realmSlug` identity supports stable opaque namespaces for proven `SHARED` entries; catalog-only policy/display changes advance `catalogRevision` while preserving exact prior snapshots. Lifecycle resolution gates only the selected entry: an `ISOLATED` entry without an owner-proven canonical playtest lifecycle ID and positive playtest-state generation has no namespace or initial-bind read, without blocking a proven shared entry. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md), [owner service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java), [snapshot](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/PublishedRealmCatalogSnapshot.java), and [owner-service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). +Published realm-policy receiving is implemented by a lazy Game Session owner that stages snapshots from authenticated Game Design reads and the committed local tenant association, rejecting source-provenance mismatches. Focused owner/client proof is recorded in the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status); PostgreSQL and end-to-end lifecycle/catalog proof remain outstanding. The canonical [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#published-realm-entry-policy-owner-read) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) own the target boundaries; this preparation does not implement strict actor entry or `PLAY` admission. See the [catalog owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerService.java) and [owner-service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmCatalogOwnerServiceTest.java). -Published-snapshot initial-bind composition: the explicit internal coordinator consumes that immutable V14 snapshot and exact visible public `SHARED` `PRESEEDED_ONLY` entry, then cross-checks authored launch and World's exact ACTIVE lifecycle readback, including template, descriptor, version, release-bundle ID/reference, version-state epoch, and lifecycle epoch. It fails closed before authored launch when the Game Design source row ID differs from the retained local GS tenant ID: the existing authored-launch API passes one numeric tenant ID to both local ownership and Game Design descriptor lookup, so a source/local-aware launch adapter remains a prerequisite for those associations. The World `publishedReleaseBundleRef` is retained as separate launch evidence alongside the V14 release digest, without inferred identity conversion. V15 links new `V14_PUBLISHED` attempts to the exact snapshot and entry while retaining historical V9 attempts as `V9_FIXTURE`; the owner writes `PRESEEDED_ONLY` directly and conservatively sets the legacy `requiresCharacterSelection` pointer field true. No startup/environment trigger or raw fixture promotion is added. Ten focused Game Session tests passed on 2026-10-04, covering bind, historical/published repository decoding, unequal-source launch denial, and owner-read composition; PostgreSQL integration sources compiled, but PostgreSQL execution, restart/lost-response/finalize ambiguity and live World-held bind remain unproved. The internal owner read composes the unchanged first pointer, matching audit and committed published attempt; it is not fresh World ACTIVE proof or a validation-through-commit gate, and authenticated receiving transport remains unwired. This code does not implement strict Account `JOIN`, actor/roster validation, or `PLAY` admission. See the [coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java), [V15 migration](../../../services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql), and [API contract status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). +Published-snapshot initial-bind composition is implemented by the internal coordinator for the exact V14 snapshot entry and records the matching pointer, audit, and bind attempt together after authored-launch and World-lifecycle readback. It fails closed before authored launch when Game Design's source row ID differs from Game Session's retained local tenant ID because the current launch API accepts one numeric ID for both roles; a source/local-aware adapter remains a prerequisite for those associations. Ten focused Game Session tests passed on 2026-10-04; PostgreSQL execution, restart/lost-response/finalize ambiguity, and live World-held bind remain unproved. The shared-interceptor authentication wiring proof remains pending. Strict Account `JOIN`, actor/roster validation, and `PLAY` admission are not implemented. See the [coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinator.java), [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind), and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). Initial-admission owner boundary: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). 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 4905838385..9a4297ba56 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,9 +10,9 @@ Account's persisted UUID backs registration REST/gRPC output and the Account com This candidate now carries Account UUID through Account authentication, bootstrap, and profile producers; Common Security subject/account matching; Gateway gameplay-handshake validation; and Game Session and Game Logic carriers. Reported focused unit and formatting tasks passed for Account, Common Security, Gateway, Game Logic, and Game Design; the focused Game Session suite passed 262/262. This is candidate source/test proof, not deployed or fresh-runtime proof, and it does not establish global convergence of numeric Account consumers or backfill historical command UUIDs. Canonical identity and namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Account's `ResolveRuntimeAccountIdentity` owner read has focused service proof (7/7) and auth-wiring proof (3/3); Entity Management's Account identity receiver test passed 7/7. Those reads carry persisted UUID and source-row/provenance evidence but do not create membership, grants, actor ownership, a namespace, or admission authority; Game Session caller wiring remains unclaimed. Focused Game Session proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. Game Session now rejects unreadable or wrong-type registry evidence before persisted-context fallback and preserves numeric/opaque account evidence without mutation. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. `PLAYER`/`PLAY`, actor association/namespace roster, and full-stack fresh-smoke proof remain incomplete. #2898 remains unresolved. -The Game Design canonical tenant UUID/provenance producer and its Game Session receiver are prepared in a separate retained-tenant association prerequisite, not this Account UUID carrier slice. That prerequisite must prove source identity and exact retained-row association without establishing the current Game Session pointer, playable-state namespace/scope, published actor-entry policy, Entity selection, or actor creation. `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +The Game Design tenant-UUID producer and Game Session's retained-association receiver provide a separate identity-evidence prerequisite for this Account UUID carrier slice. Focused provenance and receiver tests exist, while PostgreSQL migration/readback and restore proof remain outstanding. This association does not establish the Game Session pointer, playable-state namespace/scope, actor selection, or actor creation. `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); see the [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#audited-retained-game-session-tenant-association) and [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#audited-retained-tenant-association-nonactivating). -The retained-tenant association prerequisite now has a signed Game Design owner receipt/read (V30 + forward V32 payload-retention migration) and a Game Session local immutable association/snapshot receiver (V12 + forward V13 payload-retention migration). Schema-4 snapshot and signed-evidence-v2 bind one authoritative source capture time; account-linked raw snapshot, approval and digests have a 30-day capture-based lifetime with bounded owner cleanup, while minimal immutable namespace/UUID/private-key/provenance claims remain for anti-reassignment. The internal Game Session proof read is `readMinimalAssociation(exactNamespace, canonicalTenantId)` and returns only that mapping/provenance. Expired or restored stale raw evidence fails closed and old ambiguous evidence requires recapture. Hold audit now references the immutable mapping so raw cleanup cannot cascade away create/release evidence; it is separate purpose-bound safety evidence, not retained RAW payload. Its finite post-release retention/export/erasure schedule and authenticated owner policy are not implemented, so create/release remain fail-closed and no hold extension is operational. PostgreSQL fixtures exercise blocker/release cleanup only by seeding owner rows with the guard trigger temporarily disabled; this is not authorization proof. Restore cleanup gating and backup artifact rewriting are not proved. This audited mapping remains unwired and does not create pointers, rosters, actor selection, membership, `PLAY`, or public endpoints. PostgreSQL migration/readback execution remains unproved when Docker is unavailable; this does not change `AA-2.1` status. +The mapping-only Game Session read returns the committed local association and provenance, and catalog preparation consumes that evidence; it does not grant player admission or create actor state. Hold create/release remain fail-closed until the separate finite retention/export/erasure policy and authenticated owner authorization exist. PostgreSQL migration/readback, restore cleanup gating, and backup artifact handling remain unproved; seeded cleanup fixtures are not authorization proof. Detailed retention and owner-boundary behavior stays with the [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#audited-retained-game-session-tenant-association) and [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#audited-retained-tenant-association-nonactivating). `AA-2.1` remains `partial` / `drift-found`. Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index 71d71c97a2..8cf08cf9f7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -444,6 +444,15 @@ void databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInse .dsl() .execute("TRUNCATE game_design_game_session_tenant_association_operations")) .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "TRUNCATE game_design_game_session_tenant_association_operations, " + + "game_design_game_session_tenant_association_payload")) + .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); assertThatThrownBy( @@ -482,7 +491,7 @@ private AssociationReceipt concurrentApply( private Fixture fixtureWithFreshAndRetainedSources() throws Exception { String schema = "game_design_gs_assoc_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); - migrate(dataSource, schema, MigrationVersion.fromVersion("29")); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); DSLContext legacyDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); Long retainedGameId = @@ -632,7 +641,7 @@ void insertRawPayload(UUID operationId, int schemaVersion, String projectionDige + "manifest_digest, signature) VALUES (?, ?, 'owner-key', 'owner', 'case', ?, ?, ?, ?, ?)", operationId, schemaVersion, - java.time.Instant.now().toString(), + java.time.Instant.now().truncatedTo(ChronoUnit.MICROS).toString(), projectionDigest, "sha256:" + "b".repeat(64), "sha256:" + "c".repeat(64), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java index e84daf5e5b..0e610519cb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java @@ -566,27 +566,51 @@ private NamespaceAssignment resolveNamespace( .fetchOne(); RealmEntryPolicy policy = evidence.policy(); if (previous != null) { - String previousScope = Objects.requireNonNull(previous.get(STATE_SCOPE)); + RealmEntryPolicy.StateScope previousScope; NamespaceResolution previousResolution; try { + previousScope = + RealmEntryPolicy.StateScope.valueOf(Objects.requireNonNull(previous.get(STATE_SCOPE))); previousResolution = NamespaceResolution.valueOf(Objects.requireNonNull(previous.get(NAMESPACE_RESOLUTION))); - } catch (IllegalArgumentException exception) { + } catch (IllegalArgumentException | NullPointerException exception) { throw new IllegalStateException( "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior namespace state is unsupported", exception); } - if (!previousScope.equals(policy.stateScope().name()) - || previousResolution != NamespaceResolution.RESOLVED - || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED) { - return new NamespaceAssignment(null, NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + + UUID previousNamespace = previous.get(PLAYABLE_STATE_NAMESPACE_ID); + if (!canonicalTenantId.equals(previous.get(CANONICAL_TENANT_ID)) + || (previousResolution == NamespaceResolution.RESOLVED + && (previousScope != RealmEntryPolicy.StateScope.SHARED + || previousNamespace == null + || previousNamespace.equals(NIL_UUID))) + || (previousResolution == NamespaceResolution.AWAITING_LIFECYCLE_PROOF + && previousNamespace != null)) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior namespace proof is inconsistent"); } - UUID previousNamespace = Objects.requireNonNull(previous.get(PLAYABLE_STATE_NAMESPACE_ID)); - if (previousNamespace.equals(NIL_UUID)) { + + if (previousScope == RealmEntryPolicy.StateScope.SHARED + && previousResolution == NamespaceResolution.RESOLVED + && !previousNamespace.equals( + getOrCreateCanonicalTenantSharedNamespace(exactNamespace, canonicalTenantId))) { throw new IllegalStateException( - "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior namespace is nil"); + "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior shared namespace differs from tenant authority"); } - return new NamespaceAssignment(previousNamespace, NamespaceResolution.RESOLVED); + + if (policy.stateScope() != RealmEntryPolicy.StateScope.SHARED) { + return new NamespaceAssignment(null, NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + } + + if (previousScope == RealmEntryPolicy.StateScope.SHARED + && previousResolution == NamespaceResolution.RESOLVED) { + return new NamespaceAssignment(previousNamespace, NamespaceResolution.RESOLVED); + } + + return new NamespaceAssignment( + getOrCreateCanonicalTenantSharedNamespace(exactNamespace, canonicalTenantId), + NamespaceResolution.RESOLVED); } if (policy.stateScope() != RealmEntryPolicy.StateScope.SHARED) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index a29dea29d5..b0c7cda283 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -871,8 +871,10 @@ AssociationReceipt register( Record storedByRequest(UUID associationRequestId) { return dsl.fetchOne( - "SELECT * FROM game_session_retained_tenant_association " - + "WHERE target_namespace = ? AND association_request_id = ?", + "SELECT association.*, payload.approval_manifest_digest, payload.approval_signature " + + "FROM game_session_retained_tenant_association association " + + "JOIN game_session_retained_tenant_association_payload payload USING (operation_id) " + + "WHERE association.target_namespace = ? AND association.association_request_id = ?", NAMESPACE, associationRequestId); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java index 70e8550468..4c318bc85e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PublishedRealmCatalogRepositoryIntegrationTest.java @@ -183,6 +183,128 @@ void snapshotsRetryExactlyKeepStableRealmAndSharedIdentityAndGateLifecycleTransi assertThat(fixture.dsl().fetchCount(ADMISSION_POINTER)).isEqualTo(originalPointerCount); } + @Test + void scopeTransitionsResolveOnlyTheCurrentTenantSharedNamespaceAndKeepPriorSnapshotsImmutable() { + Fixture fixture = fixture(); + fixture.seedAssociation(TENANT_ID, CANONICAL_TENANT_ID, 501L, "source-game-501"); + + PublishedRealmCatalogSnapshot sharedBeforeIsolation = + fixture.materialize( + TENANT_ID, + evidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501", 110L, 1, "Main", "SHARED")); + UUID tenantSharedNamespace = + sharedBeforeIsolation.entries().stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow() + .requirePlayableStateNamespaceId(); + + PublishedRealmCatalogSnapshot isolatedTransition = + fixture.materialize( + TENANT_ID, + evidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501", 111L, 2, "Main", "ISOLATED")); + var isolatedSide = + isolatedTransition.entries().stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow(); + assertThat(isolatedSide.namespaceResolution()) + .isEqualTo(NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + assertThat(isolatedSide.playableStateNamespaceId()).isNull(); + + PublishedRealmCatalogSnapshot sharedAfterIsolation = + fixture.materialize( + TENANT_ID, + evidenceSet(CANONICAL_TENANT_ID, 501L, "source-game-501", 112L, 3, "Main", "SHARED")); + var sharedSideAfterIsolation = + sharedAfterIsolation.entries().stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow(); + assertThat(sharedSideAfterIsolation.namespaceResolution()) + .isEqualTo(NamespaceResolution.RESOLVED); + assertThat(sharedSideAfterIsolation.requirePlayableStateNamespaceId()) + .isEqualTo(tenantSharedNamespace); + + fixture.seedAssociation(OTHER_TENANT_ID, OTHER_CANONICAL_TENANT_ID, 502L, "source-game-502"); + PublishedRealmCatalogSnapshot initiallyIsolated = + fixture.materialize( + OTHER_TENANT_ID, + evidenceSet( + OTHER_CANONICAL_TENANT_ID, 502L, "source-game-502", 210L, 1, "Main", "ISOLATED")); + var initiallyIsolatedSide = + initiallyIsolated.entries().stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow(); + assertThat(initiallyIsolatedSide.namespaceResolution()) + .isEqualTo(NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + assertThat(initiallyIsolatedSide.playableStateNamespaceId()).isNull(); + + PublishedRealmCatalogSnapshot isolatedThenShared = + fixture.materialize( + OTHER_TENANT_ID, + evidenceSet( + OTHER_CANONICAL_TENANT_ID, 502L, "source-game-502", 211L, 2, "Main", "SHARED")); + UUID otherTenantSharedNamespace = + isolatedThenShared.entries().stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("main")) + .findFirst() + .orElseThrow() + .requirePlayableStateNamespaceId(); + var isolatedThenSharedSide = + isolatedThenShared.entries().stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow(); + assertThat(isolatedThenSharedSide.namespaceResolution()) + .isEqualTo(NamespaceResolution.RESOLVED); + assertThat(isolatedThenSharedSide.requirePlayableStateNamespaceId()) + .isEqualTo(otherTenantSharedNamespace) + .isNotEqualTo(tenantSharedNamespace); + + var storedSharedBeforeIsolation = + fixture + .repository + .findPublishedSnapshot(NAMESPACE, TENANT_ID, 1L) + .orElseThrow() + .entries() + .stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow(); + var storedIsolatedTransition = + fixture + .repository + .findPublishedSnapshot(NAMESPACE, TENANT_ID, 2L) + .orElseThrow() + .entries() + .stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow(); + var storedInitiallyIsolated = + fixture + .repository + .findPublishedSnapshot(NAMESPACE, OTHER_TENANT_ID, 1L) + .orElseThrow() + .entries() + .stream() + .filter(entry -> entry.policyEvidence().policy().realmSlug().equals("side")) + .findFirst() + .orElseThrow(); + assertThat(storedSharedBeforeIsolation.namespaceResolution()) + .isEqualTo(NamespaceResolution.RESOLVED); + assertThat(storedSharedBeforeIsolation.requirePlayableStateNamespaceId()) + .isEqualTo(tenantSharedNamespace); + assertThat(storedIsolatedTransition.namespaceResolution()) + .isEqualTo(NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + assertThat(storedIsolatedTransition.playableStateNamespaceId()).isNull(); + assertThat(storedInitiallyIsolated.namespaceResolution()) + .isEqualTo(NamespaceResolution.AWAITING_LIFECYCLE_PROOF); + assertThat(storedInitiallyIsolated.playableStateNamespaceId()).isNull(); + } + @Test void persistedSnapshotOrdersAsciiPunctuationByWorldThenRealmSlug() { Fixture fixture = fixture(); @@ -475,7 +597,7 @@ void seedAssociation( + "(operation_id, target_namespace, association_request_id, " + "legacy_game_session_tenant_id, canonical_tenant_id, source_game_row_id, " + "source_game_tenant_key, provenance_kind, captured_at, terminal_outcome) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, clock_timestamp(), 'ASSOCIATED')", + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, 'ASSOCIATED')", UUID.randomUUID(), NAMESPACE, UUID.randomUUID(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java index 55de829fbb..845c859d20 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PublishedRealmInitialAdmissionBindCoordinatorTest.java @@ -1,26 +1,52 @@ 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.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; 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 java.time.Instant; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; 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.entitymanagement.v1.PlayableStateScope; 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.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry; import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogEntry.NamespaceResolution; import net.firedevops.firemud.gamesession.entity.PublishedRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; import net.firedevops.firemud.gamesession.service.PublishedRealmCatalogOwnerService; import net.firedevops.firemud.gamesession.service.PublishedRealmInitialAdmissionBindCommand; import net.firedevops.firemud.gamesession.service.PublishedRealmInitialAdmissionBindCoordinator; +import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import tools.jackson.databind.ObjectMapper; class PublishedRealmInitialAdmissionBindCoordinatorTest { @@ -31,6 +57,22 @@ class PublishedRealmInitialAdmissionBindCoordinatorTest { private static final long LOCAL_GAME_SESSION_TENANT_ID = 41L; private static final long SOURCE_GAME_ROW_ID = 731L; private static final long PUBLISHED_VERSION_ID = 902L; + private static final long GAME_TEMPLATE_ID = 12L; + private static final long OWNER_ACCOUNT_ID = 88L; + private static final long GAME_INSTANCE_ID = 73L; + private static final long ACTIVE_LIFECYCLE_EPOCH = 4L; + private static final long CATALOG_REVISION = 5L; + private static final String TARGET_NAMESPACE = "gameplay-test"; + private static final String INITIAL_ADMISSION_REQUEST_ID = "66666666-6666-4666-8666-666666666666"; + private static final UUID HOLD_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID HOLD_FENCE = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID ATTEMPT_ID = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID WRONG_ATTEMPT_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID WRONG_REALM_ID = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String LAUNCH_DESCRIPTOR_ID = "launch-descriptor-1"; + private static final String PUBLISHED_RELEASE_BUNDLE_REF = "release-bundle:903"; private static final ObjectMapper JSON = new ObjectMapper(); @Test @@ -63,6 +105,578 @@ void distinctSourceAndLocalTenantIdsFailBeforeAuthoredLaunchOrWorldHold() { verifyNoInteractions(gameInstanceService, ownerService, worldManagementClient); } + @Test + void matchingRetryableHoldStatusesAttachThenCommitTheExactOwnerBinding() { + for (InitialAdmissionBindHoldStatus status : + List.of( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, + InitialAdmissionBindHoldStatus + .INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED)) { + Fixture fixture = fixture(status); + + var result = fixture.coordinator().coordinate(fixture.command()); + + InitialAdmissionBindRequest request = verifyLaunchAndIntent(fixture); + InitialAdmissionBindHoldBinding expectedBinding = expectedBinding(request.requestDigest()); + assertThat(result) + .isEqualTo( + new PublishedRealmInitialAdmissionBindCoordinator.Result( + PublishedRealmInitialAdmissionBindCoordinator.TerminalOutcome.COMMITTED, + terminalProof(expectedBinding, Outcome.COMMITTED))); + verify(fixture.ownerService()).attachHold(expectedBinding); + verify(fixture.ownerService()).commit(expectedBinding); + verify(fixture.ownerService(), never()).read(any()); + verify(fixture.ownerService(), never()).abort(any()); + verifyNoMoreInteractions(fixture.ownerService()); + verifyNoUnexpectedHoldInputs(fixture, request); + } + } + + @Test + void matchingCommittedAndAbortedHoldsAcceptOnlyTheirExactTerminalOwnerProofs() { + for (var terminal : + List.of( + new TerminalCase( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED, + Outcome.COMMITTED, + PublishedRealmInitialAdmissionBindCoordinator.TerminalOutcome.COMMITTED), + new TerminalCase( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED, + Outcome.ABORTED, + PublishedRealmInitialAdmissionBindCoordinator.TerminalOutcome.ABORTED))) { + Fixture fixture = fixture(terminal.holdStatus()); + when(fixture.ownerService().read(any())) + .thenAnswer( + invocation -> + terminalProof( + invocation.getArgument(0), + terminal.ownerOutcome(), + ATTEMPT_ID.toString(), + terminal.ownerOutcome() == Outcome.COMMITTED ? "93" : null, + terminal.ownerOutcome() == Outcome.COMMITTED ? 1L : 0L, + terminal.ownerOutcome() == Outcome.COMMITTED + ? invocation + .getArgument(0, InitialAdmissionBindHoldBinding.class) + .requestDigest() + : null, + terminal.ownerOutcome() == Outcome.ABORTED)); + + var result = fixture.coordinator().coordinate(fixture.command()); + + InitialAdmissionBindRequest request = verifyLaunchAndIntent(fixture); + InitialAdmissionBindHoldBinding expectedBinding = expectedBinding(request.requestDigest()); + assertThat(result) + .isEqualTo( + new PublishedRealmInitialAdmissionBindCoordinator.Result( + terminal.resultOutcome(), + terminalProof(expectedBinding, terminal.ownerOutcome()))); + verify(fixture.ownerService()).read(expectedBinding); + verify(fixture.ownerService(), never()).attachHold(any()); + verify(fixture.ownerService(), never()).commit(any()); + verify(fixture.ownerService(), never()).abort(any()); + verifyNoMoreInteractions(fixture.ownerService()); + verifyNoUnexpectedHoldInputs(fixture, request); + } + } + + @Test + void committedAndAbortedHoldProofsWithInvalidTerminalEvidenceAreRejectedWithoutCommit() { + for (var rejected : + List.of( + new TerminalCase( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED, + Outcome.COMMITTED, + PublishedRealmInitialAdmissionBindCoordinator.TerminalOutcome.COMMITTED), + new TerminalCase( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED, + Outcome.ABORTED, + PublishedRealmInitialAdmissionBindCoordinator.TerminalOutcome.ABORTED))) { + Fixture fixture = fixture(rejected.holdStatus()); + when(fixture.ownerService().read(any())) + .thenAnswer( + invocation -> + terminalProof( + invocation.getArgument(0), + rejected.ownerOutcome(), + rejected.ownerOutcome() == Outcome.COMMITTED + ? WRONG_ATTEMPT_ID.toString() + : ATTEMPT_ID.toString(), + rejected.ownerOutcome() == Outcome.COMMITTED ? "93" : null, + rejected.ownerOutcome() == Outcome.COMMITTED ? 1L : 0L, + rejected.ownerOutcome() == Outcome.COMMITTED + ? invocation + .getArgument(0, InitialAdmissionBindHoldBinding.class) + .requestDigest() + : null, + false)); + + assertThatThrownBy(() -> fixture.coordinator().coordinate(fixture.command())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("INITIAL_ADMISSION_OWNER_PROOF_UNRESOLVED"); + + InitialAdmissionBindRequest request = verifyLaunchAndIntent(fixture); + verify(fixture.ownerService()).read(expectedBinding(request.requestDigest())); + verify(fixture.ownerService(), never()).attachHold(any()); + verify(fixture.ownerService(), never()).commit(any()); + verify(fixture.ownerService(), never()).abort(any()); + verifyNoMoreInteractions(fixture.ownerService()); + verifyNoUnexpectedHoldInputs(fixture, request); + } + } + + @Test + void mismatchedHoldTupleOrLifecycleEpochCannotReachOwnerAttachmentOrCommit() { + for (boolean mismatchLifecycleEpoch : List.of(false, true)) { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + when(fixture + .worldManagementClient() + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong())) + .thenAnswer( + invocation -> { + String requestDigest = invocation.getArgument(5); + InitialAdmissionBindHold.Builder hold = + exactHold( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, + requestDigest); + if (mismatchLifecycleEpoch) { + hold.setActiveLifecycleEpoch(ACTIVE_LIFECYCLE_EPOCH + 1L); + } else { + hold.setRealmUuid(WRONG_REALM_ID.toString()); + } + return AcquireInitialAdmissionBindHoldResponse.newBuilder().setHold(hold).build(); + }); + + assertThatThrownBy(() -> fixture.coordinator().coordinate(fixture.command())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("INITIAL_ADMISSION_WORLD_HOLD_MISMATCH"); + + InitialAdmissionBindRequest request = verifyLaunchAndIntent(fixture); + verifyNoOwnerMutationAfterIntent(fixture); + verifyNoUnexpectedHoldInputs(fixture, request); + } + } + + @Test + void launchAndWorldLifecycleEpochMismatchStopsBeforeIntentOrHoldMutation() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + when(fixture + .worldManagementClient() + .getWorldInstanceLifecycle(LOCAL_GAME_SESSION_TENANT_ID, GAME_INSTANCE_ID)) + .thenReturn(activeLifecycle(ACTIVE_LIFECYCLE_EPOCH + 1L)); + + assertThatThrownBy(() -> fixture.coordinator().coordinate(fixture.command())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("INITIAL_ADMISSION_WORLD_LIFECYCLE_MISMATCH"); + + verify(fixture.catalogOwner()) + .materializePublishedSnapshot(CANONICAL_TENANT_ID, PUBLISHED_VERSION_ID); + verify(fixture.gameInstanceService()) + .startRunOwnedInitialLaunch( + new StartSessionRequest( + LOCAL_GAME_SESSION_TENANT_ID, + GAME_TEMPLATE_ID, + INITIAL_ADMISSION_REQUEST_ID, + OWNER_ACCOUNT_ID)); + verify(fixture.worldManagementClient()) + .getWorldInstanceLifecycle(LOCAL_GAME_SESSION_TENANT_ID, GAME_INSTANCE_ID); + verify(fixture.worldManagementClient(), never()) + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong()); + verifyNoMoreInteractions( + fixture.catalogOwner(), fixture.gameInstanceService(), fixture.worldManagementClient()); + verifyNoInteractions(fixture.ownerService()); + } + + @Test + void unspecifiedWorldHoldStatusFailsClosedBeforeOwnerAttachmentOrCommit() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED); + + assertThatThrownBy(() -> fixture.coordinator().coordinate(fixture.command())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("INITIAL_ADMISSION_WORLD_HOLD_MISMATCH"); + + InitialAdmissionBindRequest request = verifyLaunchAndIntent(fixture); + verifyNoOwnerMutationAfterIntent(fixture); + verifyNoUnexpectedHoldInputs(fixture, request); + } + + private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { + PublishedRealmCatalogOwnerService catalogOwner = mock(PublishedRealmCatalogOwnerService.class); + GameInstanceService gameInstanceService = mock(GameInstanceService.class); + InitialAdmissionBindOwnerService ownerService = mock(InitialAdmissionBindOwnerService.class); + WorldManagementClient worldManagementClient = mock(WorldManagementClient.class); + AtomicReference request = new AtomicReference<>(); + PublishedRealmInitialAdmissionBindCommand command = command(); + + when(catalogOwner.materializePublishedSnapshot(CANONICAL_TENANT_ID, PUBLISHED_VERSION_ID)) + .thenReturn(matchingSnapshot()); + when(gameInstanceService.startRunOwnedInitialLaunch(any())) + .thenReturn(new RunOwnedInitialLaunchResult(activeGameInstance(), ACTIVE_LIFECYCLE_EPOCH)); + when(worldManagementClient.getWorldInstanceLifecycle( + LOCAL_GAME_SESSION_TENANT_ID, GAME_INSTANCE_ID)) + .thenReturn(activeLifecycle(ACTIVE_LIFECYCLE_EPOCH)); + when(ownerService.beginIntent(any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindRequest received = invocation.getArgument(0); + request.set(received); + return attempt(received, null, null, Status.PENDING); + }); + when(worldManagementClient.acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHold hold = + exactHold(holdStatus, invocation.getArgument(5)).build(); + return AcquireInitialAdmissionBindHoldResponse.newBuilder().setHold(hold).build(); + }); + when(ownerService.attachHold(any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return attempt( + request.get(), + UUID.fromString(binding.holdId()), + UUID.fromString(binding.holdFence()), + Status.PENDING); + }); + when(ownerService.commit(any())) + .thenAnswer(invocation -> terminalProof(invocation.getArgument(0), Outcome.COMMITTED)); + + return new Fixture( + new PublishedRealmInitialAdmissionBindCoordinator( + catalogOwner, gameInstanceService, ownerService, worldManagementClient), + command, + catalogOwner, + gameInstanceService, + ownerService, + worldManagementClient); + } + + private static PublishedRealmInitialAdmissionBindCommand command() { + return new PublishedRealmInitialAdmissionBindCommand( + CANONICAL_TENANT_ID, + PUBLISHED_VERSION_ID, + GAME_TEMPLATE_ID, + OWNER_ACCOUNT_ID, + "earth", + "main", + INITIAL_ADMISSION_REQUEST_ID); + } + + private static PublishedRealmCatalogSnapshot matchingSnapshot() { + String workflow = "publish:published-bind-matching-unit-test"; + String manifest = "published-bind-matching-manifest"; + RealmEntryPolicy policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON); + String releaseIdentity = + PublishedRealmEntryPolicyEvidence.releaseBundleIdentity( + CANONICAL_TENANT_ID, PUBLISHED_VERSION_ID, workflow, manifest, JSON); + PublishedRealmEntryPolicyEvidence policyEvidence = + PublishedRealmEntryPolicyEvidence.create( + UUID.fromString("55555555-5555-4555-8555-555555555555"), + CANONICAL_TENANT_ID, + "RETAINED_GAME_V29", + LOCAL_GAME_SESSION_TENANT_ID, + "gd-source-41", + PUBLISHED_VERSION_ID, + 3, + 903L, + releaseIdentity, + workflow, + manifest, + policy, + JSON); + PublishedRealmEntryPolicySetEvidence policySet = + PublishedRealmEntryPolicySetEvidence.create( + CANONICAL_TENANT_ID, + PUBLISHED_VERSION_ID, + 3, + releaseIdentity, + workflow, + manifest, + List.of(policyEvidence), + JSON); + return new PublishedRealmCatalogSnapshot( + LOCAL_GAME_SESSION_TENANT_ID, + TARGET_NAMESPACE, + CANONICAL_TENANT_ID, + LOCAL_GAME_SESSION_TENANT_ID, + "gd-source-41", + "RETAINED_GAME_V29", + CATALOG_REVISION, + policySet, + List.of( + new PublishedRealmCatalogEntry( + LOCAL_GAME_SESSION_TENANT_ID, + CATALOG_REVISION, + REALM_ID, + NAMESPACE_ID, + NamespaceResolution.RESOLVED, + policyEvidence)), + Instant.parse("2026-01-01T00:00:00Z")); + } + + private static GameInstanceDto activeGameInstance() { + return new GameInstanceDto( + GAME_INSTANCE_ID, + LOCAL_GAME_SESSION_TENANT_ID, + "v1", + null, + null, + null, + null, + GAME_TEMPLATE_ID, + LAUNCH_DESCRIPTOR_ID, + PUBLISHED_VERSION_ID, + 903L, + 5L, + "config-1", + null, + OWNER_ACCOUNT_ID, + "RUNNING"); + } + + private static GetWorldInstanceLifecycleResponse activeLifecycle(long lifecycleEpoch) { + return GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + WorldInstanceLifecycleSnapshot.newBuilder() + .setTenantId(Long.toString(LOCAL_GAME_SESSION_TENANT_ID)) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setGameTemplateId(Long.toString(GAME_TEMPLATE_ID)) + .setControlPlaneRequestId(INITIAL_ADMISSION_REQUEST_ID) + .setLaunchDescriptorId(LAUNCH_DESCRIPTOR_ID) + .setVersionId(Long.toString(PUBLISHED_VERSION_ID)) + .setReleaseBundleId("903") + .setPublishedReleaseBundleRef(PUBLISHED_RELEASE_BUNDLE_REF) + .setVersionStateEpoch(5L) + .setLifecycleEpoch(lifecycleEpoch) + .setStatus(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) + .build()) + .build(); + } + + private static InitialAdmissionBindHold.Builder exactHold( + InitialAdmissionBindHoldStatus status, String requestDigest) { + return InitialAdmissionBindHold.newBuilder() + .setHoldId(HOLD_ID.toString()) + .setHoldFence(HOLD_FENCE.toString()) + .setTenantId(Long.toString(LOCAL_GAME_SESSION_TENANT_ID)) + .setRealmUuid(REALM_ID.toString()) + .setPlayableStateNamespaceUuid(NAMESPACE_ID.toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setVersionId(Long.toString(PUBLISHED_VERSION_ID)) + .setActiveLifecycleEpoch(ACTIVE_LIFECYCLE_EPOCH) + .setInitialAdmissionRequestId(INITIAL_ADMISSION_REQUEST_ID) + .setRequestDigest(requestDigest) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(CATALOG_REVISION) + .setStatus(status); + } + + private static InitialAdmissionBindAttempt attempt( + InitialAdmissionBindRequest request, UUID holdId, UUID holdFence, Status status) { + Instant now = Instant.parse("2026-01-01T00:00:00Z"); + return new InitialAdmissionBindAttempt( + ATTEMPT_ID, + request.tenantId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + REALM_ID, + NAMESPACE_ID, + "SHARED", + true, + CATALOG_REVISION, + GAME_INSTANCE_ID, + PUBLISHED_VERSION_ID, + ACTIVE_LIFECYCLE_EPOCH, + holdId, + holdFence, + status, + status == Status.COMMITTED ? 1L : null, + status == Status.COMMITTED ? 93L : null, + now, + now, + status == Status.PENDING ? null : now, + "V14_PUBLISHED", + TARGET_NAMESPACE, + CANONICAL_TENANT_ID, + GAME_TEMPLATE_ID, + LAUNCH_DESCRIPTOR_ID, + 903L, + PUBLISHED_RELEASE_BUNDLE_REF, + 5L); + } + + private static InitialAdmissionBindOwnerProof terminalProof( + InitialAdmissionBindHoldBinding binding, Outcome outcome) { + return terminalProof( + binding, + outcome, + ATTEMPT_ID.toString(), + outcome == Outcome.COMMITTED ? "93" : null, + outcome == Outcome.COMMITTED ? 1L : 0L, + outcome == Outcome.COMMITTED ? binding.requestDigest() : null, + outcome == Outcome.ABORTED); + } + + private static InitialAdmissionBindOwnerProof terminalProof( + InitialAdmissionBindHoldBinding binding, + Outcome outcome, + String ownerProofId, + String pointerAuditId, + long pointerVersion, + String pointerAuditRequestDigest, + boolean futureCommitPrevented) { + return new InitialAdmissionBindOwnerProof( + outcome, + binding.holdId(), + binding.holdFence(), + binding.tenantId(), + binding.realmUuid(), + binding.playableStateNamespaceUuid(), + binding.playableStateScope(), + binding.gameInstanceId(), + binding.versionId(), + binding.activeLifecycleEpoch(), + binding.initialAdmissionRequestId(), + binding.requestDigest(), + binding.expectedNoPriorPointer(), + binding.expectedCatalogRevision(), + ownerProofId, + pointerAuditId, + pointerVersion, + pointerAuditRequestDigest, + futureCommitPrevented); + } + + private static InitialAdmissionBindHoldBinding expectedBinding(String requestDigest) { + return new InitialAdmissionBindHoldBinding( + HOLD_ID.toString(), + HOLD_FENCE.toString(), + LOCAL_GAME_SESSION_TENANT_ID, + REALM_ID.toString(), + NAMESPACE_ID.toString(), + "SHARED", + GAME_INSTANCE_ID, + PUBLISHED_VERSION_ID, + ACTIVE_LIFECYCLE_EPOCH, + INITIAL_ADMISSION_REQUEST_ID, + requestDigest, + true, + CATALOG_REVISION); + } + + private static InitialAdmissionBindRequest verifyLaunchAndIntent(Fixture fixture) { + verify(fixture.catalogOwner()) + .materializePublishedSnapshot(CANONICAL_TENANT_ID, PUBLISHED_VERSION_ID); + verify(fixture.gameInstanceService()) + .startRunOwnedInitialLaunch( + new StartSessionRequest( + LOCAL_GAME_SESSION_TENANT_ID, + GAME_TEMPLATE_ID, + INITIAL_ADMISSION_REQUEST_ID, + OWNER_ACCOUNT_ID)); + verify(fixture.worldManagementClient()) + .getWorldInstanceLifecycle(LOCAL_GAME_SESSION_TENANT_ID, GAME_INSTANCE_ID); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(InitialAdmissionBindRequest.class); + verify(fixture.ownerService()).beginIntent(requestCaptor.capture()); + InitialAdmissionBindRequest request = requestCaptor.getValue(); + assertThat(request.tenantId()).isEqualTo(LOCAL_GAME_SESSION_TENANT_ID); + assertThat(request.worldSlug()).isEqualTo("earth"); + assertThat(request.realmSlug()).isEqualTo("main"); + assertThat(request.initialAdmissionRequestId()).isEqualTo(INITIAL_ADMISSION_REQUEST_ID); + assertThat(request.gameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(request.versionId()).isEqualTo(PUBLISHED_VERSION_ID); + assertThat(request.activeLifecycleEpoch()).isEqualTo(ACTIVE_LIFECYCLE_EPOCH); + assertThat(request.publishedCatalog()) + .isEqualTo( + new InitialAdmissionBindRequest.PublishedCatalogBinding( + TARGET_NAMESPACE, CANONICAL_TENANT_ID, CATALOG_REVISION)); + assertThat(request.launchEvidence()) + .isEqualTo( + new InitialAdmissionBindRequest.LaunchEvidence( + GAME_TEMPLATE_ID, LAUNCH_DESCRIPTOR_ID, 903L, PUBLISHED_RELEASE_BUNDLE_REF, 5L)); + verifyNoMoreInteractions(fixture.catalogOwner()); + return request; + } + + private static void verifyNoUnexpectedHoldInputs( + Fixture fixture, InitialAdmissionBindRequest request) { + verify(fixture.worldManagementClient()) + .acquireInitialAdmissionBindHold( + eq(LOCAL_GAME_SESSION_TENANT_ID), + eq(GAME_INSTANCE_ID), + eq(PUBLISHED_VERSION_ID), + eq(ACTIVE_LIFECYCLE_EPOCH), + eq(INITIAL_ADMISSION_REQUEST_ID), + eq(request.requestDigest()), + eq(REALM_ID), + eq(NAMESPACE_ID), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + eq(CATALOG_REVISION)); + verifyNoMoreInteractions(fixture.gameInstanceService(), fixture.worldManagementClient()); + } + + private static void verifyNoOwnerMutationAfterIntent(Fixture fixture) { + verify(fixture.ownerService(), never()).attachHold(any()); + verify(fixture.ownerService(), never()).read(any()); + verify(fixture.ownerService(), never()).commit(any()); + verify(fixture.ownerService(), never()).abort(any()); + verifyNoMoreInteractions(fixture.ownerService()); + } + + private record Fixture( + PublishedRealmInitialAdmissionBindCoordinator coordinator, + PublishedRealmInitialAdmissionBindCommand command, + PublishedRealmCatalogOwnerService catalogOwner, + GameInstanceService gameInstanceService, + InitialAdmissionBindOwnerService ownerService, + WorldManagementClient worldManagementClient) {} + + private record TerminalCase( + InitialAdmissionBindHoldStatus holdStatus, + Outcome ownerOutcome, + PublishedRealmInitialAdmissionBindCoordinator.TerminalOutcome resultOutcome) {} + private static PublishedRealmCatalogSnapshot snapshotWithDistinctSourceAndLocalIds() { String workflow = "publish:published-bind-unit-test"; String manifest = "published-bind-manifest"; From 04fa155e257035618eacefe1b03956b173a1b172 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:57:59 +1300 Subject: [PATCH 089/105] fix: exercise association immutability and validate prior namespace state --- ...TenantAssociationRepositoryIntegrationTest.java | 3 ++- .../InitialAdmissionBindCatalogRepository.java | 14 +++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index 8cf08cf9f7..3ceb0c0797 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -451,7 +451,8 @@ void databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInse .dsl() .execute( "TRUNCATE game_design_game_session_tenant_association_operations, " - + "game_design_game_session_tenant_association_payload")) + + "game_design_game_session_tenant_association_payload, " + + "game_design_game_session_tenant_association_legal_hold")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java index 0e610519cb..4f7436b67a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java @@ -568,12 +568,16 @@ private NamespaceAssignment resolveNamespace( if (previous != null) { RealmEntryPolicy.StateScope previousScope; NamespaceResolution previousResolution; + String previousScopeValue = previous.get(STATE_SCOPE); + String previousResolutionValue = previous.get(NAMESPACE_RESOLUTION); + if (previousScopeValue == null || previousResolutionValue == null) { + throw new IllegalStateException( + "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior namespace state is unsupported"); + } try { - previousScope = - RealmEntryPolicy.StateScope.valueOf(Objects.requireNonNull(previous.get(STATE_SCOPE))); - previousResolution = - NamespaceResolution.valueOf(Objects.requireNonNull(previous.get(NAMESPACE_RESOLUTION))); - } catch (IllegalArgumentException | NullPointerException exception) { + previousScope = RealmEntryPolicy.StateScope.valueOf(previousScopeValue); + previousResolution = NamespaceResolution.valueOf(previousResolutionValue); + } catch (IllegalArgumentException exception) { throw new IllegalStateException( "PUBLISHED_REALM_CATALOG_NAMESPACE_INVALID: prior namespace state is unsupported", exception); From afc1bf5a443266ed5f3390a90eeb7771224aacd5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:34:25 +1300 Subject: [PATCH 090/105] test: bind gameplay roster fixtures to canonical Account UUIDs --- .../test/ChatTestFixturesTest.java | 30 ++++++++++++ .../stubs/EntityManagementStubServerTest.java | 48 ++++++++++++++----- .../gamesession/test/ChatTestFixtures.java | 7 +-- 3 files changed, 70 insertions(+), 15 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java new file mode 100644 index 0000000000..39a09196e9 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.gamesession.test; + +import static org.assertj.core.api.Assertions.assertThat; + +import net.firedevops.firemud.test.AccountRuntimeStubServer; +import org.junit.jupiter.api.Test; + +class ChatTestFixturesTest { + @Test + void characterRosterUsesCanonicalAccountUuidsAndPreservesActorIds() { + assertCharacter("Emberline", 7L, ChatTestFixtures.PLAYER_EMBERLINE); + assertCharacter("Sora", 8L, ChatTestFixtures.PLAYER_SORA); + assertCharacter("Nyx", 9L, ChatTestFixtures.PLAYER_NYX); + } + + @Test + void unknownCharacterNameRemainsEmpty() { + assertThat(ChatTestFixtures.characterByName("unknown").getId()).isEmpty(); + assertThat(ChatTestFixtures.characterByName("unknown").getAccountId()).isEmpty(); + } + + private static void assertCharacter(String name, long accountRowId, String actorId) { + var character = ChatTestFixtures.characterByName(name); + + assertThat(character.getId()).isEqualTo(actorId); + assertThat(character.getAccountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(accountRowId)); + assertThat(character.getAccountId()).isNotEqualTo(character.getId()); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 30af581f9c..8cba724d5e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.test.ChatTestFixtures; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.Test; class EntityManagementStubServerTest { @@ -26,9 +27,9 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw for (FixtureCharacter fixture : List.of( - new FixtureCharacter("7", "Emberline"), - new FixtureCharacter("8", "Sora"), - new FixtureCharacter("9", "Nyx"))) { + new FixtureCharacter(accountUuid(7L), "Emberline"), + new FixtureCharacter(accountUuid(8L), "Sora"), + new FixtureCharacter(accountUuid(9L), "Nyx"))) { ListCharactersByAccountResponse response = listCharacters( stub, "1", fixture.accountId(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -48,14 +49,14 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { Character.newBuilder() .setId("101") .setTenantId("1") - .setAccountId("101") + .setAccountId(accountUuid(101L)) .setName("player-1") .build(); Character secondPlayer = Character.newBuilder() .setId("102") .setTenantId("1") - .setAccountId("102") + .setAccountId(accountUuid(102L)) .setName("player-2") .build(); @@ -68,15 +69,18 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, "1", accountUuid(101L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(firstPlayer)); assertThat( - listCharacters(stub, "1", "102", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, "1", accountUuid(102L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(secondPlayer)); assertThat( - listCharacters(stub, "2", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, "2", accountUuid(101L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -95,11 +99,19 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "2", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "2", + accountUuid(7L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + accountUuid(999L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -118,11 +130,19 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + listCharacters( + stub, + "1", + accountUuid(7L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + listCharacters( + stub, + "1", + accountUuid(7L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .getCharactersList()) .isEmpty(); } finally { @@ -155,5 +175,9 @@ private static Character sharedCharacter(Character character) { .build(); } + private static String accountUuid(long accountRowId) { + return AccountRuntimeStubServer.accountUuidForTestFixture(accountRowId); + } + private record FixtureCharacter(String accountId, String name) {} } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java index 5c92ce6ff3..f35d820466 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java @@ -4,6 +4,7 @@ import net.firedevops.firemud.entitymanagement.v1.EntityType; import net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse; import net.firedevops.firemud.entitymanagement.v1.RoomEntity; +import net.firedevops.firemud.test.AccountRuntimeStubServer; public final class ChatTestFixtures { public static final String ROOM_ID = "R-1021"; @@ -57,7 +58,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_EMBERLINE) .setTenantId("1") - .setAccountId("7") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(7L)) .setName("Emberline") .build(); } @@ -65,7 +66,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_SORA) .setTenantId("1") - .setAccountId("8") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(8L)) .setName("Sora") .build(); } @@ -73,7 +74,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_NYX) .setTenantId("1") - .setAccountId("9") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(9L)) .setName("Nyx") .build(); } From 26f1de607f08e7d6ddad3dcd9426d55ff9b08dab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:34:25 +1300 Subject: [PATCH 091/105] test: bind gameplay roster fixtures to canonical Account UUIDs --- .../test/ChatTestFixturesTest.java | 30 +++++++++++ .../stubs/EntityManagementStubServerTest.java | 54 ++++++++++++++----- .../gamesession/test/ChatTestFixtures.java | 7 +-- 3 files changed, 76 insertions(+), 15 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java new file mode 100644 index 0000000000..39a09196e9 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.gamesession.test; + +import static org.assertj.core.api.Assertions.assertThat; + +import net.firedevops.firemud.test.AccountRuntimeStubServer; +import org.junit.jupiter.api.Test; + +class ChatTestFixturesTest { + @Test + void characterRosterUsesCanonicalAccountUuidsAndPreservesActorIds() { + assertCharacter("Emberline", 7L, ChatTestFixtures.PLAYER_EMBERLINE); + assertCharacter("Sora", 8L, ChatTestFixtures.PLAYER_SORA); + assertCharacter("Nyx", 9L, ChatTestFixtures.PLAYER_NYX); + } + + @Test + void unknownCharacterNameRemainsEmpty() { + assertThat(ChatTestFixtures.characterByName("unknown").getId()).isEmpty(); + assertThat(ChatTestFixtures.characterByName("unknown").getAccountId()).isEmpty(); + } + + private static void assertCharacter(String name, long accountRowId, String actorId) { + var character = ChatTestFixtures.characterByName(name); + + assertThat(character.getId()).isEqualTo(actorId); + assertThat(character.getAccountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(accountRowId)); + assertThat(character.getAccountId()).isNotEqualTo(character.getId()); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 30af581f9c..4c6f5af9d2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.test.ChatTestFixtures; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.Test; class EntityManagementStubServerTest { @@ -26,9 +27,9 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw for (FixtureCharacter fixture : List.of( - new FixtureCharacter("7", "Emberline"), - new FixtureCharacter("8", "Sora"), - new FixtureCharacter("9", "Nyx"))) { + new FixtureCharacter(accountUuid(7L), "Emberline"), + new FixtureCharacter(accountUuid(8L), "Sora"), + new FixtureCharacter(accountUuid(9L), "Nyx"))) { ListCharactersByAccountResponse response = listCharacters( stub, "1", fixture.accountId(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -48,14 +49,14 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { Character.newBuilder() .setId("101") .setTenantId("1") - .setAccountId("101") + .setAccountId(accountUuid(101L)) .setName("player-1") .build(); Character secondPlayer = Character.newBuilder() .setId("102") .setTenantId("1") - .setAccountId("102") + .setAccountId(accountUuid(102L)) .setName("player-2") .build(); @@ -68,15 +69,27 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + accountUuid(101L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(firstPlayer)); assertThat( - listCharacters(stub, "1", "102", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + accountUuid(102L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(secondPlayer)); assertThat( - listCharacters(stub, "2", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "2", + accountUuid(101L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -95,11 +108,16 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "2", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, "2", accountUuid(7L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + accountUuid(999L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -118,11 +136,19 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + listCharacters( + stub, + "1", + accountUuid(7L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + listCharacters( + stub, + "1", + accountUuid(7L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .getCharactersList()) .isEmpty(); } finally { @@ -155,5 +181,9 @@ private static Character sharedCharacter(Character character) { .build(); } + private static String accountUuid(long accountRowId) { + return AccountRuntimeStubServer.accountUuidForTestFixture(accountRowId); + } + private record FixtureCharacter(String accountId, String name) {} } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java index 5c92ce6ff3..f35d820466 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java @@ -4,6 +4,7 @@ import net.firedevops.firemud.entitymanagement.v1.EntityType; import net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse; import net.firedevops.firemud.entitymanagement.v1.RoomEntity; +import net.firedevops.firemud.test.AccountRuntimeStubServer; public final class ChatTestFixtures { public static final String ROOM_ID = "R-1021"; @@ -57,7 +58,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_EMBERLINE) .setTenantId("1") - .setAccountId("7") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(7L)) .setName("Emberline") .build(); } @@ -65,7 +66,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_SORA) .setTenantId("1") - .setAccountId("8") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(8L)) .setName("Sora") .build(); } @@ -73,7 +74,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_NYX) .setTenantId("1") - .setAccountId("9") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(9L)) .setName("Nyx") .build(); } From 5f89c6c5386b4fbf913d5847b83a9e64cc433d9e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:37:14 +1300 Subject: [PATCH 092/105] test: strengthen owner-read assertions and static proof --- ...ialAdmissionBindAttemptRepositoryTest.java | 19 ++++++++++-------- ...itialAdmissionOwnerReadAuthWiringTest.java | 2 ++ ...ealmAdmissionOwnerReadGrpcServiceTest.java | 20 ++++++++----------- .../stubs/EntityManagementStubServerTest.java | 20 ++++++++++++------- 4 files changed, 34 insertions(+), 27 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java index b3f93a1205..b4a1e728b0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java @@ -7,6 +7,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.time.Instant; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; @@ -36,10 +37,11 @@ void insertAndReadPreservesHistoricalAndPublishedCatalogSources() throws Excepti assertNull(historical.canonicalTenantId()); assertEquals( historicalRealmId, - dsl.fetchOne( - "SELECT fixture_catalog_realm_id FROM gameplay_initial_admission_bind_attempt " - + "WHERE initial_admission_request_id = ?", - "request-historical") + Objects.requireNonNull( + dsl.fetchOne( + "SELECT fixture_catalog_realm_id FROM gameplay_initial_admission_bind_attempt " + + "WHERE initial_admission_request_id = ?", + "request-historical")) .get(0, UUID.class)); UUID publishedRealmId = UUID.randomUUID(); @@ -79,10 +81,11 @@ void insertAndReadPreservesHistoricalAndPublishedCatalogSources() throws Excepti assertEquals("V14_PUBLISHED", published.catalogSourceKind()); assertEquals(Instant.parse("2026-10-03T00:00:00Z"), published.createdAt()); assertNull( - dsl.fetchOne( - "SELECT fixture_catalog_realm_id FROM gameplay_initial_admission_bind_attempt " - + "WHERE initial_admission_request_id = ?", - "request-published") + Objects.requireNonNull( + dsl.fetchOne( + "SELECT fixture_catalog_realm_id FROM gameplay_initial_admission_bind_attempt " + + "WHERE initial_admission_request_id = ?", + "request-published")) .get(0, UUID.class)); assertEquals("prod-west", published.publishedTargetNamespace()); assertEquals(canonicalTenantId, published.canonicalTenantId()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java index 54511ebbd6..812c74871c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionOwnerReadAuthWiringTest.java @@ -88,10 +88,12 @@ void noTokenReachesEachExactOwnerHandlerForItsSameNamespacePeer() { PublishedDispatchResult published = dispatchPublished(interceptor, service, ENTITY_URI); assertThat(initial.handlerDispatched()).isTrue(); + assertThat(initial.observer().statusCode).isNull(); assertThat(initial.observer().response.getError().getCode()).isEqualTo("INTERNAL"); verify(proofReader).read(binding()); assertThat(published.handlerDispatched()).isTrue(); + assertThat(published.observer().response).isNull(); assertThat(published.observer().statusCode).isEqualTo(Status.Code.UNAVAILABLE); verify(ownerReadService).read(any(PublishedRealmAdmissionOwnerReadRequest.class)); }); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java index 08081166d6..42832e8207 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PublishedRealmAdmissionOwnerReadGrpcServiceTest.java @@ -78,7 +78,7 @@ void returnsTheCompleteTypedOwnerCompositionForTheExactRequest() { () -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(response))); GetPublishedRealmAdmissionOwnerReadResponse result = response.value; - assertThat(response.failure).isNull(); + assertThat(response.failureCode).isNull(); assertThat(result).isNotNull(); assertThat(result.getProof().getTargetNamespace()).isEqualTo(NAMESPACE); assertThat(result.getProof().getCanonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID.toString()); @@ -137,8 +137,7 @@ void rejectsMalformedOrNonCanonicalTargetWithoutCallingOwnerAuthority() { () -> grpcService.getPublishedRealmAdmissionOwnerRead(malformed, capture(response))); assertThat(response.value).isNull(); - assertThat(Status.fromThrowable(response.failure).getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(response.failureCode).isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(ownerReadService); } @@ -153,7 +152,7 @@ void rejectsMismatchedOrUnavailableOwnerEvidenceWithoutReturningPartialProof() { () -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(response))); assertThat(response.value).isNull(); - assertThat(Status.fromThrowable(response.failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(response.failureCode).isEqualTo(Status.Code.UNAVAILABLE); } @Test @@ -169,8 +168,7 @@ void rejectsWrongPeerAndMissingOwnerDependencyWithoutReturningProof() { "world-management-service")) .run(() -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(denied))); assertThat(denied.value).isNull(); - assertThat(Status.fromThrowable(denied.failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.failureCode).isEqualTo(Status.Code.PERMISSION_DENIED); CapturingObserver wrongTarget = new CapturingObserver<>(); @@ -180,8 +178,7 @@ void rejectsWrongPeerAndMissingOwnerDependencyWithoutReturningProof() { request().toBuilder().setTargetNamespace("other-namespace").build(), capture(wrongTarget))); assertThat(wrongTarget.value).isNull(); - assertThat(Status.fromThrowable(wrongTarget.failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongTarget.failureCode).isEqualTo(Status.Code.PERMISSION_DENIED); verifyNoInteractions(ownerReadService); grpcService.configurePublishedRealmAdmissionOwnerReadBoundary(null, NAMESPACE); @@ -190,8 +187,7 @@ void rejectsWrongPeerAndMissingOwnerDependencyWithoutReturningProof() { runAsEntityManagementPeer( () -> grpcService.getPublishedRealmAdmissionOwnerRead(request(), capture(unavailable))); assertThat(unavailable.value).isNull(); - assertThat(Status.fromThrowable(unavailable.failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.failureCode).isEqualTo(Status.Code.UNAVAILABLE); } private static StreamObserver capture( @@ -201,7 +197,7 @@ private static StreamObserver captu private static final class CapturingObserver implements StreamObserver { private T value; - private Throwable failure; + private Status.Code failureCode; @Override public void onNext(T next) { @@ -210,7 +206,7 @@ public void onNext(T next) { @Override public void onError(Throwable throwable) { - failure = throwable; + failureCode = Status.fromThrowable(throwable).getCode(); } @Override diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 8cba724d5e..4c6f5af9d2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -70,17 +70,26 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { assertThat( listCharacters( - stub, "1", accountUuid(101L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + stub, + "1", + accountUuid(101L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(firstPlayer)); assertThat( listCharacters( - stub, "1", accountUuid(102L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + stub, + "1", + accountUuid(102L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(secondPlayer)); assertThat( listCharacters( - stub, "2", accountUuid(101L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + stub, + "2", + accountUuid(101L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -100,10 +109,7 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { assertThat( listCharacters( - stub, - "2", - accountUuid(7L), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + stub, "2", accountUuid(7L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); assertThat( From 75de9e584571f3d5b447175e3a8dbeef5d05dc00 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:53:01 +1300 Subject: [PATCH 093/105] test: reuse canonical Account UUIDs in Telnet roster setup --- ...tewayGameSessionAccountCrossServiceIntegrationTest.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 26cedaf6f0..1c89ab998b 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -131,13 +131,6 @@ void clearSharedRuntimeState() throws Exception { .setCharacters( List.of("Emberline", "Sora", "Nyx").stream() .map(ChatTestFixtures::characterByName) - .map( - character -> - character.toBuilder() - .setAccountId( - AccountRuntimeStubServer.accountUuidForTestFixture( - Long.parseLong(character.getAccountId()))) - .build()) .toList()); } From 8f8d6c96b732390b0b72a2d471cc8cdc519ba39c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:01:14 +1300 Subject: [PATCH 094/105] ci: retain module JUnit execution and skip evidence --- .github/workflows/ci.yml | 8 +++++ .../tests/ci-validation-summary-contract.sh | 35 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aab6706691..89d47da9bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1007,6 +1007,14 @@ jobs: name: ${{ matrix.module }}-jacoco verbose: true + - name: 📤 Upload JUnit XML Reports + if: ${{ always() && contains(fromJSON('["success","failure","cancelled"]'), steps.checks.outcome) }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: junit-${{ matrix.module }}-${{ github.sha }} + path: ${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/test-results/**/*.xml' || format('services/{0}/build/test-results/**/*.xml', matrix.module) }} + if-no-files-found: warn + - name: 📤 Upload Test Logs if Failed if: failure() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3ada95c248 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -12,6 +12,41 @@ import yaml path = Path(sys.argv[1]) workflow = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) +build_test_steps = workflow["jobs"]["build-and-test"]["steps"] +test_report_steps = [ + step for step in build_test_steps + if step.get("name") == "📤 Upload JUnit XML Reports" +] +if len(test_report_steps) != 1: + raise SystemExit("build-and-test must contain exactly one JUnit XML artifact upload") +test_report = test_report_steps[0] +test_report_with = test_report["with"] +if test_report.get("if") != "${{ always() && contains(fromJSON('[\"success\",\"failure\",\"cancelled\"]'), steps.checks.outcome) }}": + raise SystemExit("JUnit XML upload must run after attempted checks, including failure or cancellation") +attempted_check_outcomes = {"success", "failure", "cancelled"} +outcome_truth_table = { + "": False, + "skipped": False, + "success": True, + "failure": True, + "cancelled": True, +} +for outcome, expected in outcome_truth_table.items(): + if (outcome in attempted_check_outcomes) != expected: + raise SystemExit(f"JUnit XML upload attempted-check guard has wrong result for {outcome!r}") +if test_report.get("uses") != "actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a": + raise SystemExit("JUnit XML upload must use the pinned upload-artifact action") +if test_report_with.get("name") != "junit-${{ matrix.module }}-${{ github.sha }}": + raise SystemExit("JUnit XML artifact name must identify its module and head") +expected_test_report_path = ( + "${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/test-results/**/*.xml' " + "|| format('services/{0}/build/test-results/**/*.xml', matrix.module) }}" +) +if test_report_with.get("path") != expected_test_report_path: + raise SystemExit("JUnit XML upload must cover module test-results XML, including load-testing") +if test_report_with.get("if-no-files-found") != "warn": + raise SystemExit("missing JUnit XML reports must warn without failing builds that did not reach tests") + job = workflow["jobs"]["validation-summary"] steps = job["steps"] summary_steps = [ From 1512fc9cefbc222cfbac99c8b862e8a7bed0b275 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:16:58 +1300 Subject: [PATCH 095/105] docs(game-design): enumerate workload-only tenant RPC exemptions --- .../microservices/game-design-service/api-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 8633b000ae..42f7563310 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -109,7 +109,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e The only permitted peer is the verified Game Session workload identity `spiffe://firemud/ns/{namespace}/sa/game-session-service`, where `{namespace}` must exactly match Game Design's configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. An empty or invalid configured namespace, absent verified peer identity, another service identity, or a peer from another namespace returns `PERMISSION_DENIED`. JWT claims and request metadata are not peer identity; workload authentication follows [Authentication and Authorization](../../system-architecture-authentication.md). -The shared `AuthTokenInterceptor` configuration exempts exactly this full RPC method name from bearer-token validation because this is a workload-only method under [ADR 0038](../../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). This is not public transport exposure: the gRPC listener still requires mTLS, and the handler requires the exact verified workload identity above. No other Game Design RPC is exempted. +The shared `AuthTokenInterceptor` configuration exempts exactly the full RPC method names `TenantIdentityService/ResolveRuntimeTenantIdentity`, `TenantIdentityService/ResolveLegacyGameSessionTenantAssociation`, `TenantIdentityService/ResolvePublishedRealmEntryPolicy`, and `TenantIdentityService/ListPublishedRealmEntryPolicies` from bearer-token validation because these are workload-only methods under [ADR 0038](../../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). This is not public transport exposure: the gRPC listener still requires mTLS, and each handler requires the exact verified workload identity above. No other Game Design RPC is exempted. The request contains exactly two fields: `canonical_tenant_id` and `request_id`, each a canonical lower-case, nonnil UUID string. Unknown protobuf fields, noncanonical/nil IDs, or a missing ID return `INVALID_ARGUMENT`. The tenant UUID is only a selector: Game Design returns it only after an exact canonical-UUID lookup and owner-row provenance validation. From d5fc011dbc8e353d9689e80d4ae75666566af659 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:53:24 +1300 Subject: [PATCH 096/105] Align cross-service gameplay fixtures with canonical Account UUIDs --- .../gamesession/CommunicationWebSocketCrossServiceTest.java | 6 ++++-- .../gamesession/testsupport/GameplayCrossServiceStack.java | 4 ++-- .../gamesession/testsupport/GameplayLoadScenarios.java | 3 ++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 0a8cf4f2da..02c21a47ff 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.socialgroups.v1.FriendPresenceActivityState; import net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry; import net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; @@ -952,15 +953,16 @@ private URI gameSessionWebSocketUrl() { } private GameplayWebSocketDriver openFirstPartyClient(String transportSessionId) { + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(ACCOUNT_ID); return GameplayWebSocketDriver.connectFirstPartyWeb( URI.create("ws://localhost:" + gameSession().port() + "/ws/game"), COMMAND_WAIT, transportSessionId, FIRST_PARTY_CONNECT_SECRET, - Long.toString(ACCOUNT_ID), + accountUuid, Map.of( "accountId", - Long.toString(ACCOUNT_ID), + accountUuid, "tenantId", Long.toString(TENANT_ID), "worldSlug", diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 03b453aef3..956f10a829 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -864,7 +864,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - Long.toString(accountId), + AccountRuntimeStubServer.accountUuidForTestFixture(accountId), loginName, characterId, characterName, @@ -891,7 +891,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - Long.toString(accountId), + AccountRuntimeStubServer.accountUuidForTestFixture(accountId), loginName, characterId, characterName, diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index cd9a886fa2..bc9ab4f33e 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.test.AccountRuntimeStubServer; /** Shared load-oriented gameplay scenario helpers above the base cross-service stack. */ public final class GameplayLoadScenarios { @@ -73,7 +74,7 @@ public static List seedPlayers( Character.newBuilder() .setId(Long.toString(accountId)) .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(accountId)) .setName(label) .build()); players.add( From b9cbe95aab2a37f2c5c5c8b5465eb18088458695 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:55:11 +1300 Subject: [PATCH 097/105] Run Game Session PostgreSQL proof before full cross-service validation --- .github/workflows/ci.yml | 6 +++++- .../tests/ci-validation-summary-contract.sh | 21 +++++++++++++++++++ ...ommunicationWebSocketCrossServiceTest.java | 6 ++++-- .../GameplayCrossServiceStack.java | 4 ++-- .../testsupport/GameplayLoadScenarios.java | 3 ++- 5 files changed, 34 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 89d47da9bc..9c39fb73c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -950,7 +950,11 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - ./gradlew :${{ matrix.module }}:check -PfullCheck + if [ "${{ matrix.module }}" = "game-session-service" ]; then + ./gradlew :game-session-service:integrationTest :game-session-service:check -PfullCheck + else + ./gradlew :${{ matrix.module }}:check -PfullCheck + fi echo "::endgroup::" - name: 📦 Build Runtime JAR diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index 3ada95c248..fbe7fadd52 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -47,6 +47,27 @@ if test_report_with.get("path") != expected_test_report_path: if test_report_with.get("if-no-files-found") != "warn": raise SystemExit("missing JUnit XML reports must warn without failing builds that did not reach tests") +check_steps = [step for step in build_test_steps if step.get("name") == "🧪 Run Gradle Checks"] +if len(check_steps) != 1: + raise SystemExit("build-and-test must contain exactly one module validation step") +check_step = check_steps[0] +check_run = check_step.get("run", "") +game_session_integration = ( + "./gradlew :game-session-service:integrationTest :game-session-service:check -PfullCheck" +) +other_module_check = "./gradlew :${{ matrix.module }}:check -PfullCheck" +if '[ "${{ matrix.module }}" = "game-session-service" ]' not in check_run: + raise SystemExit("Game Session must use its explicit integration-test validation path") +if game_session_integration not in check_run: + raise SystemExit("Game Session integrationTest must run before its full check in one Gradle invocation") +if other_module_check not in check_run: + raise SystemExit("non-Game-Session modules must retain the existing full check invocation") +if check_step.get("continue-on-error", "false").lower() == "true": + raise SystemExit("module validation must remain a required CI gate") +gradle_commands = [line.strip() for line in check_run.splitlines() if line.strip().startswith("./gradlew ")] +if gradle_commands != [game_session_integration, other_module_check]: + raise SystemExit("module validation must use only the ordered Game Session and unchanged module Gradle gates") + job = workflow["jobs"]["validation-summary"] steps = job["steps"] summary_steps = [ diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 0a8cf4f2da..02c21a47ff 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.socialgroups.v1.FriendPresenceActivityState; import net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry; import net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; @@ -952,15 +953,16 @@ private URI gameSessionWebSocketUrl() { } private GameplayWebSocketDriver openFirstPartyClient(String transportSessionId) { + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(ACCOUNT_ID); return GameplayWebSocketDriver.connectFirstPartyWeb( URI.create("ws://localhost:" + gameSession().port() + "/ws/game"), COMMAND_WAIT, transportSessionId, FIRST_PARTY_CONNECT_SECRET, - Long.toString(ACCOUNT_ID), + accountUuid, Map.of( "accountId", - Long.toString(ACCOUNT_ID), + accountUuid, "tenantId", Long.toString(TENANT_ID), "worldSlug", diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 03b453aef3..956f10a829 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -864,7 +864,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - Long.toString(accountId), + AccountRuntimeStubServer.accountUuidForTestFixture(accountId), loginName, characterId, characterName, @@ -891,7 +891,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - Long.toString(accountId), + AccountRuntimeStubServer.accountUuidForTestFixture(accountId), loginName, characterId, characterName, diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index cd9a886fa2..bc9ab4f33e 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.test.AccountRuntimeStubServer; /** Shared load-oriented gameplay scenario helpers above the base cross-service stack. */ public final class GameplayLoadScenarios { @@ -73,7 +74,7 @@ public static List seedPlayers( Character.newBuilder() .setId(Long.toString(accountId)) .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(accountId)) .setName(label) .build()); players.add( From 9c8bb313f081780bbf6a3b859a6654ec49f8f999 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:26:35 +1300 Subject: [PATCH 098/105] test(game-session): repair executed retained proof and canonical identity fixtures --- ...GameSessionApplicationIntegrationTest.java | 3 +- ...tAssociationRepositoryIntegrationTest.java | 95 +++++++++++++++---- ...nantSnapshotRepositoryIntegrationTest.java | 18 ++-- ...lAdmissionBindPostgresIntegrationTest.java | 2 + ...essionWebSocketHandlerIntegrationTest.java | 1 + 5 files changed, 90 insertions(+), 29 deletions(-) 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 802aebe29e..ef00c66673 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 @@ -60,6 +60,7 @@ }) class GameSessionApplicationIntegrationTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String ACCOUNT_UUID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final JwtUtil JWT_UTIL = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); @@ -296,7 +297,7 @@ void effectiveSettingsEndpointMergesScopedOverridesForPersistedSession() { new SessionContext( 999L, 42L, - "100", + ACCOUNT_UUID, "player@example.com", 55L, "Player", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index b0c7cda283..648a3e1e5e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -175,6 +175,7 @@ void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesMinimalAntiReassignme UUID releasedOperation = uuid(921); UUID heldCanonical = uuid(922); UUID releasedCanonical = uuid(923); + fixture.seedInstance(920L, 920L, "held-runtime"); fixture.insertExpiredMapping(heldOperation, uuid(924), heldCanonical, 920L); fixture.insertExpiredMapping(releasedOperation, uuid(925), releasedCanonical, 921L); @@ -204,11 +205,14 @@ void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesMinimalAntiReassignme "SELECT 1 FROM game_session_retained_tenant_association_legal_hold " + "WHERE hold_id = ? AND operation_id = ? " + "AND hold_scope = 'RAW_PAYLOAD' AND reason_code = 'LITIGATION' " + + "AND authorized_principal = ? " + "AND released_at IS NOT NULL " - + "AND released_by = 'fixture-authenticated-owner' " + + "AND released_by = ? " + "AND release_reference = 'release-927'", releasedHoldId, - releasedOperation) + releasedOperation, + fixture.sessionUser(), + fixture.sessionUser()) != null) .isTrue(); assertThat(fixture.repository.purgeExpiredRawPayloads()).isZero(); @@ -219,9 +223,13 @@ void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesMinimalAntiReassignme fixture.dsl.fetchOne( "SELECT 1 FROM game_session_retained_tenant_association_legal_hold " + "WHERE hold_id = ? AND operation_id = ? " - + "AND released_at IS NOT NULL AND release_reference = 'release-927'", + + "AND authorized_principal = ? " + + "AND released_at IS NOT NULL AND released_by = ? " + + "AND release_reference = 'release-927'", activeHoldId, - heldOperation) + heldOperation, + fixture.sessionUser(), + fixture.sessionUser()) != null) .isTrue(); assertThat(fixture.repository.readMinimalAssociation(NAMESPACE, heldCanonical)) @@ -239,10 +247,7 @@ void unverifiedLegalHoldWritesFailClosedAndCleanupPreservesMinimalAntiReassignme () -> fixture.repository.read(heldOperation, uuid(924), heldCanonical, 920L, NAMESPACE)) .isInstanceOf(InvalidAssociationEvidenceException.class); GameSessionRetainedTenantSnapshot staleCapture = - fixture - .capture(920L) - .withCapturedAt( - java.time.Instant.now().minus(java.time.Duration.ofDays(31)).toString()); + fixture.capture(920L).withCapturedAt(fixture.captureTimeDaysAgo(31)); LegacyGameSessionTenantAssociationReceipt staleRetry = fixture.approval(uuid(928), heldCanonical, 920L, staleCapture); assertThatThrownBy(() -> fixture.register(uuid(924), staleRetry)) @@ -265,8 +270,7 @@ void expiredUnverifiedApprovalCannotBeRegisteredAndRequiresFreshCapture() { fixture.seedInstance(42L, 420L, "runtime-42"); GameSessionRetainedTenantSnapshot current = fixture.capture(42L); GameSessionRetainedTenantSnapshot expired = - current.withCapturedAt( - java.time.Instant.now().minus(java.time.Duration.ofDays(31)).toString()); + current.withCapturedAt(fixture.captureTimeDaysAgo(31)); LegacyGameSessionTenantAssociationReceipt oldApproval = fixture.approval(uuid(930), uuid(931), 42L, expired); @@ -388,6 +392,7 @@ void lostAcknowledgementExactRetryReturnsSameOriginalOperationAndBytesWithoutMut String originalReceiptDigest = committed.get("receipt_digest", String.class); byte[] originalSnapshotBytes = originalSnapshot.getBytes(StandardCharsets.UTF_8); String originalXmin = fixture.associationXmin(associationRequestId); + String originalPayloadXmin = fixture.payloadXmin(associationRequestId); AssociationReceipt recovered = fixture.register(associationRequestId, approval); @@ -400,6 +405,7 @@ void lostAcknowledgementExactRetryReturnsSameOriginalOperationAndBytesWithoutMut assertThat(recovered.snapshot().evidenceDigest()).isEqualTo(originalSnapshotDigest); assertThat(recovered.receiptDigest()).isEqualTo(originalReceiptDigest); assertThat(fixture.associationXmin(associationRequestId)).isEqualTo(originalXmin); + assertThat(fixture.payloadXmin(associationRequestId)).isEqualTo(originalPayloadXmin); assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); } @@ -555,9 +561,21 @@ void persistedRowsRejectUpdateDeleteAndTruncateThroughTheirOwnImmutableTriggers( fixture.dsl.execute( "DELETE FROM game_session_retained_tenant_association WHERE operation_id = ?", operationId)); + SQLException truncateBlockedByForeignKey = + assertSqlState( + () -> fixture.dsl.execute("TRUNCATE game_session_retained_tenant_association"), + "0A000"); + assertThat((Throwable) truncateBlockedByForeignKey) + .hasMessageContaining("cannot truncate a table referenced in a foreign key constraint"); assertCheckViolation( - () -> fixture.dsl.execute("TRUNCATE game_session_retained_tenant_association")); + () -> fixture.dsl.execute("TRUNCATE game_session_retained_tenant_association CASCADE")); assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat( + fixture + .dsl + .fetchOne("SELECT count(*) FROM game_session_retained_tenant_association_payload") + .get(0, Long.class)) + .isEqualTo(1L); } private Fixture fixture() { @@ -588,11 +606,17 @@ private Fixture fixture() { private static void assertCheckViolation( org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertSqlState(action, "23514"); + } + + private static SQLException assertSqlState( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedSqlState) { Throwable failure = catchThrowable(action); assertThat(failure).isInstanceOf(DataAccessException.class); SQLException sqlException = findSqlException(failure); assertThat((Throwable) sqlException).isNotNull(); - assertThat(sqlException.getSQLState()).isEqualTo("23514"); + assertThat(sqlException.getSQLState()).isEqualTo(expectedSqlState); + return sqlException; } private static SQLException findSqlException(Throwable failure) { @@ -730,12 +754,13 @@ UUID insertActiveHold(UUID operationId, UUID holdId) { "INSERT INTO game_session_retained_tenant_association_legal_hold (" + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + "authorization_id, authorized_principal, authorized_at, review_at) " - + "VALUES (?, ?, 'RAW_PAYLOAD', 'LITIGATION', 'test-case-927', ?, " - + "'fixture-authenticated-owner', clock_timestamp() - INTERVAL '2 days', " + + "VALUES (?, ?, 'RAW_PAYLOAD', 'LITIGATION', 'test-case-927', ?, ?, " + + "clock_timestamp() - INTERVAL '2 days', " + "clock_timestamp() + INTERVAL '30 days')", holdId, operationId, - uuid(928))); + uuid(928), + sessionUser())); return holdId; } @@ -746,19 +771,21 @@ void insertInvalidScopeHold(UUID operationId) { "INSERT INTO game_session_retained_tenant_association_legal_hold (" + "hold_id, operation_id, hold_scope, reason_code, case_reference, " + "authorization_id, authorized_principal, authorized_at, review_at) " - + "VALUES (?, ?, 'ACCOUNT_MAPPING', 'LITIGATION', 'bad-scope', ?, " - + "'fixture-authenticated-owner', clock_timestamp(), " + + "VALUES (?, ?, 'ACCOUNT_MAPPING', 'LITIGATION', 'bad-scope', ?, ?, " + + "clock_timestamp(), " + "clock_timestamp() + INTERVAL '30 days')", uuid(929), operationId, - uuid(930))); + uuid(930), + sessionUser())); } void releaseHold(UUID holdId) { dsl.execute( "UPDATE game_session_retained_tenant_association_legal_hold " - + "SET released_at = clock_timestamp(), released_by = 'fixture-authenticated-owner', " + + "SET released_at = clock_timestamp(), released_by = ?, " + "release_reference = 'release-927' WHERE hold_id = ?", + sessionUser(), holdId); } @@ -782,6 +809,20 @@ void releaseHoldForRetentionTest(UUID holdId) { } } + String sessionUser() { + Record row = dsl.fetchOne("SELECT session_user AS db_session_user"); + return Objects.requireNonNull(row).get("db_session_user", String.class); + } + + String captureTimeDaysAgo(int days) { + Record row = + dsl.fetchOne( + "SELECT clock_timestamp() - (?::int * INTERVAL '1 day') AS captured_at", days); + java.time.OffsetDateTime capturedAt = + Objects.requireNonNull(row).get("captured_at", java.time.OffsetDateTime.class); + return capturedAt.toInstant().truncatedTo(java.time.temporal.ChronoUnit.MICROS).toString(); + } + private void withHoldInsertTriggerDisabled(Runnable insert) { dsl.execute( "ALTER TABLE game_session_retained_tenant_association_legal_hold " @@ -871,7 +912,9 @@ AssociationReceipt register( Record storedByRequest(UUID associationRequestId) { return dsl.fetchOne( - "SELECT association.*, payload.approval_manifest_digest, payload.approval_signature " + "SELECT association.*, payload.request_digest, payload.approval_manifest_digest, " + + "payload.approval_signature, payload.snapshot_canonical_json, " + + "payload.snapshot_evidence_digest, payload.receipt_digest " + "FROM game_session_retained_tenant_association association " + "JOIN game_session_retained_tenant_association_payload payload USING (operation_id) " + "WHERE association.target_namespace = ? AND association.association_request_id = ?", @@ -901,6 +944,18 @@ String associationXmin(UUID associationRequestId) { return Objects.requireNonNull(row).get("xmin", String.class); } + String payloadXmin(UUID associationRequestId) { + Record row = + dsl.fetchOne( + "SELECT payload.xmin::text AS xmin " + + "FROM game_session_retained_tenant_association association " + + "JOIN game_session_retained_tenant_association_payload payload USING (operation_id) " + + "WHERE association.target_namespace = ? AND association.association_request_id = ?", + NAMESPACE, + associationRequestId); + return Objects.requireNonNull(row).get("xmin", String.class); + } + String instanceXmin(long instanceId) { Record row = dsl.fetchOne("SELECT xmin::text AS xmin FROM game_instances WHERE id = ?", instanceId); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java index bbae020095..393c51e3d0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java @@ -194,14 +194,15 @@ void capturesCurrentNumericOwnersAndBindsOwnerChangesToSnapshotDigest() throws E fixture.dsl.execute("UPDATE game_instances SET owner_account_id = ? WHERE id = ?", 90011L, 10L); GameSessionRetainedTenantSnapshot changedRawSnapshot = fixture.capture(); - assertThat(changedRawSnapshot.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + assertThat(changedRawSnapshot.projectionDigest()).isNotEqualTo(snapshot.projectionDigest()); JsonNode changedRawOwner = JSON.readTree(changedRawSnapshot.canonicalJson()).get("instances").get(1); assertThat(changedRawOwner.get("owner_account_id").textValue()).isEqualTo("90011"); fixture.dsl.execute("UPDATE game_instances SET owner_account_id = ? WHERE id = ?", 90023L, 22L); GameSessionRetainedTenantSnapshot changedSnapshot = fixture.capture(); - assertThat(changedSnapshot.evidenceDigest()).isNotEqualTo(changedRawSnapshot.evidenceDigest()); + assertThat(changedSnapshot.projectionDigest()) + .isNotEqualTo(changedRawSnapshot.projectionDigest()); JsonNode changedOwner = JSON.readTree(changedSnapshot.canonicalJson()).get("instances").get(3); assertThat(changedOwner.get("owner_account_id").textValue()).isEqualTo("90023"); } @@ -259,7 +260,7 @@ void captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback() throws }); fixture.assertMutationMatrixSucceedsThenRollsBack(); - assertThat(fixture.capture().evidenceDigest()).isEqualTo(originalSnapshot.evidenceDigest()); + assertThat(fixture.capture().projectionDigest()).isEqualTo(originalSnapshot.projectionDigest()); fixture.executeMutation(COMMITTED_INSTANCE_PHANTOM_INSERT); Long instancePhantomCount = java.util.Objects.requireNonNull( @@ -268,8 +269,8 @@ void captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback() throws .get(0, Long.class); assertThat(instancePhantomCount).isEqualTo(1L); GameSessionRetainedTenantSnapshot afterInstanceInsert = fixture.capture(); - assertThat(afterInstanceInsert.evidenceDigest()) - .isNotEqualTo(originalSnapshot.evidenceDigest()); + assertThat(afterInstanceInsert.projectionDigest()) + .isNotEqualTo(originalSnapshot.projectionDigest()); fixture.transactions.execute( status -> { @@ -278,7 +279,8 @@ void captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback() throws return null; }); fixture.assertMutationMatrixSucceedsThenRollsBack(); - assertThat(fixture.capture().evidenceDigest()).isEqualTo(afterInstanceInsert.evidenceDigest()); + assertThat(fixture.capture().projectionDigest()) + .isEqualTo(afterInstanceInsert.projectionDigest()); fixture.executeMutation(COMMITTED_POINTER_PHANTOM_INSERT); Long pointerPhantomCount = java.util.Objects.requireNonNull( @@ -289,8 +291,8 @@ void captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback() throws .get(0, Long.class); assertThat(pointerPhantomCount).isEqualTo(1L); GameSessionRetainedTenantSnapshot afterPointerInsert = fixture.capture(); - assertThat(afterPointerInsert.evidenceDigest()) - .isNotEqualTo(afterInstanceInsert.evidenceDigest()); + assertThat(afterPointerInsert.projectionDigest()) + .isNotEqualTo(afterInstanceInsert.projectionDigest()); } private Fixture fixture() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index fe72388ef3..1875a068dd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -175,7 +175,9 @@ void publishedSnapshotBindsWithoutCreatingOrReadingAV9FixtureCatalog() { runtime.setLaunchDescriptorId("published-launch-v1"); runtime.setReleaseBundleId(77L); runtime.setVersionStateEpoch(4L); + runtime.setGenerationConfigRevision("genrev-4"); runtime.setRunOwnedStartRequestId("4c31b7b9-e9e8-41a4-a5b1-334db8bc49ae"); + runtime.setRunOwnedStartRequestDigest("a".repeat(64)); runtime.setRunOwnedStartPublishedReleaseBundleRef("prb:41:902:77"); GameInstance savedRuntime = gameInstanceRepository.save(runtime); seedAssociation(dsl, 41L, CANONICAL_TENANT_ID, 731L, "source-game-key-not-local-id"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index d8258fc8b0..75ac700bf2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -1621,6 +1621,7 @@ private GameplayWebSocketDriver openFirstPartyDriver( java.time.Duration.ofSeconds(10), transportSessionId, "testsecretkeytestsecretkeytest1234", + ACCOUNT_UUID, connectClaims); } From 0f4f31f4aeb615f0b1960a7060458ad1a0e9da25 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 01:01:51 +1300 Subject: [PATCH 099/105] test: keep retained evidence expiry fixture at microsecond precision --- ...ssionRetainedTenantAssociationRepositoryIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index 648a3e1e5e..a845a14c8c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -723,7 +723,7 @@ void insertExpiredPayload( "fixture-owner-key", "owner-reviewer", "approval-" + operationId, - java.time.Instant.now().toString(), + java.time.Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS).toString(), projectionDigest, "sha256:" + "c".repeat(64), "sha256:" + "d".repeat(64), From 5871aa86eec23ddcbce12771c3e78cc72efeb8e3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:37:16 +1300 Subject: [PATCH 100/105] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d30a730f81..35cf3bf72c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1010,7 +1010,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index ccbb89354c..985a365ce1 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -355,6 +355,44 @@ if "workflow_dispatch" not in events: raise SystemExit("Validation must retain manual dispatch") PYTHON +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1524,6 +1562,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1994,6 +2041,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2026,13 +2074,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2046,8 +2097,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2058,6 +2125,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { From 063c4cba422f0ea2a6536ad341756a08c9091559 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:37:40 +1300 Subject: [PATCH 101/105] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aab6706691..8970557348 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1022,7 +1022,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index ccbb89354c..985a365ce1 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -355,6 +355,44 @@ if "workflow_dispatch" not in events: raise SystemExit("Validation must retain manual dispatch") PYTHON +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1524,6 +1562,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1994,6 +2041,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2026,13 +2074,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2046,8 +2097,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2058,6 +2125,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { From 8ee5e2e0300037e6746714f1c1e58a4982a60a1f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:37:49 +1300 Subject: [PATCH 102/105] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c39fb73c2..f774605114 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1034,7 +1034,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fbe7fadd52..09212667be 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -97,6 +97,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index ccbb89354c..985a365ce1 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -355,6 +355,44 @@ if "workflow_dispatch" not in events: raise SystemExit("Validation must retain manual dispatch") PYTHON +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1524,6 +1562,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1994,6 +2041,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2026,13 +2074,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2046,8 +2097,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2058,6 +2125,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { From 38132de87fdf49b632bff87fd3083bf01a912811 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 03:11:34 +1300 Subject: [PATCH 103/105] Preserve UUID Friends correction before producer extraction --- .../player-access-and-session.md | 1 - .../client/SocialGroupsClient.java | 51 +-- .../command/text/FriendsCommandHandler.java | 94 ++--- .../FriendMutationResultOutput.java | 6 +- .../FriendPresenceViewOutput.java | 2 +- ...ommunicationWebSocketCrossServiceTest.java | 104 +++--- .../text/FriendsCommandHandlerTest.java | 333 +++++++++++------- .../TextPlayerOutputRendererTest.java | 4 +- .../WebSocketOutputProjectorTest.java | 25 +- 9 files changed, 355 insertions(+), 265 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5e00819fe3..f28f3aef08 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -11,7 +11,6 @@ Account's persisted UUID backs registration REST/gRPC output and the Account com The Account source-currentness and first-JOIN persistence stage adds V40 to the inherited V30–V39 authority-storage and retention-safety foundation. Newly repository-created Accounts and genuinely new issuers receive Account-owner-proven sequence-zero source baselines; retained rows are not backfilled. Exact security-relevant Account updates couple source generation, issuance fence, canonical event, and current readback in the owner transaction. The owner-local first-JOIN coordinator retains membership, pair/event, audit, and terminal-operation evidence; this remains preparation only, not authenticated public JOIN, cross-service target-through-commit protection, Game Session text JOIN, or playable proof. The inherited storage stage reports 493 unit tests and 13 targeted physical PostgreSQL cases across separate earlier runs, with 42 integration skips in its no-fixture run; these do not establish reconciled V40/source-currentness/coordinator proof, which remains pending. This stage does not enable signer provisioning, LOGIN, PLAY, or activation. #2898/#2848 gaps and capability statuses remain unchanged. The historical hosted pass for seven `CredentialCleanupRepositoryIntegrationTest` PostgreSQL cases predates the Account source-retention changes. The pre-correction #3010 head `5a261129e65e857e8b7fa7900af8aec99f8cafb7` failed CI run 37448816417 with nine Account integration-test failures: those seven cases failed in shared setup when `TRUNCATE accounts ... CASCADE` reached V40's retained-source guard; the retained-row UUID migration assertion did not account for V40.1's generated nullable approval-reference column; and the first-JOIN replay test retried the low-level producer before the terminal operation proof existed. Test fixtures now preserve Account/source rows and exercise migration and replay through their canonical contracts. The pre-correction CI run also reported protobuf configuration-cache incompatibilities and discarded its cache entry; the authorized local validation invocation for that run reported the same cache diagnostics and completed successfully, so they were not an independent validation failure. The first substantive CI run at head `39453c55924b6ec80f6e5a91b3458206da318b21` completed with one Account integration-test failure: `accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity` omitted V40.1's generated nullable `approved_tenant_payload_operation_id` from its retained connect-scope comparison. The comparison fixture now excludes that migration-added projection field; exact-head CI proof for the correction remains pending. CI run 37456142059 also reported protobuf configuration-cache incompatibilities and discarded its cache entry; these diagnostics were separate from the Account integration-test failure. - This candidate now carries Account UUID through Account authentication, bootstrap, and profile producers; Common Security subject/account matching; Gateway gameplay-handshake validation; and Game Session and Game Logic carriers. Reported focused unit and formatting tasks passed for Account, Common Security, Gateway, Game Logic, and Game Design; the focused Game Session suite passed 262/262. This is candidate source/test proof, not deployed or fresh-runtime proof, and it does not establish global convergence of numeric Account consumers or backfill historical command UUIDs. Canonical identity and namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Account's `ResolveRuntimeAccountIdentity` owner read has focused service proof (7/7) and auth-wiring proof (3/3); Entity Management's Account identity receiver test passed 7/7. Those reads carry persisted UUID and source-row/provenance evidence but do not create membership, grants, actor ownership, a namespace, or admission authority; Game Session caller wiring remains unclaimed. Focused Game Session proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. Game Session now rejects unreadable or wrong-type registry evidence before persisted-context fallback and preserves numeric/opaque account evidence without mutation. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. `PLAYER`/`PLAY`, actor association/namespace roster, and full-stack fresh-smoke proof remain incomplete. #2898 remains unresolved. The Game Design canonical tenant UUID/provenance producer and its Game Session receiver are prepared in a separate retained-tenant association prerequisite, not this Account UUID carrier slice. That prerequisite must prove source identity and exact retained-row association without establishing the current Game Session pointer, playable-state namespace/scope, published actor-entry policy, Entity selection, or actor creation. `PLAY`, actor entry, and #2898 remain incomplete under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java index 050a9b781b..b0e0de1d6d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java @@ -67,107 +67,110 @@ protected SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub buildStub( SocialGroupsServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public ListFriendPresenceResponse listFriendPresence(long tenantId, long accountId) { + public ListFriendPresenceResponse listFriendPresence(long tenantId, String accountId) { return callStub() .listFriendPresence( ListFriendPresenceRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId, FriendRosterFilter filter) { + public ListFriendsResponse listFriends( + long tenantId, String accountId, FriendRosterFilter filter) { return callStub() .listFriends( ListFriendsRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setFilter(filter) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId) { + public ListFriendsResponse listFriends(long tenantId, String accountId) { return listFriends(tenantId, accountId, FriendRosterFilter.FRIEND_ROSTER_FILTER_ALL); } - public AddFriendResponse addFriend(long tenantId, long accountId, long friendAccountId) { + public AddFriendResponse addFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .addFriend( AddFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } - public RemoveFriendResponse removeFriend(long tenantId, long accountId, long friendAccountId) { + public RemoveFriendResponse removeFriend( + long tenantId, String accountId, String friendAccountId) { return callStub() .removeFriend( RemoveFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } public RemoveFriendByOrdinalResponse removeFriendByOrdinal( - long tenantId, long accountId, int ordinal) { + long tenantId, String accountId, int ordinal) { return callStub() .removeFriendByOrdinal( RemoveFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setOrdinal(ordinal) .build()); } - public GetFriendResponse getFriend(long tenantId, long accountId, long friendAccountId) { + public GetFriendResponse getFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .getFriend( GetFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } - public GetFriendByOrdinalResponse getFriendByOrdinal(long tenantId, long accountId, int ordinal) { + public GetFriendByOrdinalResponse getFriendByOrdinal( + long tenantId, String accountId, int ordinal) { return callStub() .getFriendByOrdinal( GetFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setOrdinal(ordinal) .build()); } - public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, long accountId) { + public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, String accountId) { return callStub() .getFriendRosterSummary( GetFriendRosterSummaryRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } - public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, long accountId) { + public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, String accountId) { return callStub() .getFriendPresencePolicy( GetFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } public UpdateFriendPresencePolicyResponse updateFriendPresencePolicy( long tenantId, - long accountId, + String accountId, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy visibilityPolicy) { return callStub() .updateFriendPresencePolicy( UpdateFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setVisibilityPolicy(visibilityPolicy) .build()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 60801b312c..d5dce63380 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.presentation.FriendPresenceViewOutput; import net.firedevops.firemud.gamesession.presentation.FriendRosterSummaryViewOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -72,7 +73,7 @@ public TextCommandInterpretationResult handle(TextCommand command, SessionContex return usageFailure; } try { - numericAccountId(context); + requireCanonicalAccountUuid(context.accountId()); } catch (IllegalArgumentException ex) { return accountIdUnavailable(action); } @@ -182,11 +183,11 @@ private TextCommandInterpretationResult handleList( SessionContext context, FriendListFilter filter, String rawCommandText) { ListFriendsResponse response = filter == FriendListFilter.ALL - ? socialGroupsClient.listFriends(context.tenantId(), numericAccountId(context)) + ? socialGroupsClient.listFriends(context.tenantId(), context.accountId()) : socialGroupsClient.listFriends( - context.tenantId(), numericAccountId(context), mapRosterFilter(filter)); + context.tenantId(), context.accountId(), mapRosterFilter(filter)); if (response == null && filter != FriendListFilter.ALL) { - response = socialGroupsClient.listFriends(context.tenantId(), numericAccountId(context)); + response = socialGroupsClient.listFriends(context.tenantId(), context.accountId()); } if (response.hasError()) { String message = @@ -210,13 +211,13 @@ private TextCommandInterpretationResult handleList( private TextCommandInterpretationResult handleAdd( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == numericAccountId(context)) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } AddFriendResponse response = socialGroupsClient.addFriend( - context.tenantId(), numericAccountId(context), target.friendAccountId()); + context.tenantId(), context.accountId(), target.friendAccountId()); if (response.hasError() || !response.getSuccess()) { String message = response.hasError() && !response.getError().getMessage().isBlank() @@ -234,13 +235,13 @@ private TextCommandInterpretationResult handleAdd( private TextCommandInterpretationResult handleRemove( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == numericAccountId(context)) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } RemoveFriendResponse response = socialGroupsClient.removeFriend( - context.tenantId(), numericAccountId(context), target.friendAccountId()); + context.tenantId(), context.accountId(), target.friendAccountId()); if (response.hasError() || !response.getSuccess()) { String message = response.hasError() && !response.getError().getMessage().isBlank() @@ -260,7 +261,7 @@ private TextCommandInterpretationResult handleDetail( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { GetFriendResponse response = socialGroupsClient.getFriend( - context.tenantId(), numericAccountId(context), target.friendAccountId()); + context.tenantId(), context.accountId(), target.friendAccountId()); if (response.hasError()) { String code = "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -294,8 +295,7 @@ private TextCommandInterpretationResult handleDetailByOrdinal( return invalidUsage("FRIENDS SHOW "); } GetFriendByOrdinalResponse response = - socialGroupsClient.getFriendByOrdinal( - context.tenantId(), numericAccountId(context), ordinal); + socialGroupsClient.getFriendByOrdinal(context.tenantId(), context.accountId(), ordinal); if (response.hasError()) { String code = "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -325,7 +325,7 @@ private TextCommandInterpretationResult handleDetailByOrdinal( private TextCommandInterpretationResult handleSummary( SessionContext context, String rawCommandText) { GetFriendRosterSummaryResponse response = - socialGroupsClient.getFriendRosterSummary(context.tenantId(), numericAccountId(context)); + socialGroupsClient.getFriendRosterSummary(context.tenantId(), context.accountId()); if (response.hasError()) { String message = response.getError().getMessage().isBlank() @@ -358,7 +358,7 @@ private TextCommandInterpretationResult handleSummary( private TextCommandInterpretationResult handleVisibilityView( SessionContext context, String rawCommandText) { GetFriendPresencePolicyResponse response = - socialGroupsClient.getFriendPresencePolicy(context.tenantId(), numericAccountId(context)); + socialGroupsClient.getFriendPresencePolicy(context.tenantId(), context.accountId()); if (response.hasError()) { String code = response.getError().getCode().isBlank() @@ -392,7 +392,7 @@ private TextCommandInterpretationResult handleVisibilityUpdate( } UpdateFriendPresencePolicyResponse response = socialGroupsClient.updateFriendPresencePolicy( - context.tenantId(), numericAccountId(context), visibilityPolicy); + context.tenantId(), context.accountId(), visibilityPolicy); if (response.hasError() || !response.getSuccess()) { String code = response.hasError() && !response.getError().getCode().isBlank() @@ -423,8 +423,7 @@ private TextCommandInterpretationResult handleRemoveByOrdinal( return invalidUsage("FRIENDS REMOVE "); } RemoveFriendByOrdinalResponse response = - socialGroupsClient.removeFriendByOrdinal( - context.tenantId(), numericAccountId(context), ordinal); + socialGroupsClient.removeFriendByOrdinal(context.tenantId(), context.accountId(), ordinal); if (response.hasError() || !response.getSuccess()) { String code = response.hasError() && "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -511,7 +510,7 @@ private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendList private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry entry) { FriendPresenceEntry presence = entry.getPresence(); - long friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); + String friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); String characterName = presence.getCharacterName().isBlank() ? null : presence.getCharacterName().trim(); return new FriendPresenceViewOutput.Entry( @@ -544,23 +543,19 @@ private String activityState(FriendPresenceActivityState activityState) { }; } - private long requireFriendAccountId(String value) { - if (!StringUtils.hasText(value)) { + private String requireFriendAccountId(String value) { + if (!AccountIds.isCanonicalNonNilUuid(value)) { throw new IllegalStateException( - "Malformed friend roster friendAccountId: friendAccountId is required"); - } - try { - return PositiveLongParsing.requireOptionalText(value, "friendAccountId") - .orElseThrow(() -> new IllegalArgumentException("friendAccountId is required")); - } catch (IllegalArgumentException ex) { - throw new IllegalStateException( - "Malformed friend roster friendAccountId: " + ex.getMessage(), ex); + "Malformed friend roster friendAccountId: " + + "friendAccountId must be a canonical non-nil UUID"); } + return value; } - private long numericAccountId(SessionContext context) { - return PositiveLongParsing.requireOptionalText(context.accountId(), "accountId") - .orElseThrow(() -> new IllegalArgumentException("accountId must be positive")); + private void requireCanonicalAccountUuid(String value) { + if (!AccountIds.isCanonicalNonNilUuid(value)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } } private Long parseOptionalLong(String value) { @@ -662,13 +657,21 @@ private FriendAction parseAction(TextCommand command) { } private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction action) { - Long accountId = tryParseAccountId(action.targetToken()); + String accountId = tryParseAccountId(action.targetToken()); if (accountId != null) { return new ResolvedFriendTarget(accountId, null, null); } + if (isNumericAccountId(action.targetToken()) || looksLikeAccountUuid(action.targetToken())) { + return new ResolvedFriendTarget( + null, + null, + friendTargetError( + "INVALID_ARGUMENT", + "Friend account ID must be a canonical non-nil UUID or a character name")); + } if (!StringUtils.hasText(action.targetToken())) { return new ResolvedFriendTarget( - 0L, + null, null, invalidUsage("FRIENDS " + action.keyword() + " ")); } @@ -677,17 +680,16 @@ private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction context, resolvePlayableStateScope(context), action.targetToken().trim()); if (character.isEmpty() || !StringUtils.hasText(character.get().getAccountId())) { return new ResolvedFriendTarget( - 0L, + null, null, friendTargetError("FRIEND_TARGET_NOT_FOUND", notFoundMessage(action.targetToken()))); } - PositiveLongParsing.ParsedPositiveLong parsedAccountId = - PositiveLongParsing.parseOptionalText(character.get().getAccountId(), "friendAccountId"); - if (!parsedAccountId.valid()) { + String resolvedAccountId = character.get().getAccountId(); + if (!AccountIds.isCanonicalNonNilUuid(resolvedAccountId)) { return new ResolvedFriendTarget( - 0L, null, malformedResolvedTargetError(action, character.get().getAccountId())); + null, null, malformedResolvedTargetError(action, resolvedAccountId)); } - return new ResolvedFriendTarget(parsedAccountId.value(), character.get().getName(), null); + return new ResolvedFriendTarget(resolvedAccountId, character.get().getName(), null); } private TextCommandInterpretationResult malformedResolvedTargetError( @@ -769,10 +771,16 @@ private FriendRosterFilter mapRosterFilter(FriendListFilter filter) { }; } - private Long tryParseAccountId(String value) { - return PositiveLongParsing.parseOptionalText(value, "friendAccountId") - .optionalValue() - .orElse(null); + private String tryParseAccountId(String value) { + return AccountIds.isCanonicalNonNilUuid(value) ? value : null; + } + + private boolean isNumericAccountId(String value) { + return value != null && value.matches("[+-]?\\d+"); + } + + private boolean looksLikeAccountUuid(String value) { + return value != null && value.matches("(?i)[0-9a-f-]{36}"); } private boolean isOrdinalToken(String value) { @@ -947,5 +955,5 @@ private record FriendAction( String invalidUsage) {} private record ResolvedFriendTarget( - long friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} + String friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java index 0bd9a89cfd..c17bf5c6f9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java @@ -4,7 +4,11 @@ /** Structured payload for canonical friend add/remove mutation results. */ public record FriendMutationResultOutput( - String action, long friendAccountId, String displayName, String characterName, Integer ordinal) + String action, + String friendAccountId, + String displayName, + String characterName, + Integer ordinal) implements PlayerOutputPayload { public FriendMutationResultOutput { Objects.requireNonNull(action, "action must not be null"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java index b31bff8ecb..a7e564dd09 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java @@ -12,7 +12,7 @@ public record FriendPresenceViewOutput( public record Entry( int ordinal, Long friendLinkId, - long friendAccountId, + String friendAccountId, String status, Long linkedAtEpochMs, String displayName, diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 02c21a47ff..c43872b28f 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -36,6 +36,10 @@ class CommunicationWebSocketCrossServiceTest { private static final long ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); private static final long NYX_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); + private static final String ACCOUNT_UUID = + AccountRuntimeStubServer.accountUuidForTestFixture(ACCOUNT_ID); + private static final String SORA_ACCOUNT_UUID = + AccountRuntimeStubServer.accountUuidForTestFixture(SORA_ACCOUNT_ID); private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; private static final String FIRST_PARTY_CONNECT_SECRET = "cross-service-connect-context-secret"; @@ -171,7 +175,7 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { runCommunicationSequence( sessionId, "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses) @@ -179,10 +183,10 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { response -> response.contains( "Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( - socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -196,7 +200,7 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { "FRIENDS ONLINE", "Friends ONLINE [1/1]:\n" + "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) @@ -205,12 +209,12 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { response.contains("Friends ONLINE [1/1]:") && response.contains( "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @@ -225,7 +229,7 @@ void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { "FRIENDS SHARED", "Friends SHARED [1/1]:\n" + "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) @@ -234,12 +238,12 @@ void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { response.contains("Friends SHARED [1/1]:") && response.contains( "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); } @@ -254,14 +258,14 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc runCommunicationSequence( sessionId, "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) .anyMatch( response -> response.contains( "Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); } @@ -272,22 +276,22 @@ void websocketFriendsMutationFlowUsesCanonicalRosterSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-conn")) { - client.send("FRIENDS ADD 77"); - client.awaitContains("Friend #77 added."); - client.send("FRIENDS REMOVE 77"); - client.awaitContains("Friend #77 removed."); + client.send("FRIENDS ADD " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " added."); + client.send("FRIENDS REMOVE " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -298,21 +302,21 @@ void websocketFriendsMutationByCharacterNameUsesCanonicalIdentityLookup() throws try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-name-conn")) { client.send("FRIENDS ADD Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] added."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] added."); client.send("FRIENDS REMOVE Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -323,14 +327,11 @@ void websocketFriendsRemoveByRosterOrdinalUsesRenderedRosterIdentity() throws Ex try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-remove-ordinal-conn")) { client.send("FRIENDS REMOVE #1"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertRemoveFriendByOrdinalRequest( - socialStub().lastRemoveFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastRemoveFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -341,16 +342,13 @@ void websocketFriendsShowUsesCanonicalFriendDetailSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-show-detail-conn")) { client.send("FRIENDS SHOW #1"); - client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_ID + "]"); + client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_UUID + "]"); client.awaitContains("Presence: online in Demo World / Live Realm (idle)"); client.awaitContains("Roster entry: #1"); } GameplaySocialAssertions.assertGetFriendByOrdinalRequest( - socialStub().lastGetFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastGetFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -369,7 +367,7 @@ void websocketFriendsSummaryUsesCanonicalRosterSummarySurface() throws Exception } GameplaySocialAssertions.assertFriendRosterSummaryRequest( - socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -387,13 +385,11 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { } GameplaySocialAssertions.assertGetVisibilityRequest( - socialStub().lastGetVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID)); + socialStub().lastGetVisibilityRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); GameplaySocialAssertions.assertUpdateVisibilityRequest( socialStub().lastUpdateVisibilityRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } @@ -439,8 +435,8 @@ void websocketFirstPartyFriendsViewsUseStructuredCanonicalPayloads() throws Exce JsonNode friendsPayload = requirePayload(friends, "friends_view"); assertThat(friends.path("accepted").asBoolean()).isTrue(); assertThat(friendsPayload.path("filter").asText()).isEqualTo("ALL"); - assertThat(friendsPayload.path("friends").get(0).path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); + assertThat(friendsPayload.path("friends").get(0).path("friendAccountId").asText()) + .isEqualTo(SORA_ACCOUNT_UUID); assertThat(friendsPayload.path("friends").get(0).path("playableStateScope").asText()) .isEqualTo("SHARED"); @@ -449,8 +445,8 @@ void websocketFirstPartyFriendsViewsUseStructuredCanonicalPayloads() throws Exce JsonNode detail = awaitStructuredCommand(client, baseline, "FRIENDS"); JsonNode detailPayload = requirePayload(detail, "friend_detail_view"); assertThat(detailPayload.path("friend").path("ordinal").asInt()).isEqualTo(1); - assertThat(detailPayload.path("friend").path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); + assertThat(detailPayload.path("friend").path("friendAccountId").asText()) + .isEqualTo(SORA_ACCOUNT_UUID); baseline = client.responses().size(); client.send("FRIENDS SUMMARY"); @@ -484,13 +480,11 @@ void websocketFirstPartyFriendsVisibilityUsesStructuredPolicyPayloads() throws E } GameplaySocialAssertions.assertGetVisibilityRequest( - socialStub().lastGetVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID)); + socialStub().lastGetVisibilityRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); GameplaySocialAssertions.assertUpdateVisibilityRequest( socialStub().lastUpdateVisibilityRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } @@ -501,12 +495,12 @@ void websocketFirstPartyFriendsMutationsUseStructuredCanonicalPayloads() throws try (GameplayWebSocketDriver client = openFirstPartyGameplayClient("friends-add-first-party")) { int baseline = client.responses().size(); - client.send("FRIENDS ADD 77"); + client.send("FRIENDS ADD " + SORA_ACCOUNT_UUID); JsonNode added = awaitStructuredCommand(client, baseline, "FRIENDS"); JsonNode addPayload = requirePayload(added, "friend_mutation_result"); assertThat(addPayload.path("action").asText()).isEqualTo("ADD"); - assertThat(addPayload.path("friendAccountId").asLong()).isEqualTo(77L); - assertThat(addPayload.path("displayName").asText()).isEqualTo("Friend #77"); + assertThat(addPayload.path("friendAccountId").asText()).isEqualTo(SORA_ACCOUNT_UUID); + assertThat(addPayload.path("displayName").asText()).isEqualTo("Friend #" + SORA_ACCOUNT_UUID); } prepareGameInstance(); @@ -517,7 +511,7 @@ void websocketFirstPartyFriendsMutationsUseStructuredCanonicalPayloads() throws JsonNode removedByName = awaitStructuredCommand(client, baseline, "FRIENDS"); JsonNode removeByNamePayload = requirePayload(removedByName, "friend_mutation_result"); assertThat(removeByNamePayload.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeByNamePayload.path("friendAccountId").asLong()).isEqualTo(SORA_ACCOUNT_ID); + assertThat(removeByNamePayload.path("friendAccountId").asText()).isEqualTo(SORA_ACCOUNT_UUID); assertThat(removeByNamePayload.path("displayName").asText()).isEqualTo("Sora"); assertThat(removeByNamePayload.path("characterName").asText()).isEqualTo("Sora"); } @@ -530,8 +524,8 @@ void websocketFirstPartyFriendsMutationsUseStructuredCanonicalPayloads() throws JsonNode removedByOrdinal = awaitStructuredCommand(client, baseline, "FRIENDS"); JsonNode removeByOrdinalPayload = requirePayload(removedByOrdinal, "friend_mutation_result"); assertThat(removeByOrdinalPayload.path("action").asText()).isEqualTo("REMOVE"); - assertThat(removeByOrdinalPayload.path("friendAccountId").asLong()) - .isEqualTo(SORA_ACCOUNT_ID); + assertThat(removeByOrdinalPayload.path("friendAccountId").asText()) + .isEqualTo(SORA_ACCOUNT_UUID); assertThat(removeByOrdinalPayload.path("ordinal").asInt()).isEqualTo(1); } } @@ -861,7 +855,7 @@ private static synchronized void ensureTestServicesStarted() throws Exception { net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse.newBuilder() .addPresences( FriendPresenceEntry.newBuilder() - .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setFriendAccountId(SORA_ACCOUNT_UUID) .setOnline(true) .setCharacterId(ChatTestFixtures.PLAYER_SORA) .setCharacterName("Sora") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index 7b7d5aa4b8..482c33be33 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -39,11 +39,15 @@ class FriendsCommandHandlerTest { private record InvalidAccountAction(List args, String errorCode, String message) {} + private static final String CALLER_ACCOUNT_ID = "a0000000-0000-4000-8000-000000000041"; + private static final String FRIEND_ACCOUNT_ID = "b0000000-0000-4000-8000-000000000077"; + private static final String OTHER_FRIEND_ACCOUNT_ID = "c0000000-0000-4000-8000-000000000088"; + private static final SessionContext GAMEPLAY_CONTEXT = new SessionContext( 7L, 1L, - "41", + CALLER_ACCOUNT_ID, "demo@example.com", 99L, "Emberline", @@ -118,7 +122,16 @@ void unsupportedAccountIdsFailByActionBeforeEntitySocialOrEventCalls() { "FRIEND_VISIBILITY_UPDATE_UNAVAILABLE", "Friend presence visibility update unavailable")); - for (String accountId : List.of("opaque-account-uuid", "", "0", "-41")) { + for (String accountId : + List.of( + "opaque-account-uuid", + "", + "0", + "-41", + "41", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000007-", + CALLER_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT))) { SessionContext context = gameplayContextWithAccountId(accountId); for (InvalidAccountAction action : actions) { TextCommandInterpretationResult result = @@ -173,22 +186,22 @@ void usageErrorsRemainVisibleBeforeUnsupportedAccountFailure() { } @Test - void friendsListPreservesMaximumPositiveLongAccountId() { + void friendsListPassesCanonicalAccountUuidUnchanged() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.listFriends(1L, Long.MAX_VALUE)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn(ListFriendsResponse.newBuilder().build()); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.FRIENDS, List.of(), "FRIENDS"), - gameplayContextWithAccountId(Long.toString(Long.MAX_VALUE))); + gameplayContextWithAccountId(CALLER_ACCOUNT_ID)); assertThat(result.commandResult().accepted()).isTrue(); - Mockito.verify(socialGroupsClient).listFriends(1L, Long.MAX_VALUE); + Mockito.verify(socialGroupsClient).listFriends(1L, CALLER_ACCOUNT_ID); Mockito.verify(scriptEventPublisher).publishCommandEvent(Mockito.any(), Mockito.any()); } @@ -199,16 +212,16 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterId("99") .setCharacterName("Sora") @@ -243,7 +256,7 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { .satisfies( entry -> { assertThat(entry.friendLinkId()).isNull(); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.status()).isEqualTo("active"); assertThat(entry.linkedAtEpochMs()).isNull(); assertThat(entry.displayName()).isEqualTo("Sora"); @@ -253,7 +266,8 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Sora [acct #77] - online in Demo World / Live Realm (idle)"); + .contains( + "Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.any(), @@ -272,16 +286,16 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -306,7 +320,7 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { entry -> { assertThat(entry.friendLinkId()).isNull(); assertThat(entry.status()).isEqualTo("active"); - assertThat(entry.displayName()).isEqualTo("Friend #77"); + assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); assertThat(entry.lastSeenAtEpochMs()) .isEqualTo(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()); assertThat(entry.recentDisposition()).isEqualTo("LOGOUT"); @@ -320,13 +334,15 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("ADD", "77"), "friends add 77"), + TextCommandType.FRIENDS, + java.util.List.of("ADD", FRIEND_ACCOUNT_ID), + "FRIENDS ADD " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -334,12 +350,12 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 added."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -349,7 +365,8 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { Mockito.argThat( gameplayCommand -> "FRIENDS".equals(gameplayCommand.getCommandName()) - && "friends add 77".equals(gameplayCommand.getCommandText()))); + && ("FRIENDS ADD " + FRIEND_ACCOUNT_ID) + .equals(gameplayCommand.getCommandText()))); } @Test @@ -359,7 +376,8 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE) @@ -368,10 +386,10 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .build()) @@ -396,9 +414,9 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) .contains("Friends ONLINE [1/2]:") - .contains("1) Sora [acct #77] - online"); + .contains("1) Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @Test @@ -408,7 +426,8 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE) @@ -417,10 +436,10 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(2) - .setFriendAccountId("88") + .setFriendAccountId(OTHER_FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("88") + .setFriendAccountId(OTHER_FRIEND_ACCOUNT_ID) .setOnline(false) .setVisibilityPolicy( net.firedevops.firemud.socialgroups.v1 @@ -446,7 +465,7 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .satisfies( entry -> { assertThat(entry.ordinal()).isEqualTo(2); - assertThat(entry.friendAccountId()).isEqualTo(88L); + assertThat(entry.friendAccountId()).isEqualTo(OTHER_FRIEND_ACCOUNT_ID); assertThat(entry.visibilityPolicy()).isEqualTo("PRIVATE"); }); assertThat( @@ -455,7 +474,7 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .render(result.outputs().getFirst())) .contains("Friends PRIVATE [1/2]:"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE); } @Test @@ -465,7 +484,8 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED) @@ -474,10 +494,10 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setPlayableStateScope( @@ -501,7 +521,7 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .satisfies( entry -> { assertThat(entry.ordinal()).isEqualTo(1); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.playableStateScope()).isEqualTo("SHARED"); }); assertThat( @@ -510,7 +530,7 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .render(result.outputs().getFirst())) .contains("Friends SHARED [1/2]:"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); } @Test @@ -520,7 +540,8 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT) @@ -529,10 +550,10 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -552,7 +573,7 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() - .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(77L)); + .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID)); } @Test @@ -562,7 +583,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendRosterSummary(1L, 41L)) + when(socialGroupsClient.getFriendRosterSummary(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendRosterSummaryResponse.newBuilder() .setSummary( @@ -621,7 +642,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { .contains("Visibility private: 1") .contains("Scope shared: 2") .contains("Scope isolated: 1"); - Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, CALLER_ACCOUNT_ID); } @Test @@ -637,8 +658,12 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -652,15 +677,15 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] added."); + assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).addFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -670,13 +695,15 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("REMOVE", "77"), "FRIENDS REMOVE 77"), + TextCommandType.FRIENDS, + java.util.List.of("REMOVE", FRIEND_ACCOUNT_ID), + "FRIENDS REMOVE " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -684,12 +711,12 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 removed."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -708,8 +735,12 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -725,15 +756,16 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).removeFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -743,17 +775,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) .setRemovedFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setCharacterName("Sora") .build()) .build()) @@ -770,16 +802,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); assertThat(mutation.ordinal()).isEqualTo(1); }); - Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test @@ -789,7 +822,7 @@ void friendsRemoveByOrdinalRejectsMalformedReturnedFriendAccountId() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) @@ -823,18 +856,18 @@ void friendsShowReturnsCanonicalFriendDetailView() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriend(1L, 41L, 77L)) + when(socialGroupsClient.getFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn( GetFriendResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setFriendLinkId("11") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setCreatedAtMs(Instant.parse("2026-04-10T01:02:03Z").toEpochMilli()) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setWorldDisplayName("Demo World") @@ -852,7 +885,9 @@ void friendsShowReturnsCanonicalFriendDetailView() { TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("SHOW", "77"), "FRIENDS SHOW 77"), + TextCommandType.FRIENDS, + java.util.List.of("SHOW", FRIEND_ACCOUNT_ID), + "FRIENDS SHOW " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -861,7 +896,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { .extracting(PlayerOutput::payload) .isInstanceOf(FriendDetailViewOutput.class); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); - assertThat(detail.friend().friendAccountId()).isEqualTo(77L); + assertThat(detail.friend().friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(detail.friend().friendLinkId()).isEqualTo(11L); assertThat(detail.friend().characterName()).isEqualTo("Sora"); assertThat(detail.friend().playableStateScope()).isEqualTo("SHARED"); @@ -870,7 +905,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friend Sora [acct #77]") + .contains("Friend Sora [acct #" + FRIEND_ACCOUNT_ID + "]") .contains("Presence: online in Demo World / Live Realm (idle)") .contains("State scope: shared") .contains("Pointer version: 17"); @@ -883,16 +918,16 @@ void friendsShowByOrdinalUsesCanonicalDetailSurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( GetFriendByOrdinalResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setCharacterName("Sora") .build()) .build()) @@ -907,39 +942,72 @@ void friendsShowByOrdinalUsesCanonicalDetailSurface() { assertThat(result.commandResult().accepted()).isTrue(); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); assertThat(detail.friend().ordinal()).isEqualTo(1); - Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test - void friendsAddAndRemoveRejectSelfLinkForEquivalentNumericAccountText() { + void friendsAddAndRemoveRejectSelfLinkByCanonicalUuid() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - for (String accountIdText : List.of("41", "041", "+41")) { - SessionContext context = gameplayContextWithAccountId(accountIdText); - for (String action : List.of("ADD", "REMOVE")) { - TextCommandInterpretationResult result = - handler.handle( - new TextCommand( - TextCommandType.FRIENDS, List.of(action, "41"), "FRIENDS " + action + " 41"), - context); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_SELF_LINK_FORBIDDEN"); - assertThat(result.outputs()) - .singleElement() - .extracting(PlayerOutput::text) - .isEqualTo( - "ERROR FRIEND_SELF_LINK_FORBIDDEN Cannot add or remove your own account as a friend"); - } + for (String action : List.of("ADD", "REMOVE")) { + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, + List.of(action, CALLER_ACCOUNT_ID), + "FRIENDS " + action + " " + CALLER_ACCOUNT_ID), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_SELF_LINK_FORBIDDEN"); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo( + "ERROR FRIEND_SELF_LINK_FORBIDDEN Cannot add or remove your own account as a friend"); } Mockito.verifyNoInteractions(socialGroupsClient, entityManagementClient, scriptEventPublisher); } + @Test + void friendsMutationsRejectLegacyNumericAccountIdsWithoutResolvingThemAsNames() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + FriendsCommandHandler handler = + newHandler( + socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); + + for (String legacyId : + List.of( + "77", + "+77", + "00077", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000007-", + FRIEND_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT))) { + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, List.of("ADD", legacyId), "FRIENDS ADD " + legacyId), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo( + "ERROR INVALID_ARGUMENT Friend account ID must be a canonical non-nil UUID or a character name"); + } + + Mockito.verifyNoInteractions(socialGroupsClient, entityManagementClient); + } + @Test void friendsMutationRejectsMissingTarget() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); @@ -968,7 +1036,7 @@ void friendsRemoveRejectsUnknownRosterOrdinal() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(false) @@ -1058,16 +1126,18 @@ void friendsListTreatsMalformedFriendLinkIdAsAbsent() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() .setFriendLinkId("abc") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( - FriendPresenceEntry.newBuilder().setFriendAccountId("77").build()) + FriendPresenceEntry.newBuilder() + .setFriendAccountId(FRIEND_ACCOUNT_ID) + .build()) .build()) .build()); @@ -1085,32 +1155,42 @@ void friendsListTreatsMalformedFriendLinkIdAsAbsent() { } @Test - void friendsListRejectsMalformedFriendAccountIdPayload() { + void friendsListRejectsLegacyNilAndMalformedFriendAccountIdPayloads() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) - .thenReturn( - ListFriendsResponse.newBuilder() - .addFriends( - FriendRosterEntry.newBuilder() - .setFriendAccountId("abc") - .setStatus("active") - .setPresence( - FriendPresenceEntry.newBuilder().setFriendAccountId("abc").build()) - .build()) - .build()); - - TextCommandInterpretationResult result = - handler.handle( - new TextCommand(TextCommandType.FRIENDS, java.util.List.of(), "FRIENDS"), - GAMEPLAY_CONTEXT); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_PRESENCE_UNAVAILABLE"); - assertThat(result.commandResult().errorMessage()).isEqualTo("Friend presence unavailable"); + for (String invalidAccountId : + List.of( + "abc", + "77", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000007-", + FRIEND_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT))) { + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) + .thenReturn( + ListFriendsResponse.newBuilder() + .addFriends( + FriendRosterEntry.newBuilder() + .setFriendAccountId(invalidAccountId) + .setStatus("active") + .setPresence( + FriendPresenceEntry.newBuilder() + .setFriendAccountId(invalidAccountId) + .build()) + .build()) + .build()); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommand(TextCommandType.FRIENDS, java.util.List.of(), "FRIENDS"), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_PRESENCE_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()).isEqualTo("Friend presence unavailable"); + } } @Test @@ -1120,7 +1200,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setCurrentPolicy( @@ -1155,7 +1235,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { .render(result.outputs().getFirst())) .contains("Friend presence visibility: FRIENDS_ONLY") .contains("Use FRIENDS VISIBILITY ."); - Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID); } @Test @@ -1165,7 +1245,7 @@ void friendsVisibilityViewFailsClosedWhenCanonicalPolicyReadIsUnavailable() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setError( @@ -1198,7 +1278,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1235,7 +1315,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { Mockito.verify(socialGroupsClient) .updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); Mockito.verify(scriptEventPublisher) @@ -1253,7 +1333,7 @@ void friendsVisibilityUpdateFailsClosedWhenCanonicalPolicyUpdateIsUnavailable() socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1306,7 +1386,7 @@ void friendsVisibilityRejectsReservedHiddenStaffPolicy() { .isEqualTo( "ERROR INVALID_ARGUMENT HIDDEN_STAFF is reserved and cannot be set from gameplay"); Mockito.verify(socialGroupsClient, Mockito.never()) - .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); + .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyString(), Mockito.any()); } @Test @@ -1340,7 +1420,7 @@ void friendsUnspecifiedVisibilityUsesCanonicalFilterAlias() { newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); when(socialGroupsClient.listFriends( - 1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY)) + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY) @@ -1359,6 +1439,7 @@ void friendsUnspecifiedVisibilityUsesCanonicalFilterAlias() { (FriendPresenceViewOutput) result.outputs().getFirst().payload(); assertThat(view.filter()).isEqualTo("UNSPECIFIED_VISIBILITY"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY); + .listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index bdae4a8cdc..2b2ef9403d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -1069,7 +1069,7 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + "00000000-0000-4000-8000-000000000041", "ONLINE", null, "Sora", @@ -1095,7 +1095,7 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { assertThat(rendered) .isEqualTo( "OK FRIENDS\n" - + "Friend Sora [acct #41]\n" + + "Friend Sora [acct #00000000-0000-4000-8000-000000000041]\n" + "Link: #77\n" + "Status: online\n" + "Presence: online in Demo World / Ember Realm (active)\n" diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index bf36dd9d4d..919e02edc4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -254,7 +254,7 @@ void genericWebSocketProjectsFriendViewThroughFriendsRenderer() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + "00000000-0000-4000-8000-000000000041", "ONLINE", null, "Sora", @@ -422,7 +422,7 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -448,7 +448,7 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -480,8 +480,8 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { .path("friends") .get(0) .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo("00000000-0000-4000-8000-000000000003"); assertThat( json.path("outputs") .get(0) @@ -549,7 +549,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -571,7 +571,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -600,8 +600,8 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { .path("payload") .path("friend") .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo("00000000-0000-4000-8000-000000000003"); assertThat( json.path("outputs") .get(0) @@ -707,7 +707,8 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); FriendMutationResultOutput payloadView = - new FriendMutationResultOutput("REMOVE", 77L, "Sora", "Sora", 1); + new FriendMutationResultOutput( + "REMOVE", "00000000-0000-4000-8000-000000000077", "Sora", "Sora", 1); String payload = projector.projectCommandResponse( @@ -725,8 +726,8 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { .isEqualTo("friend_mutation_result"); assertThat(json.path("outputs").get(0).path("payload").path("action").asText()) .isEqualTo("REMOVE"); - assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asLong()) - .isEqualTo(77L); + assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asText()) + .isEqualTo("00000000-0000-4000-8000-000000000077"); assertThat(json.path("outputs").get(0).path("payload").path("displayName").asText()) .isEqualTo("Sora"); assertThat(json.path("outputs").get(0).path("payload").path("ordinal").asInt()).isEqualTo(1); From 89b327ebe60ef0474b3d96e28659a1c3a20a6940 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 04:09:11 +1300 Subject: [PATCH 104/105] Keep Game Design association migrations collision-free after parent reconciliation --- ...ns.sql => V33__game_session_tenant_association_operations.sql} | 0 ...=> V34__game_session_tenant_association_payload_retention.sql} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename services/game-design-service/src/main/resources/db/migration/{V30__game_session_tenant_association_operations.sql => V33__game_session_tenant_association_operations.sql} (100%) rename services/game-design-service/src/main/resources/db/migration/{V32__game_session_tenant_association_payload_retention.sql => V34__game_session_tenant_association_payload_retention.sql} (100%) diff --git a/services/game-design-service/src/main/resources/db/migration/V30__game_session_tenant_association_operations.sql b/services/game-design-service/src/main/resources/db/migration/V33__game_session_tenant_association_operations.sql similarity index 100% rename from services/game-design-service/src/main/resources/db/migration/V30__game_session_tenant_association_operations.sql rename to services/game-design-service/src/main/resources/db/migration/V33__game_session_tenant_association_operations.sql diff --git a/services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql b/services/game-design-service/src/main/resources/db/migration/V34__game_session_tenant_association_payload_retention.sql similarity index 100% rename from services/game-design-service/src/main/resources/db/migration/V32__game_session_tenant_association_payload_retention.sql rename to services/game-design-service/src/main/resources/db/migration/V34__game_session_tenant_association_payload_retention.sql From 7d84487939919ef756978be2e1c5036101a699c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 04:31:10 +1300 Subject: [PATCH 105/105] Normalize reconciled player tracker table spacing --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5fe024dea8..764cb60f5a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -45,7 +45,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [runtime_account_identity_service.proto](../../../protos/account/v1/runtime_account_identity_service.proto); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [RuntimeAccountIdentityGrpcAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. The current candidate now emits canonical Account UUID identity in the covered authentication/bootstrap/profile producers and binds matching JWT subject/account claims, with the cross-service carriers and focused proof summarized above; owner-local numeric source-row storage is retained. Tenant identifiers and unrelated numeric-only account consumers remain unconverted, while full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.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); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session direct-text scope/JOIN dispatch is implemented locally under #2898; first-party `Join & Play` remains unavailable. Complete membership authority-generation semantics, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.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); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session direct-text scope/JOIN dispatch is implemented locally under #2898; first-party `Join & Play` remains unavailable. Complete membership authority-generation semantics, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [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); [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) | [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) | [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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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 `DeleteAccount` fails closed at AccountRepository's hard-delete boundary, but retained-data lifecycle and deletion reconciliation remain unimplemented. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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`. |