diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 818fef7121..01ff15032f 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -150,7 +150,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. -- `IssueDirectTextConnectScope` – implemented local internal Account RPC for issuing a direct-text connect scope. Game Session text `REALMS` dispatch to this RPC remains pending under #2898. The request carries authenticated caller context in typed `PlayerExecutionContext` plus the server-resolved target; Account validates caller context separately from the short-lived scope and returns an opaque `connectScopeId` bound to the evaluated routing snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Reachable missing or invalid routing evidence fails as `ADMISSION_POINTER_UNAVAILABLE`; a changed exact routing pair fails as `CONNECT_SCOPE_MISMATCH`; unavailable authority fails as `AUTH_UNAVAILABLE`. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. +- `IssueDirectTextConnectScope` – implemented local internal Account RPC for issuing a direct-text connect scope. Game Session text `REALMS` dispatch to this RPC remains pending under #2898. The request carries typed `PlayerExecutionContext` scope data plus the server-resolved target. The certificate-derived Game Session mTLS workload identity authenticates the caller; Account validates the context against that trusted caller and Account-owned records separately from the short-lived scope, and returns an opaque `connectScopeId` with its expiry. After routing and entitlement validation, Account samples its own immutable `evaluatedAt` and binds it into the issued scope snapshot; this timestamp is not supplied by or inherited from the retained routing snapshot. Game Session retains the returned timestamp rather than deriving one from its clock or the expiry. Missing, ambiguous, or unavailable entitlement records fail as `ENTITLEMENT_UNAVAILABLE`, distinct from reachable missing or invalid routing evidence (`ADMISSION_POINTER_UNAVAILABLE`), a changed exact routing pair (`CONNECT_SCOPE_MISMATCH`), or unavailable routing authority (`AUTH_UNAVAILABLE`). An authoritative entitlement that denies gameplay returns `TENANT_BILLING_BLOCKED`. This RPC is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). - `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. 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 fd23aa4e70..ca2734d7e3 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -32,6 +32,8 @@ The sections below define the target-state runtime contract. Current implementat - **Current first-party receiving boundary:** Game Session's prepared receiver verifies the Gateway-signed context and rechecks the canonical target and retained private-handle evidence. When that first-party context is present, bare `LOGIN` and `PLAY` return `FIRST_PARTY_AUTHORITY_UNAVAILABLE` before legacy Account authentication, Entity resolution, or gameplay binding effects. Recovery from registry loss still requires the persisted compact JWS to remain valid; registry loss does not extend its expiry. The public Gateway cookie path is currently denied and its gameplay-route readiness is `OUT_OF_SERVICE`; no first-party wire success or admission is claimed. Account context production, shared replay fencing, and dedicated Gateway key qualification remain open. +- **Direct-text WORLDS menu retention:** the manually composed menu store and one-key Redis script retain only the public `WORLDS` UI snapshot under the tenantless proxy-UUID family. The numeric transport session ID and the exact observed proxy UUID remain separate correlation values; neither an observed UUID nor Redis `ACL WHOAMI` establishes authenticated receiving custody or LOGIN/JOIN authority. Missing, expired, reset, or source-stale menu state requires a fresh `WORLDS` request and cannot recreate or clear authentication state. Production protected-connection binding, receiving-chain provenance and hidden rebind remain gaps; the source has no deployed ACL change. Focused component and physical Redis proof is recorded in the owning tracker, without establishing genuine receiving custody or registration. See [the Redis menu contract](../../system-architecture-redis.md#direct-text-worlds-ui-menu) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation). + - Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. - Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). @@ -81,6 +83,14 @@ The sections below define the target-state runtime contract. Current implementat - Credential brute-force defense remains delegated to Account Service, which owns one login-attempt policy across transport paths using trusted source context. Game Session consumes the resulting auth outcomes when binding gameplay sessions but does not implement separate credential-abuse logic. The target ordinary gameplay limiter is an in-process session-front-end token bucket under [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); the current implementation still uses a Redis-backed per-session limiter and does not yet prove the target role isolation or loss behavior. Before a restart or takeover initializes a replacement bucket, the target owner atomically reserves from the binding's shared bounded cumulative handoff budget, so retries or concurrent replacements cannot reset or double-consume the remaining allowance. Optional coarse shared abuse windows remain outside the per-command fast path. - No single Game Session process may become the hidden source of truth for reconnectable gameplay state. If the service needs a value to survive non-edge restart or permit same-type takeover, that value must live in Redis or PostgreSQL-backed coordination rather than only in process memory. Realm admission additionally requires a fresh World lifecycle row/epoch read under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); Temporal status is coordination evidence, not admission authority. +### Direct-text authenticated lobby companion + +The separately owned `game_session_direct_text_authenticated_lobby_scope`, `game_session_direct_text_authenticated_lobby_current` and `game_session_direct_text_authenticated_lobby_join` tables retain pre-admission lobby scope and JOIN-original state. They reference the original LOGIN journal without adding realm, tenant-admission or JOIN lifecycle to that minimal journal or its closed live-context codec. The [Authentication contract](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) owns the caller-bound scope and logical-attempt behavior. + +New scope and dispatch claims serialize with original LOGIN abandonment through the parent row lock and exact original-coordinate/witness comparison. Current selection is separate from retained attempt history: replacing a selection or observing expiry cannot erase an older uncertain JOIN. A frozen JOIN original is committed and independently read back before dispatch becomes possible; an uncertain reply never resets that original or supplies a new request identity. Positive exact-original receipts may be retained after custody is lost, without applying them to a replacement transport or granting admission. + +This companion preserves the existing SQL retention hold. Direct deletion, truncation and invalid identity/state transitions are refused; no expiry-based release or cleanup API is supplied. Before this owner becomes reachable, new scope intake per original LOGIN must be bounded and qualified under repeated and concurrent REALMS requests. Intake refusal must preserve all retained scopes and uncertain JOIN originals; expiry, selection replacement or capacity pressure cannot evict them. The current preparation does not implement that intake bound or establish a retention/archival horizon, so live registration remains held on capacity qualification as well as lawful release. Parent token disposal is not a membership JOIN outcome. Full negative-terminal qualification, unknown-result recovery and lawful release remain at their owning later boundary. Rows, decoded state and matching witnesses do not establish live socket authentication; each operation still needs its current verified Account result and protected receiving custody. Credentials and compact tokens are excluded from stored lobby state. Production composition and proof status are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation). + ### Protected Human initial-admission storage The protected reservation retains the complete Account protection and original owner association on the Game Session attempt. A separate immutable runtime-completion record binds that protection to the exact launch, captured `STARTING` row version, and completed `RUNNING` row version; this completion changes no admission pointer or terminal. The manually composed, final completion repository explicitly requires its caller's active writable `READ COMMITTED` transaction at runtime, without Spring transaction-proxy registration. The existing initial-admission owner later writes the pointer, matching append-only audit, and immutable protected attempt/intent terminal together, while the Account-purpose read exposes the retained exact terminal for settlement. Protected abort terminalizes only its own retained attempt and intent. Its `EXPECT_CLOSED` storage lookup verifies the immutable original CLOSED request/catalog/audit without locking a later current pointer; positive commit retains the current-origin checks. Legacy unprotected rows remain readable but are not adopted as protected attempts. These local storage owners remain unregistered; the [API contract](./api-contracts.md#initial-admission-bind) owns the cross-owner behavior and the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) records proof and remaining limits. diff --git a/design/architecture/system-architecture-redis-cheatsheet.md b/design/architecture/system-architecture-redis-cheatsheet.md index 5adaf8e826..46a7d7eea7 100644 --- a/design/architecture/system-architecture-redis-cheatsheet.md +++ b/design/architecture/system-architecture-redis-cheatsheet.md @@ -44,6 +44,7 @@ This table highlights representative prefixes and their intended Redis role. It | `retry:{tenantRegionTag}` | **Coordination Redis** | Game Session Service | Retry queues for tick effects. Uses idempotent Lua semantics; reset only through documented coordination reset flows. | | `tick-executor-lease:{tenantRegionTag}` | **Coordination Redis** | Game Session Service | Region leadership and executor lease. Must obey shard-local Lua rules; coordination resets and failover must follow the patterns in [Tick System and Runtime Design](./system-architecture-ticks.md). | | `session:game:{tenantGameplayTag}::` | **Coordination Redis** | Game Session Service | Gameplay session binding and reconnect state. Treated as volatile coordination data with derived expiry; removed when sessions end or expire. Recreated as part of normal login/reconnect flows, not by manual key edits. Region- and tenant-scoped recovery requests record either `--preserve-sessions` or `--invalidate-sessions`; no policy is inferred. Cluster recovery requires explicit `--invalidate-sessions` because the cluster token-registry cutover forces reauthentication and cannot preserve a usable gameplay binding. | +| `session:game:direct-text-worlds:v1:` | **Coordination Redis** | Game Session Service | Tenantless, full-key-hashed, reset-sensitive storage for only the original public direct-text WORLDS UI menu. The proxy UUID is observational correlation, not authentication or gameplay-session authority. The original five-minute expiry is never refreshed; loss, reset, or expiry requires fresh WORLDS discovery. | | `session:game:index:character:{tenantGameplayTag}::`, `session:game:index:account-tenant:{tenantGameplayTag}:`, `session:game:index:tenant:{tenantGameplayTag}` | **Coordination Redis** | Game Session Service | Secondary gameplay-session indexes over the canonical `session:game:*` records. The character index enforces controller uniqueness `{tenantId, playableStateNamespaceId, characterId}` and retains `{sessionId, gameInstanceId, bindingGeneration}` as value/evidence; server-derived `playableStateScope` remains binding/routing evidence, not a uniqueness dimension. Character, account-tenant, and tenant index rebuilds come from the durable active-binding inventory, followed by exact session/index readback and reconciliation; an empty Redis key never proves that a character is unbound. These indexes are not separate authority. The existing `:` character-index shape is current implementation drift and remains behind the [legacy controller-index migration gate](./system-architecture-session-behavior.md#legacy-controller-index-migration-gate). Binding ownership and takeover semantics remain in [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). | | `sessionctx:*` | **Coordination Redis** | Game Session Service | Bootstrap/session-context keys for pre-auth transport context and authenticated session lookup indexes. Not region-local gameplay authority; gameplay commands still require authenticated `LOGIN` / `PLAY` state and region binding. | | `session:auth:token:` | **Coordination Redis** | Account Service | One versioned server-side issued-token record per revocable `control-ui`, player-bootstrap, or receiver-specific private player-delegation JWT as described in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md). Ownership is split from `session:game:*`. Region- and tenant-scoped resets preserve these records; a cluster reset closes protected admission, completes the Account repair/reset cutover, then drops them as physical cleanup and forces reauthentication/token re-issuance. | diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index e6db5d1334..3460f84dfa 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -34,6 +34,7 @@ Every coordination script belongs to a **script category** that constrains which | Tick staging / pending | `tick:{tenantRegionTag}:pending` and related effect structures | Single-key or shard-local multi-key scripts that operate entirely within one `{tenantRegionTag}` slot. | | Timers and retries | `timer:{tenantRegionTag}`, `retry:{tenantRegionTag}` | Shard-local scripts operating on keys that share the same `{tenantRegionTag}`; no cross-slot operations. | | Gameplay session CAS / bindings | `session:game:{tenantGameplayTag}::`, tenant-tagged `session:game:index:*:{tenantGameplayTag}:*`, and `session:game:account-admission:{tenantGameplayTag}::` | Gameplay session CAS/update scripts may be shard-local multi-key scripts where all gameplay-session keys share `{tenantGameplayTag}`. The final binding CAS checks the exact account-qualified barrier in that slot. These scripts do not operate on Account auth-token registry keys, tick keys, or the untagged global account index/control key in the same invocation. | +| Direct-text WORLDS UI menu CAS | `session:game:direct-text-worlds:v1:` | Single-key `SESSION_CAS` on Coordination Redis, with caller-observed time and original absolute `PXAT`; no Redis `TIME` or multi-key claim. The [menu owner](./system-architecture-redis.md#direct-text-worlds-ui-menu) defines the tenantless full-key hashing exception with no fixed hash tag, plus UI-only correlation, bounds and expiry. | | Cross-tenant gameplay-session account index | `session:game:index:account:` | This global account index cannot share every tenant gameplay slot and is never included in a shard-local gameplay CAS/Lua invocation. Game Session updates it through a separate idempotent write after the owning gameplay-session mutation and reconciles it from authoritative session bindings. Account-wide revocation uses the index as a discovery projection but verifies and mutates each tenant-local binding through its owning shard-local contract; missing or stale index entries are repaired rather than treated as authorization truth. | | Issuer gameplay-session index | `session:game:index:issuer:{issuerIndexLayoutTag}::` | `SESSION_ISSUER_INDEX` operations touch exactly one pinned issuer-layout partition HASH. Binding members and versioned reservation-capacity metadata share that one key and atomic boundary; full original reservation, anchor, local operation and incarnation evidence is compared. These invocations never mix issuer partitions with tenant gameplay, account, region or replay keys. | | Account auth-token registry | `session:auth:token:` | Account-owned issued-token registry operations are single-key operations for the exact token hash. The exact-token registry record is mandatory validity and per-token-revocation authority: a cryptographically valid JWT without a matching permitted record is denied, and Lua must not invent validity from absence or from a generation alone. Durable issuer/account/tenant/membership authority generations advance in Account Service; Redis entries project/read through those durable generations for validation, while Lua may enforce the stored record state but never becomes the authority for generation advancement. This is not part of gameplay session CAS. | diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index b7c15d415a..d95ed62453 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -36,6 +36,8 @@ Defining additional Redis users, ACL variations, or ad-hoc tools is considered * In target state, these rules keep the script registry's invariants and hash-tag discipline meaningful by ensuring that every coordination mutation follows exactly one supported path: the owning service's owner-local path for an owner-exclusive mutation, or the shared-foundation path only for a mutation genuinely executed by multiple independently deployed callers. Current unreconciled direct usages remain implementation drift and do not establish that guarantee. +The source-only direct-text WORLDS menu adapter declares the Game Session Coordination principal and its owner prefix in the script descriptor, but does not provide a production protected-connection binding or a deployed ACL change. Its `ACL WHOAMI` check confirms the connected Redis principal only; neither that result nor an observed proxy UUID establishes endpoint/credential custody or authenticated receiving-chain provenance. See [Direct-text WORLDS UI menu](./system-architecture-redis.md#direct-text-worlds-ui-menu) and its [implementation status](../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation). + Every lease-script mutation is non-bypassable: no caller may invoke an owner lease script through raw `EVAL`/`EVALSHA` or an alternate helper path. For mutations of an existing lease, the owner helper must reject a missing, stale, or mismatched lease-key binding, caller principal, or script digest/version before invoking the script; acquisition may atomically establish a new binding only after principal and registered script digest/version validation. The normative script-registration fields—versioned identity/path, expected `KEYS`/`ARGV`, category/role, and reset/loss metadata—are defined by the [Lua Script Registry](./system-architecture-redis-lua-patterns.md#target-state-lua-script-registry-and-ci-expectations), while the region-lease owner, token, and compare-and-set protocol is defined by [ADR 0052](./decisions/adr-0052-redis-liveness-lease-with-durable-executor-fence.md). Redis ACLs are not a substitute and cannot authorize a bypass. ## Ops User vs Application User diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 6eb40aa45b..3b64506781 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -237,6 +237,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. | +| `session:game:direct-text-worlds:v1:` | Coordination | **Reset-sensitive, not preservable UI state** | Loss, expiry or an applicable session reset invalidates the original public WORLDS menu and requires fresh `WORLDS`. A present undecodable value is refused until actual key expiry; no current supported administrative repair path is implemented, so a malformed key without a TTL can block fresh discovery indefinitely, as defined by the linked menu owner; the old snapshot is never reconstructed or its expiry extended. A tenant/region reset cannot infer key membership from this tenantless UUID key or from the numeric transport-session ID, and must not use a wildcard scan to delete, rebuild, or preserve affected menus. Cluster reset drops the family. | Game Session owns one full-key-hashed key per canonical original proxy UUID. This is observational public UI only, contains no Account identity, credentials, REALMS scope, or JOIN intent, and is outside authenticated gameplay `--preserve-sessions` recovery. See [Direct-text WORLDS UI menu](./system-architecture-redis.md#direct-text-worlds-ui-menu). | | `session:game:initial-context:v1:*` | Coordination | **Reset-sensitive, non-preservable pre-auth state** | A whole-family invalidation declares its global impact and closes the affected initial-LOGIN boundary. A tenant or region reset cannot infer membership of tenantless records or delete this family under a tenant filter. Current recovery authority must qualify the exact global family, fence and protected binding before a physical closure continuation; missing records, retained receipts and bare absence never establish that qualification. | No expiry or recreation of missing/replaced/closed original contexts. The production external qualification producer remains unavailable; controlled fixture leases do not prove reset/restore continuity. See the [initial-context owner](./system-architecture-redis.md#initial-login-context-aggregate). | | `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. | diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 4946c3f65b..8f4abd7747 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -663,6 +663,14 @@ The **Redis Usage & Profiles** and **Redis Cache & Rate Limiting** docs expand o --- +### Direct-text WORLDS UI menu + +Game Session's `session:game:direct-text-worlds:v1:` key retains one original public `WORLDS` menu for a direct-text transport. It is a tenantless Coordination exception addressed by one complete key with full-key hashing; it has no fixed hash tag or multi-key atomicity claim. The value binds the exact observed canonical proxy UUID and the separate numeric transport-session correlation to a bounded envelope containing only the original menu snapshot. That observed UUID is correlation metadata, not authenticated ingress, caller identity, or LOGIN/JOIN authority. + +The menu snapshot has an original five-minute lifetime and preserves its original order, source fingerprint, and absolute expiry. The outer envelope is bounded to 2 MiB and the encoded inner menu to 1 MiB. The owner passes one positive safe-integer `nowEpochMillis` observed from its injected Clock to the single-key `SESSION_CAS`; Lua compares that argument, uses `PXAT` at the original expiry, and never calls Redis `TIME`. Reasserting a retained snapshot requires the exact byte-for-byte envelope to remain present and cannot renew or extend its expiry; a missing or changed preimage refuses the write. Only an explicitly fresh WORLDS discovery may create or replace the menu, and that operation obtains a new response-local snapshot from the current catalog rather than accepting a caller-supplied old snapshot. The current catalog source is revalidated before a stored snapshot is read back. + +Missing, expired, reset or source-stale menu state cannot be used and requires fresh `WORLDS` discovery. A present malformed or otherwise undecodable envelope is refused by discovery, reassertion and clear; it remains until the Redis key expires; no current supported administrative repair path is implemented. A malformed key without a TTL can therefore block fresh discovery indefinitely, and neither discovery nor clear grants repair authority. Malformed state does not establish a trustworthy original expiry. Redis or authority-source unavailability remains an explicit unavailable result, never a stale-menu fallback. The menu is not recreated from an old snapshot, carried across transport loss, or covered by preserved gameplay-session recovery. It contains no Account identity, credential, authenticated `REALMS` scope, or JOIN intent and cannot clear or recreate LOGIN/JOIN authority. Local source and proof status belong to [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation); this contract does not establish production receiving-chain custody or continuity. + ### Initial LOGIN context aggregate Game Session owns `session:game:initial-context:v1:`, where `callerContextId` is the canonical lowercase server-generated UUIDv4 defined by the [original-attempt owner](./system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). This is an explicit tenantless Coordination exception: one aggregate uses one complete key and full-key hashing, without a fixed slot or multi-key atomicity claim. The exact application grant is `~session:game:initial-context:v1:*` for `gamesession_coord_app`; no Account prefix is granted. @@ -685,7 +693,7 @@ Key principles: - All coordination and cache keys include a `tenantId` component. - Region-scoped coordination keys include both `gameInstanceId` and `regionId` so tick workloads and timers are scoped to the complete tick-region identity. - Mutable or display-only human-readable values (character names, room titles) are **never** embedded directly in keys. Key components use canonical stable identifiers or stable owner-defined selectors; shared key helpers define any required encoding. For the realm-grant index, `grantScopeId` is the sole physical grant-identity component. `worldSlug` and `realmSlug` are owner-issued fields inside the tuple passed directly to the shared codec, without caller normalization or encoding, and are not independent physical key components. - - Explicit exceptions: the Game Session initial-LOGIN aggregate described above, the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:jti:` replay markers, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` deny markers, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying its `replayAdmissionFence`), Account-owned exact-token registry records (`session:auth:token:`), Account-owned exact-input connect-token issuance-result projections (legacy `session:connect-token:tenant::account::scope::request:` and target `session:connect-token:v1:tenant::account::scope::request:`), Account-owned global authority-generation projections (`session:auth:generation:*`), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:`), the Game Session-owned global account active-binding index (`session:game:index:account:`), and the Game Session-owned global issuer active-binding index (`session:game:index:issuer:{issuerIndexLayoutTag}::`) are intentionally not tenant- or region-tagged. Both connect-token families are narrow Account-owned, single-key issuance-result projections keyed with tenant identity but not gameplay/session or region aggregates; the target family is isolated by its `v1` prefix and is not used in shard-local multi-key Lua. The Gateway's fixed tag is a slot-locality tag, not tenant or region scope. These are explicit global authority or global coordination exceptions only; all ordinary tenant/region key families remain subject to the general tagging rules. Exact-token, connect-token issuance-result, and authority-generation projections remain outside tenant/region key-tagging rules and are untouched by region- or tenant-scoped coordination resets except through their owning authority/reprojection contracts. The global account index remains one full-key-hash-sharded key; narrower resets reconcile only affected references rather than deleting unrelated tenants. The global issuer index is also outside those tags, but narrower resets reconcile only their affected binding references rather than flushing a whole issuer partition. + - Explicit exceptions: the Game Session initial-LOGIN aggregate described above, the tenantless Game Session direct-text WORLDS UI key `session:game:direct-text-worlds:v1:`, the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:jti:` replay markers, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` deny markers, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying its `replayAdmissionFence`), Account-owned exact-token registry records (`session:auth:token:`), Account-owned exact-input connect-token issuance-result projections (legacy `session:connect-token:tenant::account::scope::request:` and target `session:connect-token:v1:tenant::account::scope::request:`), Account-owned global authority-generation projections (`session:auth:generation:*`), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:`), the Game Session-owned global account active-binding index (`session:game:index:account:`), and the Game Session-owned global issuer active-binding index (`session:game:index:issuer:{issuerIndexLayoutTag}::`) are intentionally not tenant- or region-tagged. The direct-text WORLDS menu is keyed by the exact original proxy connection UUID, uses full-key hashing with no fixed slot or multi-key claim, and retains only non-authoritative public UI state. Both connect-token families are narrow Account-owned, single-key issuance-result projections keyed with tenant identity but not gameplay/session or region aggregates; the target family is isolated by its `v1` prefix and is not used in shard-local multi-key Lua. The Gateway's fixed tag is a slot-locality tag, not tenant or region scope. These explicit global and tenantless authority/coordination exceptions do not make ordinary tenant/region key families untagged. Exact-token, connect-token issuance-result, and authority-generation projections remain outside tenant/region key-tagging rules and are untouched by region- or tenant-scoped coordination resets except through their owning authority/reprojection contracts. The global account index remains one full-key-hash-sharded key; narrower resets reconcile only affected references rather than deleting unrelated tenants. The global issuer index is also outside those tags, but narrower resets reconcile only their affected binding references rather than flushing a whole issuer partition. - **`{tenantRegionTag}` hash tag** - Tick‑region coordination keys use a canonical hash tag placeholder `{tenantRegionTag}` derived from the complete `` scope. The projection must remain collision-safe; callers treat the concrete encoding as opaque. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 353a6e9072..1c97743007 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -2070,6 +2070,7 @@ exact catalog/pointer evidence. Account re-resolves the target before issuance. | connect_scope_id | [string](#string) | | | | connect_scope_expires_at | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| evaluated_at | [string](#string) | | Account's immutable evaluation time from the exact retained scope snapshot. | 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 46db06a6a3..0ec60507d4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -366,6 +366,14 @@ The #3038 warm-cache source-binding gap is corrected in the local receiver imple R1398 qualifies the subsequent review fixes with 64 fresh unit cases and 12 fresh controlled mTLS cases, all without failures, errors or skips; selected static analysis, full formatting, canonical documentation checks and the rendered Helm JWKS contract pass. The checks exercise response digest correlation, actual server-handler authentication context, caller drift and pre-effect denial, owner-coordinate binding, and readable but noncanonical projected-file refusal. Existing Account JWKS volumes now declare the required read-only file mode, without adding a Game Session or Pod-identity mount. This remains controlled preparation proof; production mount provenance, registration, custody, activation and current full CI are not established. +### Direct-text JOIN client and command receiving preparation + +The local preparation adds a typed `JOIN` command/parser, Account scope/JOIN clients, immutable request retry, response-bound world selection, observed proxy UUID and separate numeric transport-session correlation, a bounded original-menu snapshot, and the [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion). These are manually composed sources; no production receiving registration or admission authority is established. The [Authentication contract](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) owns caller-bound scope and logical JOIN attempts, the [Redis menu contract](../../architecture/system-architecture-redis.md#direct-text-worlds-ui-menu) owns menu storage and recovery, and [Redis Ops Access](../../architecture/system-architecture-redis-ops-access.md) records the missing protected-connection binding and deployed ACL. The [Game Session runtime owner](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion) owns SQL retention and ordering consequences. + +Focused controlled proof includes 427 selected catalog, menu, SQL-ordering and held-JOIN cases (390 unit and 37 physical Redis/PostgreSQL) with zero failures, errors or skips; the physical menu cases cover loss, expiry, source/preimage changes and unknown writes. The 29-unit/16-PostgreSQL lobby suite covers populated-journal migration, original/attempt retention, lock-order races, ambiguous outcomes, delayed historical success and direct SQL violations. A separate retained 67-case focused gate includes twelve physical Redis cases and independently checks the proxy UUID and numeric transport-session correlation. These separately attributed suites overlap and establish local component and storage behavior only, not a full-service CI pass or live receiving chain. + +The companion retains original LOGIN-linked scope and JOIN attempts. Focused scope/lobby proof covers Account evaluation/expiry bytes independently of the injected Game Session clock, and menu proof covers separate transport correlations, original-expiry retention and refusal to recreate lost or changed preimages. The storage and recovery contracts remain at the linked architecture owners. Uncertain JOIN originals and the existing SQL retention hold are preserved; expiry or selection replacement does not release them. Bounded REALMS scope intake and capacity qualification, complete negative/unknown-result recovery, lawful release, and a retention/archival horizon remain open. Production source registration, protected receiving custody, issuer/PKI custody, deployed Redis ACL/connection binding, activation, and first `OPEN` remain held at their owning gates, including ADR 0185 and Unit 1B constraints. No successful public admission or readiness/merge state is claimed. + ### Account operation and signer source preparation [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql) adds one immutable cleanup deadline to newly prepared Control-UI owner rows, separate from the JWT `exp` horizon and bound to the same registry bytes and Redis readback receipt. The retained-row migration case in [AccountControlUiIssuancePostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java) confirms that a pre-deadline row keeps its original fields, retains a null deadline, and is denied current use and advancement after migration. Direct PostgreSQL proof that a newly recorded deadline cannot be changed is still missing. The preparation remains source-only under AA-1.3; bounded cleanup and late revocation remain incomplete, and token issuance is not activated. @@ -463,7 +471,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `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. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Successful post-logout replay suppression and a complete playable flow remain unproved. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/dev-tools/tests/runtime-base-image-apt-contract.sh b/dev-tools/tests/runtime-base-image-apt-contract.sh index 9dc629c17a..8f17ca6105 100644 --- a/dev-tools/tests/runtime-base-image-apt-contract.sh +++ b/dev-tools/tests/runtime-base-image-apt-contract.sh @@ -8,6 +8,7 @@ trap 'rm -rf "$TEMP_DIR"' EXIT RUN_SCRIPT="$TEMP_DIR/docker-run.sh" FAKE_BIN="$TEMP_DIR/bin" +FIREMUD_APT_MIRROR_LIST_FILE="$TEMP_DIR/ubuntu-archive-mirrors.txt" mkdir -p "$FAKE_BIN" python3 - "$DOCKERFILE" "$RUN_SCRIPT" <<'PY' @@ -57,16 +58,22 @@ if len(instructions) != 1: ) canonical_source_path = "/etc/apt/sources.list.d/ubuntu.sources" +mirror_list_path = "/etc/apt/ubuntu-archive-mirrors.txt" instruction = instructions[0] if instruction.count(canonical_source_path) != 1: raise SystemExit("Dockerfile must use the canonical Ubuntu deb822 source path once") +if instruction.count(mirror_list_path) != 1: + raise SystemExit("Dockerfile must use the canonical Ubuntu mirror-list path once") -# The fixture redirects only the source-file path; the extracted APT logic stays intact. +# The fixture redirects the source and local mirror-list paths; APT logic stays intact. instruction = instruction.replace( canonical_source_path, "$FIREMUD_APT_SOURCE_FILE", 1 ) -if canonical_source_path in instruction: - raise SystemExit("fixture scratch RUN still contains the production source path") +instruction = instruction.replace( + mirror_list_path, "$FIREMUD_APT_MIRROR_LIST_FILE", 1 +) +if canonical_source_path in instruction or mirror_list_path in instruction: + raise SystemExit("fixture scratch RUN still contains a production APT path") output.write_text("#!/bin/sh\n" + instruction + "\n", encoding="utf-8") PY @@ -116,11 +123,18 @@ if [[ "$command" == update ]]; then } case "$APT_EXPECTED_LAYOUT" in archive) - grep -Eq '^URIs:[[:space:]]*https://archive\.ubuntu\.com/ubuntu/?[[:space:]]*$' "$FIREMUD_APT_SOURCE_FILE" + grep -Fqx "URIs: mirror+file:$FIREMUD_APT_MIRROR_LIST_FILE" "$FIREMUD_APT_SOURCE_FILE" grep -Eq '^URIs:[[:space:]]*https://security\.ubuntu\.com/ubuntu/?[[:space:]]*$' "$FIREMUD_APT_SOURCE_FILE" + grep -Fqx 'Suites: resolute-security' "$FIREMUD_APT_SOURCE_FILE" + grep -Fqx 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg' "$FIREMUD_APT_SOURCE_FILE" + test -s "$FIREMUD_APT_MIRROR_LIST_FILE" + grep -Fqx $'https://archive.ubuntu.com/ubuntu/\tpriority:1' "$FIREMUD_APT_MIRROR_LIST_FILE" + grep -Fqx $'https://mirror.math.princeton.edu/pub/ubuntu/\tpriority:2' "$FIREMUD_APT_MIRROR_LIST_FILE" ;; ports) grep -Eq '^URIs:[[:space:]]*https://ports\.ubuntu\.com/ubuntu-ports/?[[:space:]]*$' "$FIREMUD_APT_SOURCE_FILE" + grep -Fqx 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg' "$FIREMUD_APT_SOURCE_FILE" + test ! -e "$FIREMUD_APT_MIRROR_LIST_FILE" ;; *) echo "fixture has an unexpected APT source layout: $APT_EXPECTED_LAYOUT" >&2 @@ -163,9 +177,9 @@ Components: main restricted universe multiverse Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg SOURCES -cat > "$TEMP_DIR/sources.expected" <<'SOURCES' +cat > "$TEMP_DIR/sources.expected" < "$TEMP_DIR/mirrorlist.expected" +cmp "$TEMP_DIR/mirrorlist.expected" "$FIREMUD_APT_MIRROR_LIST_FILE" printf 'update\ninstall\n' > "$TEMP_DIR/calls.expected" -cmp "$TEMP_DIR/calls.expected" "$TEMP_DIR/success-apt.log" printf 'rm\ngroupadd\nuseradd\n' > "$TEMP_DIR/aux-calls.expected" + +python3 - "$TEMP_DIR/sources.input" "$TEMP_DIR/sources.whitespace.input" <<'PY' +from pathlib import Path +import sys + +source = Path(sys.argv[1]).read_text(encoding="utf-8") +source = source.replace( + "URIs: http://archive.ubuntu.com/ubuntu/", + "URIs:\t http://archive.ubuntu.com/ubuntu/ \t ", + 1, +) +Path(sys.argv[2]).write_text(source, encoding="utf-8") +PY +cp "$TEMP_DIR/sources.whitespace.input" "$TEMP_DIR/sources.whitespace.success" +: > "$TEMP_DIR/whitespace-success-apt.log" +: > "$TEMP_DIR/whitespace-success-aux.log" +run_dockerfile_instruction \ + "$TEMP_DIR/sources.whitespace.success" 0 0 \ + "$TEMP_DIR/whitespace-success-apt.log" "$TEMP_DIR/whitespace-success-aux.log" archive +cmp "$TEMP_DIR/sources.expected" "$TEMP_DIR/sources.whitespace.success" +cmp "$TEMP_DIR/mirrorlist.expected" "$FIREMUD_APT_MIRROR_LIST_FILE" +cmp "$TEMP_DIR/calls.expected" "$TEMP_DIR/whitespace-success-apt.log" +cmp "$TEMP_DIR/aux-calls.expected" "$TEMP_DIR/whitespace-success-aux.log" + +cmp "$TEMP_DIR/calls.expected" "$TEMP_DIR/success-apt.log" cmp "$TEMP_DIR/aux-calls.expected" "$TEMP_DIR/success-aux.log" cp "$TEMP_DIR/sources.ports.input" "$TEMP_DIR/sources.ports.success" +rm -f "$FIREMUD_APT_MIRROR_LIST_FILE" : > "$TEMP_DIR/ports-success-apt.log" : > "$TEMP_DIR/ports-success-aux.log" run_dockerfile_instruction \ diff --git a/docker/base.Dockerfile b/docker/base.Dockerfile index 2c040ca204..1eb0609eab 100644 --- a/docker/base.Dockerfile +++ b/docker/base.Dockerfile @@ -3,20 +3,32 @@ FROM eclipse-temurin:25.0.5_8-jre@sha256:ecdc0adb37bde1a281c4d245a3cd535004b1fc8 LABEL org.opencontainers.image.source="https://github.com/benhook1013/FireMUD" RUN set -eu; \ sources="/etc/apt/sources.list.d/ubuntu.sources"; \ + mirror_list="/etc/apt/ubuntu-archive-mirrors.txt"; \ test -f "$sources"; \ if { \ grep -Eq '^URIs:[[:space:]]*https?://archive\.ubuntu\.com/ubuntu/?[[:space:]]*$' "$sources" && \ grep -Eq '^URIs:[[:space:]]*https?://security\.ubuntu\.com/ubuntu/?[[:space:]]*$' "$sources"; \ - } || grep -Eq '^URIs:[[:space:]]*https?://ports\.ubuntu\.com/ubuntu-ports/?[[:space:]]*$' "$sources"; then \ - sed -i \ - -e 's|http://archive\.ubuntu\.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' \ - -e 's|http://security\.ubuntu\.com/ubuntu|https://security.ubuntu.com/ubuntu|g' \ - -e 's|http://ports\.ubuntu\.com/ubuntu-ports|https://ports.ubuntu.com/ubuntu-ports|g' \ - "$sources"; \ + }; then \ + use_archive_mirror_failover=true; \ + elif grep -Eq '^URIs:[[:space:]]*https?://ports\.ubuntu\.com/ubuntu-ports/?[[:space:]]*$' "$sources"; then \ + use_archive_mirror_failover=false; \ else \ echo "Ubuntu APT sources do not match a supported canonical layout." >&2; \ exit 1; \ fi; \ + sed -i \ + -e 's|http://archive\.ubuntu\.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' \ + -e 's|http://security\.ubuntu\.com/ubuntu|https://security.ubuntu.com/ubuntu|g' \ + -e 's|http://ports\.ubuntu\.com/ubuntu-ports|https://ports.ubuntu.com/ubuntu-ports|g' \ + "$sources"; \ + if [ "$use_archive_mirror_failover" = true ]; then \ + printf '%s\tpriority:1\n%s\tpriority:2\n' \ + 'https://archive.ubuntu.com/ubuntu/' \ + 'https://mirror.math.princeton.edu/pub/ubuntu/' \ + > "$mirror_list"; \ + mirror_uri="mirror+file:$mirror_list"; \ + sed -i -E "s|^URIs:[[:space:]]*https://archive[.]ubuntu[.]com/ubuntu/?[[:space:]]*\$|URIs: $mirror_uri|" "$sources"; \ + fi; \ if grep -Eq '^URIs:[[:space:]]*http://(archive|security)\.ubuntu\.com/ubuntu/?[[:space:]]*$|^URIs:[[:space:]]*http://ports\.ubuntu\.com/ubuntu-ports/?[[:space:]]*$' "$sources"; then \ echo "Ubuntu sources must use HTTPS." >&2; \ exit 1; \ diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 3efd87c3ff..2149e6f927 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -54,6 +54,8 @@ message IssueDirectTextConnectScopeResponse { string connect_scope_id = 1; string connect_scope_expires_at = 2; shared.v1.ErrorDetail error = 3; + // Account's immutable evaluation time from the exact retained scope snapshot. + string evaluated_at = 4; } message JoinPublicProductionMembershipRequest { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java index 0f1a2a90ca..51231a083d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java @@ -3,4 +3,5 @@ /** * Opaque, short-lived Account-issued target scope retained only by Game Session transport state. */ -public record DirectTextJoinScope(String connectScopeId, String connectScopeExpiresAt) {} +public record DirectTextJoinScope( + String connectScopeId, String connectScopeExpiresAt, String evaluatedAt) {} 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 ab7e57ddf6..29d8c1bb0a 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 @@ -141,7 +141,8 @@ public void issueDirectTextConnectScope( request.getPointerVersion())); response .setConnectScopeId(scope.connectScopeId()) - .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()); + .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()) + .setEvaluatedAt(scope.evaluatedAt()); } catch (AdminAuthorizationException ex) { response.setError( appError("IssueDirectTextConnectScope", "PERMISSION_DENIED", ex.getMessage())); 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 c2e5e02b36..4da20b561c 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 @@ -606,7 +606,7 @@ public DirectTextJoinScope issueDirectTextConnectScope( current, evaluatedAt, expiresAt); - return new DirectTextJoinScope(scopeId, expiresAt.toString()); + return new DirectTextJoinScope(scopeId, expiresAt.toString(), evaluatedAt.toString()); } @Override 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 9b4b80af8e..3d69ec90e0 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 @@ -213,7 +213,8 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { accountService.issueDirectTextConnectScope( Mockito.any(DirectTextCallerContext.class), Mockito.any(DirectTextJoinTarget.class))) - .thenReturn(new DirectTextJoinScope("scope-1", "2026-09-24T12:00:00Z")); + .thenReturn( + new DirectTextJoinScope("scope-1", "2026-09-24T12:00:00Z", "2026-09-24T11:59:30Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -226,6 +227,7 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); assertEquals("scope-1", observer.response().getConnectScopeId()); assertEquals("2026-09-24T12:00:00Z", observer.response().getConnectScopeExpiresAt()); + assertEquals("2026-09-24T11:59:30Z", observer.response().getEvaluatedAt()); Mockito.verify(accountService) .issueDirectTextConnectScope( new DirectTextCallerContext( 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 5a49e68ddc..8993441a4f 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 @@ -3724,8 +3724,11 @@ void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertNotNull(result.connectScopeId()); assertNotNull(result.connectScopeExpiresAt()); - org.mockito.Mockito.verify(accountConnectScopeRepository) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + assertEquals(result.evaluatedAt(), claims.get("evaluatedAt", String.class)); + var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); + org.mockito.Mockito.verify(accountConnectScopeRepository).insert(retained.capture()); + assertEquals(result.evaluatedAt(), retained.getValue().evaluatedAt()); + assertEquals(result.connectScopeExpiresAt(), retained.getValue().connectScopeExpiresAt()); } @Test diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 90472d7711..c7847510ce 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -6,6 +6,9 @@ import com.google.protobuf.Descriptors.FieldDescriptor; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; import java.util.List; import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -68,6 +71,8 @@ void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRealmAccess() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { @@ -76,14 +81,14 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe server.denyGameplayAdmission(); var existingButNonAdmitting = - stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); assertThat(existingButNonAdmitting.getMembershipExists()).isTrue(); assertThat(existingButNonAdmitting.getGameplayAdmissionAllowed()).isFalse(); assertThat(existingButNonAdmitting.getMembershipLifecycleState()).isEqualTo("ACTIVE"); assertThat(existingButNonAdmitting.getMembershipAuthorityGeneration()).isEqualTo(1L); server.setMembershipExists(false); - var missing = stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + var missing = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); assertThat(missing.getMembershipExists()).isFalse(); assertThat(missing.getGameplayAdmissionAllowed()).isFalse(); assertThat(missing.getMembershipLifecycleState()).isEqualTo("MISSING"); @@ -92,7 +97,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe server.setRealmAccessGranted(false); PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() - .setAccountId("7") + .setAccountId(accountUuid) .setTenantId("11") .setRealmId(REALM_ID) .setGameInstanceId("33") @@ -126,7 +131,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe .build()); assertThat(join.getSuccess()).isTrue(); - var afterJoin = stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + var afterJoin = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); assertThat(afterJoin.getMembershipExists()).isTrue(); assertThat(afterJoin.getGameplayAdmissionAllowed()).isTrue(); assertThat(afterJoin.getMembershipLifecycleState()).isEqualTo("ACTIVE"); @@ -135,7 +140,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe var realmGrant = stub.getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("7") + .setAccountId(accountUuid) .setTenantId("11") .setWorldSlug("demo") .setRealmSlug("live") @@ -155,7 +160,9 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); - IssueDirectTextConnectScopeRequest validRequest = validConnectScopeRequest(); + server.mapAccountId("demo@example.com", 7L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + IssueDirectTextConnectScopeRequest validRequest = validConnectScopeRequest(accountUuid); List invalidRequests = List.of( validRequest.toBuilder().setRealmId("22").build(), @@ -191,12 +198,14 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro @Test void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); - IssueDirectTextConnectScopeRequest scopeRequest = validConnectScopeRequest(); + IssueDirectTextConnectScopeRequest scopeRequest = validConnectScopeRequest(accountUuid); String connectScopeId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); JoinPublicProductionMembershipRequest validJoin = JoinPublicProductionMembershipRequest.newBuilder() @@ -225,10 +234,84 @@ void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { } } - private static IssueDirectTextConnectScopeRequest validConnectScopeRequest() { + @Test + void directTextScopeIssuanceAndJoinRequireRegisteredAccountUuidAndKeepClockSnapshot() + throws Exception { + Instant evaluatedAt = Instant.parse("2026-10-30T12:34:56Z"); + try (AccountRuntimeStubServer server = + new AccountRuntimeStubServer(0, Clock.fixed(evaluatedAt, ZoneOffset.UTC))) { + server.mapAccountId("demo@example.com", 7L); + server.setMembershipExists(false); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + IssueDirectTextConnectScopeRequest scopeRequest = validConnectScopeRequest(accountUuid); + List unregisteredCallers = + List.of( + "7", + "00000000-0000-0000-0000-000000000000", + "not-a-uuid", + AccountRuntimeStubServer.accountUuidForTestFixture(9L)); + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + + for (String unregisteredCaller : unregisteredCallers) { + var refusedScope = + stub.issueDirectTextConnectScope( + scopeRequest.toBuilder() + .setPlayerContext( + scopeRequest.getPlayerContext().toBuilder() + .setAccountId(unregisteredCaller)) + .build()); + assertThat(refusedScope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(refusedScope.getConnectScopeId()).isEmpty(); + assertThat(refusedScope.getConnectScopeExpiresAt()).isEmpty(); + assertThat(refusedScope.getEvaluatedAt()).isEmpty(); + } + + var issuedScope = stub.issueDirectTextConnectScope(scopeRequest); + assertThat(issuedScope.getError().getCode()).isEmpty(); + assertThat(issuedScope.getConnectScopeId()).isEqualTo("stub-connect-scope-1"); + assertThat(issuedScope.getEvaluatedAt()).isEqualTo(evaluatedAt.toString()); + assertThat(issuedScope.getConnectScopeExpiresAt()) + .isEqualTo(evaluatedAt.plusSeconds(300).toString()); + + JoinPublicProductionMembershipRequest validJoin = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(scopeRequest.getPlayerContext()) + .setConnectScopeId(issuedScope.getConnectScopeId()) + .setRequestId("join-request-1") + .build(); + for (String unregisteredCaller : unregisteredCallers) { + var refusedJoin = + stub.joinPublicProductionMembership( + validJoin.toBuilder() + .setPlayerContext( + validJoin.getPlayerContext().toBuilder().setAccountId(unregisteredCaller)) + .build()); + assertThat(refusedJoin.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(refusedJoin.getSuccess()).isFalse(); + var membership = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + assertThat(membership.getMembershipExists()).isFalse(); + assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); + } + + assertThat(stub.joinPublicProductionMembership(validJoin).getSuccess()).isTrue(); + var membershipAfterJoin = + stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + assertThat(membershipAfterJoin.getMembershipExists()).isTrue(); + assertThat(membershipAfterJoin.getGameplayAdmissionAllowed()).isTrue(); + } finally { + channel.shutdownNow(); + } + } + } + + private static IssueDirectTextConnectScopeRequest validConnectScopeRequest(String accountUuid) { PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() - .setAccountId("7") + .setAccountId(accountUuid) .setTenantId("11") .setRealmId(REALM_ID) .setGameInstanceId("33") 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 621b106c01..4074574476 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 @@ -100,21 +100,21 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() AccountServiceGrpc.newBlockingStub(channel); server.mapAccountId("demo@example.com", 7L); - assertThat( - stub.authenticate( - AuthenticateRequest.newBuilder() - .setEmail(" DEMO@EXAMPLE.COM ") - .setPassword("password") - .build()) - .getAccountId()) - .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); + String accountUuid = + stub.authenticate( + AuthenticateRequest.newBuilder() + .setEmail(" DEMO@EXAMPLE.COM ") + .setPassword("password") + .build()) + .getAccountId(); + assertThat(accountUuid).isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); server.setMembershipExists(false); var membership = stub.getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("7") + .setAccountId(accountUuid) .setTenantId("1") .setRequestId("request-1") .build()); 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 179a111842..d404d76493 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 @@ -246,6 +246,7 @@ public void issueDirectTextConnectScope( StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); if (caller.getAccountId().isBlank() + || resolveRegisteredAccountId(caller.getAccountId()) == null || caller.getTenantId().isBlank() || caller.getRealmId().isBlank() || caller.getRequestId().isBlank() @@ -279,7 +280,8 @@ public void issueDirectTextConnectScope( .build()); } else { String scopeId = "stub-connect-scope-" + nextConnectScopeId.getAndIncrement(); - Instant expiresAt = clock.instant().plusSeconds(300); + Instant evaluatedAt = clock.instant(); + Instant expiresAt = evaluatedAt.plusSeconds(300); connectScopesById.put( scopeId, new StubConnectScope( @@ -294,6 +296,7 @@ public void issueDirectTextConnectScope( IssueDirectTextConnectScopeResponse.newBuilder() .setConnectScopeId(scopeId) .setConnectScopeExpiresAt(expiresAt.toString()) + .setEvaluatedAt(evaluatedAt.toString()) .build()); } responseObserver.onCompleted(); @@ -320,6 +323,7 @@ public void joinPublicProductionMembership( || request.getRequestId().isBlank() || !request.getRequestId().equals(caller.getRequestId()) || caller.getAccountId().isBlank() + || resolveRegisteredAccountId(caller.getAccountId()) == null || caller.getTenantId().isBlank() || caller.getSessionId().isBlank() || scope == null 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 65b35dcb8e..324abdf114 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,9 @@ 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; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -14,6 +17,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,8 +32,11 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.RequestIdValidation; 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. */ @@ -36,13 +46,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 @@ -160,6 +182,164 @@ public PingResponse ping() { return callStub().ping(PingRequest.getDefaultInstance()); } + /** + * Requests one Account-owned scope for the exact server-resolved REALMS target. The unsigned + * context supplies scope data only; Account authenticates the workload and caller separately. The + * consuming store must validate the returned opaque ID and expiry before retaining them. + */ + public IssueDirectTextConnectScopeResponse issueDirectTextConnectScope( + PlayerExecutionContext playerContext, DirectTextConnectScopeTarget target) { + if (!hasDirectTextCallerShape(playerContext) + || target == null + || !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().issueDirectTextConnectScope(request); + } catch (Exception ex) { + // Issuance has no retained idempotency identity: never automatically issue again. + logger.warn("Account direct-text scope issuance did not complete", ex); + return scopeIssueError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + } + + /** Applies explicit JOIN, retaining one immutable request across at most one transport retry. */ + public JoinPublicProductionMembershipResponse joinPublicProductionMembership( + PlayerExecutionContext playerContext, + String connectScopeId, + String requestId, + Instant connectScopeExpiresAt) { + if (!hasDirectTextCallerShape(playerContext) + || !isBoundedText(connectScopeId, 2048) + || !isBoundedText(requestId, 128) + || !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 joinUnavailable(); + } + JoinPublicProductionMembershipRequest request = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(playerContext) + .setConnectScopeId(connectScopeId) + .setRequestId(requestId) + .build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub initialStub = callStub(); + if (!hasUsableConnectScope(connectScopeExpiresAt)) { + return joinError("CONNECT_SCOPE_INVALID", "Direct-text JOIN scope is missing or expired"); + } + return correlateJoin(initialStub.joinPublicProductionMembership(request), request); + } catch (StatusRuntimeException ex) { + if (ex.getStatus().getCode() == Status.Code.UNAVAILABLE + || ex.getStatus().getCode() == Status.Code.DEADLINE_EXCEEDED) { + // Expiry after possible dispatch is uncertainty, never evidence of no commit or rearm. + if (!hasUsableConnectScope(connectScopeExpiresAt)) { + return joinUnavailable(); + } + logger.warn("Account direct-text JOIN response unavailable; retrying exact request", ex); + try { + initClient(); + AccountServiceGrpc.AccountServiceBlockingStub retryStub = callStub(); + if (!hasUsableConnectScope(connectScopeExpiresAt)) { + return joinUnavailable(); + } + return correlateJoin(retryStub.joinPublicProductionMembership(request), request); + } catch (Exception retryEx) { + logger.warn("Account direct-text JOIN retry did not complete", retryEx); + } + return joinUnavailable(); + } + // This is a command-level failure, not an Account terminal operation outcome. + logger.warn("Account direct-text JOIN transport failed", ex); + return joinError("JOIN_FAILED", "Account JOIN request failed"); + } catch (Exception ex) { + logger.warn("Account direct-text JOIN did not complete", ex); + return joinUnavailable(); + } + } + + private JoinPublicProductionMembershipResponse correlateJoin( + JoinPublicProductionMembershipResponse response, + JoinPublicProductionMembershipRequest request) { + if (response == null) { + return joinUnavailable(); + } + if (response.getSuccess() + && (!request.getPlayerContext().getAccountId().equals(response.getAccountId()) + || !request.getPlayerContext().getTenantId().equals(response.getTenantId()))) { + return joinUnavailable(); + } + return response; + } + + private boolean hasUsableConnectScope(Instant expiresAt) { + return expiresAt != null && expiresAt.isAfter(clock.instant()); + } + + private boolean hasDirectTextCallerShape(PlayerExecutionContext context) { + if (context == null) { + return false; + } + try { + JwtClaims.requireCanonicalAccountUuid(context.getAccountId(), "accountId"); + RequestIdValidation.requirePositiveLong(context.getTenantId(), "tenantId"); + DirectTextConnectScopeTarget.requireUuid(context.getRealmId(), "realmId"); + DirectTextConnectScopeTarget.requireUuid( + context.getPlayableStateNamespaceId(), "playableStateNamespaceId"); + DirectTextConnectScopeTarget.requireScope(context.getPlayableStateScope()); + RequestIdValidation.requirePositiveLong(context.getGameInstanceId(), "gameInstanceId"); + return isBoundedText(context.getSessionId(), 128) + && isBoundedText(context.getRequestId(), 128); + } catch (IllegalArgumentException ex) { + return false; + } + } + + private boolean isBoundedText(String value, int maxLength) { + return value != null && !value.isBlank() && value.length() <= maxLength; + } + + private IssueDirectTextConnectScopeResponse scopeIssueError(String code, String message) { + return IssueDirectTextConnectScopeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(code).setMessage(message)) + .build(); + } + + private JoinPublicProductionMembershipResponse joinUnavailable() { + return joinError("AUTH_UNAVAILABLE", "Account authority unavailable"); + } + + 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..625f8e4880 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextConnectScopeTarget.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.gamesession.client; + +import java.util.UUID; +import net.firedevops.firemud.common.security.RequestIdValidation; + +/** Server-resolved routing evidence, not authentication or gameplay admission authority. */ +public record DirectTextConnectScopeTarget( + String tenantId, + String worldSlug, + String realmSlug, + String realmId, + String playableStateNamespaceId, + String playableStateScope, + String gameInstanceId, + long catalogRevision, + long pointerVersion) { + public DirectTextConnectScopeTarget { + RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); + requireText(worldSlug, "worldSlug", 128); + requireText(realmSlug, "realmSlug", 128); + requireUuid(realmId, "realmId"); + requireUuid(playableStateNamespaceId, "playableStateNamespaceId"); + requireScope(playableStateScope); + RequestIdValidation.requirePositiveLong(gameInstanceId, "gameInstanceId"); + if (catalogRevision < 1 || pointerVersion < 1) { + throw new IllegalArgumentException("routing revisions must be positive"); + } + } + + static void requireText(String value, String name, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(name + " is required and bounded"); + } + } + + static void requireUuid(String value, String name) { + if (value == null || !UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical UUID"); + } + } + + static void requireScope(String value) { + if (!"SHARED".equals(value) && !"ISOLATED".equals(value)) { + throw new IllegalArgumentException("playableStateScope must be SHARED or ISOLATED"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScope.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScope.java new file mode 100644 index 0000000000..30eaea315d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScope.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.gamesession.client; + +import java.time.Clock; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.common.security.JwtClaims; + +/** + * Immutable observational retention of an Account-issued direct-text scope and its resolved target. + * This value is not authenticated authority, a store, or a public wire DTO. + */ +public final class DirectTextIssuedConnectScope { + private static final int MAX_CONNECT_SCOPE_ID_LENGTH = 2048; + + private final String accountId; + private final DirectTextConnectScopeTarget target; + private final String connectScopeId; + private final String evaluatedAt; + private final Instant evaluatedAtInstant; + private final String connectScopeExpiresAt; + private final Instant connectScopeExpiresAtInstant; + + private DirectTextIssuedConnectScope( + String accountId, + DirectTextConnectScopeTarget target, + String connectScopeId, + String evaluatedAt, + Instant evaluatedAtInstant, + String connectScopeExpiresAt, + Instant connectScopeExpiresAtInstant) { + this.accountId = accountId; + this.target = target; + this.connectScopeId = connectScopeId; + this.evaluatedAt = evaluatedAt; + this.evaluatedAtInstant = evaluatedAtInstant; + this.connectScopeExpiresAt = connectScopeExpiresAt; + this.connectScopeExpiresAtInstant = connectScopeExpiresAtInstant; + } + + /** + * Retains one successful Account response without re-resolving or altering the supplied target. + * The Account-owned evaluation time is preserved as returned; the local clock is used only to + * reject a scope that is already expired. + */ + public static DirectTextIssuedConnectScope fromAccountResponse( + String accountId, + DirectTextConnectScopeTarget target, + IssueDirectTextConnectScopeResponse response, + Clock clock) { + String canonicalAccountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + if (target == null || response == null || clock == null || response.hasError()) { + throw invalid(); + } + + String connectScopeId = response.getConnectScopeId(); + if (connectScopeId == null + || connectScopeId.isBlank() + || connectScopeId.length() > MAX_CONNECT_SCOPE_ID_LENGTH) { + throw invalid(); + } + + String evaluatedAt = response.getEvaluatedAt(); + String connectScopeExpiresAt = response.getConnectScopeExpiresAt(); + Instant evaluatedAtInstant = parseCanonicalInstant(evaluatedAt); + Instant connectScopeExpiresAtInstant = parseCanonicalInstant(connectScopeExpiresAt); + if (!connectScopeExpiresAtInstant.isAfter(evaluatedAtInstant) + || !connectScopeExpiresAtInstant.isAfter(clock.instant())) { + throw invalid(); + } + + return new DirectTextIssuedConnectScope( + canonicalAccountId, + target, + connectScopeId, + evaluatedAt, + evaluatedAtInstant, + connectScopeExpiresAt, + connectScopeExpiresAtInstant); + } + + /** Returns whether this retained scope is live at the supplied clock observation. */ + public boolean isLive(Clock clock) { + if (clock == null) { + throw invalid(); + } + return connectScopeExpiresAtInstant.isAfter(clock.instant()); + } + + public String accountId() { + return accountId; + } + + public DirectTextConnectScopeTarget target() { + return target; + } + + public String connectScopeId() { + return connectScopeId; + } + + public String evaluatedAt() { + return evaluatedAt; + } + + public Instant evaluatedAtInstant() { + return evaluatedAtInstant; + } + + public String connectScopeExpiresAt() { + return connectScopeExpiresAt; + } + + public Instant connectScopeExpiresAtInstant() { + return connectScopeExpiresAtInstant; + } + + private static Instant parseCanonicalInstant(String value) { + if (value == null || value.isBlank()) { + throw invalid(); + } + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value)) { + throw invalid(); + } + return parsed; + } catch (DateTimeParseException malformed) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Successful, live Account direct-text scope required"); + } +} 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/DirectTextWorldMenuRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisScriptContribution.java new file mode 100644 index 0000000000..17c4df42f1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisScriptContribution.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.gamesession.command.text; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive UI-only contract registration, not a client, receiving-chain or admission producer. */ +public final class DirectTextWorldMenuRedisScriptContribution implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.direct-text-world-menu-cas.v1"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-direct-text-world-menu-cas.lua"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = + getClass() + .getResourceAsStream("/redis/scripts/game-session-direct-text-world-menu-cas.json")) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + var descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) + throw unavailable(); + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException("Public world menu Redis descriptor is unavailable", failure); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Public world menu Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStore.java new file mode 100644 index 0000000000..e1bb48cbee --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStore.java @@ -0,0 +1,333 @@ +package net.firedevops.firemud.gamesession.command.text; + +import io.lettuce.core.RedisNoScriptException; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Supplier; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.SelectionSnapshot; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.MapperFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Manually composed, unregistered retention of original PUBLIC WORLDS UI only. Observed transport + * metadata is correlation, never authenticated ingress, resume, initial LOGIN or admission proof. + * Missing/reset/expired state requires fresh WORLDS; there is no reconstruction or local fallback. + */ +public final class DirectTextWorldMenuRedisStore { + public static final String OWNED_PREFIX = "session:game:direct-text-worlds:v1:"; + public static final String PRINCIPAL = "gamesession_coord_app"; + static final int MAX_OUTER_BYTES = 2 * 1024 * 1024; + private static final int MAX_INNER_BYTES = + DirectTextWorldSelectionSnapshotCodec.MAX_PAYLOAD_BYTES; + private static final int MAX_BASE64_CHARS = 4 * ((MAX_INNER_BYTES + 2) / 3); + private static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L; + private static final String SCHEMA = "direct-text-world-menu/v1"; + private static final byte[] EMPTY = new byte[0]; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .build(); + + private final DirectTextWorldSelectionService selection; + private final Clock clock; + private final Supplier> connections; + private final byte[] verifiedSource; + private final String verifiedSha1; + + /** + * The supplier must own protected Coordination endpoint/credential custody and return a dedicated + * physical connection with transparent reconnect disabled. WHOAMI verifies its exact principal, + * not endpoint custody or genuine receiving-chain authority. This class creates no client/bean. + */ + public DirectTextWorldMenuRedisStore( + DirectTextWorldSelectionService selection, + Clock clock, + Supplier> protectedPinnedCoordinationConnections, + RedisScriptCatalog installedCatalog) { + this.selection = Objects.requireNonNull(selection, "selection"); + this.clock = Objects.requireNonNull(clock, "clock"); + this.connections = + Objects.requireNonNull(protectedPinnedCoordinationConnections, "protected connections"); + this.verifiedSource = + requireSource(Objects.requireNonNull(installedCatalog, "installed catalog")); + this.verifiedSha1 = digest("SHA-1", verifiedSource); + } + + /** Explicit fresh WORLDS discovery; returns its new handle only after an acknowledged CAS. */ + public Optional discoverAndReplace(ObservedDirectTextTransport transport) { + requireTransport(transport); + var discovered = selection.browse(); + if (discovered.isEmpty()) return Optional.empty(); + var snapshot = discovered.orElseThrow(); + var prepared = prepareFreshDiscovery(transport, snapshot); + if (prepared.isEmpty()) return Optional.empty(); + var write = prepared.orElseThrow(); + try (var connection = connections.get()) { + var commands = requireConnection(connection); + byte[] key = key(transport); + byte[] prior = readBounded(commands, key); + if (prior != null && decode(transport, prior).isEmpty()) return Optional.empty(); + return mutate(commands, key, "REPLACE", prior, write.desired(), write.expiry(), write.now()) + ? discovered + : Optional.empty(); + } + } + + /** Reasserts only exact still-present original bytes; loss/reset never recreates an old menu. */ + public boolean reassert(ObservedDirectTextTransport transport, SelectionSnapshot snapshot) { + requireTransport(transport); + var prepared = prepare(transport, snapshot); + if (prepared.isEmpty()) return false; + var write = prepared.orElseThrow(); + try (var connection = connections.get()) { + var commands = requireConnection(connection); + byte[] key = key(transport); + byte[] prior = readBounded(commands, key); + if (prior == null || !Arrays.equals(prior, write.desired())) return false; + // The same nonempty preimage must survive until Lua. An unchanged value is not rewritten, + // so its original physical deadline/PTTL is retained without extension. + return mutate(commands, key, "REPLACE", prior, write.desired(), write.expiry(), write.now()); + } + } + + private Optional prepare( + ObservedDirectTextTransport transport, SelectionSnapshot snapshot) { + Optional encoded = selection.encodeSnapshot(snapshot); + if (encoded.isEmpty()) return Optional.empty(); + byte[] inner = encoded.orElseThrow(); + // Source unavailability deliberately escapes separately from invalid UI state. + if (selection.restoreSnapshot(inner).isEmpty()) return Optional.empty(); + return prepareWrite(transport, snapshot, inner); + } + + private Optional prepareFreshDiscovery( + ObservedDirectTextTransport transport, SelectionSnapshot justDiscovered) { + // Only discoverAndReplace passes its browse result here. That composition already brackets + // the route-owner read with two catalog reads; this is UI evidence, not cached authority. + // Keep not-before/expiry on the selection owner's clock, then apply this store's clock bounds. + return selection + .encodeLiveSnapshot(justDiscovered) + .flatMap(inner -> prepareWrite(transport, justDiscovered, inner)); + } + + private Optional prepareWrite( + ObservedDirectTextTransport transport, SelectionSnapshot snapshot, byte[] inner) { + long nowEpochMillis = requirePositiveSafeEpochMillis(clock.millis()); + long expiry = requirePositiveSafeEpochMillis(snapshot.expiresAt().toEpochMilli()); + if (expiry <= nowEpochMillis || expiry - nowEpochMillis > 300_000L) return Optional.empty(); + return Optional.of(new MenuWrite(encode(transport, inner), expiry, nowEpochMillis)); + } + + private record MenuWrite(byte[] desired, long expiry, long now) {} + + /** + * Restores an original handle only after exact correlation and current complete source checks. + */ + public Optional find(ObservedDirectTextTransport transport) { + requireTransport(transport); + Optional inner; + try (var connection = connections.get()) { + inner = decode(transport, readBounded(requireConnection(connection), key(transport))); + } + return inner.flatMap(selection::restoreSnapshot); + } + + /** Exact original UI cleanup only; stale sources do not prevent deleting this transport's UI. */ + public boolean clear(ObservedDirectTextTransport transport) { + requireTransport(transport); + long nowEpochMillis = requirePositiveSafeEpochMillis(clock.millis()); + try (var connection = connections.get()) { + var commands = requireConnection(connection); + byte[] key = key(transport); + byte[] prior = readBounded(commands, key); + if (prior != null && decode(transport, prior).isEmpty()) return false; + return mutate(commands, key, "CLEAR", prior, EMPTY, 0L, nowEpochMillis); + } + } + + private boolean mutate( + RedisCommands commands, + byte[] key, + String operation, + byte[] prior, + byte[] desired, + long expiry, + long nowEpochMillis) { + byte[][] keys = {key}; + byte[][] arguments = { + ascii(operation), + prior == null ? EMPTY : prior, + desired, + ascii(Long.toString(expiry)), + ascii(Long.toString(nowEpochMillis)) + }; + String result; + try { + result = commands.evalsha(verifiedSha1, ScriptOutputType.STATUS, keys, arguments); + } catch (RedisNoScriptException missing) { + // Only NOSCRIPT proves the first attempt did not execute. Unknown writes are never retried. + if (!verifiedSha1.equals(commands.scriptLoad(verifiedSource))) throw unavailable(); + // One retry on this same physical connection; a second NOSCRIPT escapes without looping. + result = commands.evalsha(verifiedSha1, ScriptOutputType.STATUS, keys, arguments); + } + if ("MENU_WRITTEN".equals(result) + || "MENU_CLEARED".equals(result) + || "MENU_UNCHANGED".equals(result)) return true; + if ("PREIMAGE_MISMATCH".equals(result) || "EXPIRED_MENU".equals(result)) return false; + // INVALID_ARGS, null, unknown results and transport failures never claim a successful write. + throw unavailable(); + } + + private static RedisCommands requireConnection( + StatefulRedisConnection connection) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) throw unavailable(); + var commands = connection.sync(); + if (!PRINCIPAL.equals(commands.aclWhoami())) throw unavailable(); + return commands; + } + + private static byte[] key(ObservedDirectTextTransport transport) { + // Tenantless, one key, full-key hashing. No fixed hash tag or multi-key atomicity claim. + return ascii(OWNED_PREFIX + transport.proxyConnectionId()); + } + + private static long requirePositiveSafeEpochMillis(long value) { + // Canonical Long.toString bytes are passed unchanged to Lua. This caller-observed clock is + // UI-expiry bookkeeping only, not authentication, reset, restore or initial-LOGIN proof. + if (value <= 0L || value > MAX_SAFE_INTEGER) { + throw new IllegalArgumentException("Positive safe-integer UI epoch milliseconds required"); + } + return value; + } + + private static void requireTransport(ObservedDirectTextTransport transport) { + Objects.requireNonNull(transport, "observed transport"); + // Retain the exact numeric spelling, never parse/reformat it into a different binding. Bound + // the long-sized decimal correlation before allocating the outer envelope; no signs/coercions. + if (!transport.transportSessionId().matches("[0-9]{1,19}")) { + throw new IllegalArgumentException("Bounded numeric transport session correlation required"); + } + } + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG", + justification = + "RedisCommands takes binary keys; byte[][] supplies exactly one key. Real Redis integration verifies absence, readback and expiry semantics.") + private static byte[] readBounded(RedisCommands commands, byte[] key) { + // GETRANGE bounds the reply before allocation/decoding, even for administrator-seeded garbage. + byte[] bytes = commands.getrange(key, 0, MAX_OUTER_BYTES); + if (bytes == null) throw unavailable(); + if (bytes.length == 0 && commands.exists(new byte[][] {key}) == 0L) return null; + return bytes; + } + + private static byte[] requireSource(RedisScriptCatalog catalog) { + var descriptor = catalog.require(DirectTextWorldMenuRedisScriptContribution.SCRIPT_ID); + var expected = new DirectTextWorldMenuRedisScriptContribution().descriptors().iterator().next(); + if (!expected.equals(descriptor) + || !DirectTextWorldMenuRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION) throw unavailable(); + try (InputStream input = + DirectTextWorldMenuRedisStore.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] source = input.readNBytes(32 * 1024 + 1); + if (source.length == 0 + || source.length > 32 * 1024 + || !digest("SHA-256", source).equals(descriptor.sha256())) throw unavailable(); + return source; + } catch (IOException failure) { + throw new IllegalStateException( + "Public world menu Coordination store is unavailable", failure); + } + } + + private static byte[] encode(ObservedDirectTextTransport transport, byte[] inner) { + if (inner.length == 0 || inner.length > MAX_INNER_BYTES) throw unavailable(); + byte[] bytes = + JSON.writeValueAsBytes( + new Envelope( + SCHEMA, + transport.proxyConnectionId().toString(), + transport.transportSessionId(), + Base64.getEncoder().encodeToString(inner))); + if (bytes.length > MAX_OUTER_BYTES) throw unavailable(); + return bytes; + } + + private static Optional decode(ObservedDirectTextTransport transport, byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_OUTER_BYTES) + return Optional.empty(); + try { + var envelope = JSON.readValue(bytes, Envelope.class); + if (envelope == null + || !SCHEMA.equals(envelope.schemaVersion()) + || !transport + .proxyConnectionId() + .toString() + .equals(envelope.originalProxyConnectionUuid()) + || !transport.transportSessionId().equals(envelope.transportSessionId()) + || envelope.encodedOriginalMenu() == null + || envelope.encodedOriginalMenu().isEmpty() + || envelope.encodedOriginalMenu().length() > MAX_BASE64_CHARS) return Optional.empty(); + byte[] inner = Base64.getDecoder().decode(envelope.encodedOriginalMenu()); + if (inner.length == 0 + || inner.length > MAX_INNER_BYTES + || !Arrays.equals(bytes, encode(transport, inner))) return Optional.empty(); + return Optional.of(inner); + } catch (JacksonException | IllegalArgumentException invalid) { + return Optional.empty(); + } + } + + private record Envelope( + String schemaVersion, + String originalProxyConnectionUuid, + String transportSessionId, + String encodedOriginalMenu) {} + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Public world menu Coordination store is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java new file mode 100644 index 0000000000..66a8783f25 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java @@ -0,0 +1,285 @@ +package net.firedevops.firemud.gamesession.command.text; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService.InvalidAuthorityException; + +/** + * Manually composed, unregistered public world selection preparation. This observational read port + * neither authenticates a caller nor supplies an atomic Account commit checkpoint. A future caller + * must retain each returned menu on its own transport; menu expiry is only UI selection validity. + */ +public final class DirectTextWorldSelectionService { + private static final Duration MENU_LIFETIME = Duration.ofMinutes(5); + + private final GameplayWorldCatalog catalog; + private final CanonicalPlayerRouteReadService routeReader; + private final Clock clock; + + public DirectTextWorldSelectionService( + GameplayWorldCatalog catalog, CanonicalPlayerRouteReadService routeReader, Clock clock) { + this.catalog = Objects.requireNonNull(catalog, "catalog"); + this.routeReader = Objects.requireNonNull(routeReader, "routeReader"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Joins the existing guarded public vector, without widening its omissions. Reachable invalid or + * changing evidence requires fresh discovery; unavailable source exceptions deliberately escape. + */ + public Optional browse() { + Instant createdAt = clock.instant(); + Instant expiresAt = createdAt.plus(MENU_LIFETIME); + return compose(createdAt, expiresAt).map(snapshot -> new SelectionSnapshot(this, snapshot)); + } + + /** Encodes only this instance's genuine handle as bounded, nonsecret storage evidence. */ + public Optional encodeSnapshot(SelectionSnapshot retained) { + if (retained == null || retained.owner != this) { + return Optional.empty(); + } + try { + return Optional.of(DirectTextWorldSelectionSnapshotCodec.encode(retained.snapshot)); + } catch (IllegalArgumentException exception) { + return Optional.empty(); + } + } + + /** Owner-clock liveness for the menu store's immediate browse result, without source I/O. */ + Optional encodeLiveSnapshot(SelectionSnapshot justDiscovered) { + if (justDiscovered == null + || justDiscovered.owner != this + || !isLive(justDiscovered.snapshot)) { + return Optional.empty(); + } + return encodeSnapshot(justDiscovered); + } + + /** + * Restores the same original observational menu, never authority or a renewed deadline. Parsing + * refusal is separate from guarded source reads so unavailable sources still escape unchanged. + */ + public Optional restoreSnapshot(byte[] stored) { + Optional decoded = DirectTextWorldSelectionSnapshotCodec.decode(stored); + if (decoded.isEmpty()) { + return Optional.empty(); + } + Snapshot retained = decoded.orElseThrow(); + if (!MENU_LIFETIME.equals(Duration.between(retained.createdAt(), retained.expiresAt())) + || !isLive(retained)) { + return Optional.empty(); + } + Optional fresh = compose(retained.createdAt(), retained.expiresAt()); + if (fresh.isEmpty() || !retained.equals(fresh.orElseThrow()) || !isLive(retained)) { + return Optional.empty(); + } + return Optional.of(new SelectionSnapshot(this, retained)); + } + + private Optional compose(Instant createdAt, Instant expiresAt) { + var original = catalog.discoverySnapshot(); + List targets; + try { + targets = routeReader.readVisiblePublicProductionTargets(); + } catch (InvalidAuthorityException exception) { + return Optional.empty(); + } + if (!hasUniqueSourceIdentities(targets)) { + return Optional.empty(); + } + + ArrayList choices = new ArrayList<>(original.worlds().size()); + for (WorldView world : original.worlds()) { + List matches = + targets.stream().filter(target -> correlates(world, target)).toList(); + if (matches.size() != 1) { + return Optional.empty(); + } + choices.add(new Choice(world, matches.getFirst())); + } + + // Each call is one validated catalog read. This bracket detects observed catalog drift during + // composition; it is not a distributed lock or an Account admission fence. + if (!original.fingerprint().equals(catalog.discoverySnapshot().fingerprint()) + || !clock.instant().isBefore(expiresAt)) { + return Optional.empty(); + } + return Optional.of(new Snapshot(choices, original.fingerprint(), createdAt, expiresAt)); + } + + /** Resolves only the retained vector, then revalidates the complete selected owner record. */ + public Optional resolve(SelectionSnapshot retained, String selector) { + if (retained == null + || retained.owner != this + || selector == null + || selector.isBlank() + || !isLive(retained.snapshot)) { + return Optional.empty(); + } + Snapshot snapshot = retained.snapshot; + Optional selected = select(snapshot.choices(), selector); + if (selected.isEmpty()) { + return Optional.empty(); + } + CanonicalPlayableTarget expected = selected.orElseThrow().target(); + CanonicalPlayableTarget current; + try { + current = routeReader.readCurrentTarget(expected); + } catch (InvalidAuthorityException exception) { + return Optional.empty(); + } + if (!expected.equals(current) + || !snapshot.fingerprint().equals(catalog.discoverySnapshot().fingerprint()) + || !isLive(snapshot)) { + return Optional.empty(); + } + return Optional.of(expected); + } + + private boolean isLive(Snapshot snapshot) { + Instant now = clock.instant(); + return !now.isBefore(snapshot.createdAt()) && now.isBefore(snapshot.expiresAt()); + } + + private static Optional select(List choices, String selector) { + String folded = selector.toLowerCase(Locale.ROOT); + // Numeric input is exclusively a response-local ordinal, never an owner/runtime identifier. + if (folded.chars().allMatch(character -> character >= '0' && character <= '9')) { + try { + int ordinal = Integer.parseInt(folded); + return ordinal > 0 && ordinal <= choices.size() + ? Optional.of(choices.get(ordinal - 1)) + : Optional.empty(); + } catch (NumberFormatException exception) { + return Optional.empty(); + } + } + List matches = + choices.stream() + .filter( + choice -> + folded.equals(choice.selector()) || folded.equals(choice.target().tenantSlug())) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); + } + + private static boolean hasUniqueSourceIdentities(List targets) { + if (targets == null) { + return false; + } + Set selectors = new HashSet<>(); + Set runtimeWorlds = new HashSet<>(); + Set runtimeTargets = new HashSet<>(); + for (CanonicalPlayableTarget target : targets) { + if (target == null) { + return false; + } + try { + // Reuse the authored-source owner's exact canonical slug validation, without normalizing + // inconsistent source evidence. The target constructor already validates its full record. + AuthoredWorldSourceDigest.validateReadSelector( + target.targetNamespace(), target.canonicalTenantId(), target.tenantSlug()); + AuthoredWorldSourceDigest.validateReadSelector( + target.targetNamespace(), target.canonicalTenantId(), target.worldSlug()); + } catch (IllegalArgumentException exception) { + return false; + } + if (!selectors.add(target.tenantSlug() + "/" + target.worldSlug()) + || !runtimeWorlds.add( + new RuntimeWorldIdentity(target.gameSessionTenantId(), target.worldSlug())) + || !runtimeTargets.add( + new RuntimeTargetIdentity(target.gameSessionTenantId(), target.gameInstanceId()))) { + return false; + } + } + return true; + } + + private static boolean correlates(WorldView world, CanonicalPlayableTarget target) { + if (world.realms().size() != 1) { + return false; + } + RealmView realm = world.realms().getFirst(); + // Display data is compared only alongside actual routing identity, never used as identity. + // requiresCharacterSelection has no canonical-target counterpart: retain it in the original + // world evidence and protect it with the complete catalog fingerprint instead of inferring it. + return world.slug().equals(target.worldSlug()) + && Objects.equals(world.displayName(), target.worldDisplayName()) + && realm.visible() + && realm.publicProductionRealm() + && realm.slug().equals(target.realmSlug()) + && Objects.equals(realm.displayName(), target.realmDisplayName()) + && realm.tenantId() > 0L + && realm.tenantId() == target.gameSessionTenantId() + && realm.gameInstanceId() > 0L + && realm.gameInstanceId() == target.gameInstanceId() + && Objects.equals(realm.realmId(), target.realmId()) + && Objects.equals(realm.playableStateNamespaceId(), target.playableStateNamespaceId()) + && realm.catalogRevision() == target.catalogRevision() + && realm.pointerVersion() == target.pointerVersion() + && Objects.equals(realm.stateScope(), target.playableStateScope()) + && Objects.equals(realm.characterCreationPolicy(), target.characterCreationPolicy()); + } + + /** An opaque response-local handle, not a PlayerOutput or public wire schema. */ + public static final class SelectionSnapshot { + private final DirectTextWorldSelectionService owner; + private final Snapshot snapshot; + + private SelectionSnapshot(DirectTextWorldSelectionService owner, Snapshot snapshot) { + this.owner = owner; + this.snapshot = snapshot; + } + + /** Ordered friendly selectors parallel to the original validated public world vector. */ + public List selectors() { + return snapshot.choices().stream().map(Choice::selector).toList(); + } + + /** Immutable original display/selection evidence; callers must not expose its internal IDs. */ + public List worlds() { + return snapshot.choices().stream().map(Choice::world).toList(); + } + + public Instant expiresAt() { + return snapshot.expiresAt(); + } + } + + record Snapshot(List choices, String fingerprint, Instant createdAt, Instant expiresAt) { + Snapshot { + choices = List.copyOf(choices); + Objects.requireNonNull(fingerprint, "fingerprint"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(expiresAt, "expiresAt"); + } + } + + record Choice(WorldView world, CanonicalPlayableTarget target) { + Choice { + Objects.requireNonNull(world, "world"); + Objects.requireNonNull(target, "target"); + } + + private String selector() { + return target.tenantSlug() + "/" + target.worldSlug(); + } + } + + private record RuntimeWorldIdentity(long tenantId, String worldSlug) {} + + private record RuntimeTargetIdentity(long tenantId, long gameInstanceId) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionSnapshotCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionSnapshotCodec.java new file mode 100644 index 0000000000..78f7dad9ed --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionSnapshotCodec.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.gamesession.command.text; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.Snapshot; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.MapperFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Internal storage payload only; decoding cannot construct a usable selection handle. */ +final class DirectTextWorldSelectionSnapshotCodec { + static final int MAX_PAYLOAD_BYTES = 1024 * 1024; + private static final String SCHEMA = "direct-text-world-selection/v1"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .build(); + + private DirectTextWorldSelectionSnapshotCodec() {} + + static byte[] encode(Snapshot snapshot) { + try { + var output = new BoundedPayloadOutput(); + JSON.writeValue(output, new Envelope(SCHEMA, snapshot)); + return output.toByteArray(); + } catch (JacksonException invalid) { + throw new IllegalArgumentException("World selection payload cannot be encoded", invalid); + } + } + + static Optional decode(byte[] stored) { + if (stored == null || stored.length == 0 || stored.length > MAX_PAYLOAD_BYTES) { + return Optional.empty(); + } + try { + Envelope envelope = JSON.readValue(stored, Envelope.class); + if (envelope == null || !SCHEMA.equals(envelope.schema())) { + return Optional.empty(); + } + // Accept only the codec's exact encoding, not coercions, repaired record defaults, alternate + // timestamp/UUID forms or another character encoding. No parallel per-record schema needed. + if (!Arrays.equals(stored, encode(envelope.snapshot()))) { + return Optional.empty(); + } + return Optional.of(envelope.snapshot()); + } catch (JacksonException | IllegalArgumentException invalid) { + return Optional.empty(); + } + } + + private record Envelope(String schema, Snapshot snapshot) { + private Envelope { + Objects.requireNonNull(schema, "schema"); + Objects.requireNonNull(snapshot, "snapshot"); + } + } + + private static final class BoundedPayloadOutput extends ByteArrayOutputStream { + @Override + public synchronized void write(int value) { + requireCapacity(1); + super.write(value); + } + + @Override + public synchronized void write(byte[] bytes, int offset, int length) { + Objects.checkFromIndexSize(offset, length, bytes.length); + requireCapacity(length); + super.write(bytes, offset, length); + } + + private void requireCapacity(int additionalBytes) { + if (additionalBytes > MAX_PAYLOAD_BYTES - count) { + throw new IllegalArgumentException("World selection payload exceeds 1 MiB"); + } + } + } +} 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 8b7a7e8b5b..6bcea9e4e5 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,8 +1,12 @@ package net.firedevops.firemud.gamesession.command.text; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -105,6 +109,51 @@ public List publicWorldsFromAuthoritySnapshot() { return publicDiscoveryWorlds(loadAuthorityWorldSnapshot()); } + /** + * Captures the exact ordered public world projection and its local comparison fingerprint from + * one validated catalog snapshot. + */ + public DiscoverySnapshot discoverySnapshot() { + CatalogSnapshot snapshot = loadAuthorityWorldSnapshot(); + return new DiscoverySnapshot(publicDiscoveryWorlds(snapshot), catalogFingerprint(snapshot)); + } + + /** + * Captures the current visible realm projection for an exact world entry retained from a prior + * discovery response. A stale or no-longer-public world entry does not resolve. + */ + public Optional realmDiscoverySnapshot(WorldView selectedWorld) { + if (selectedWorld == null) { + return Optional.empty(); + } + CatalogSnapshot snapshot = loadAuthorityWorldSnapshot(); + List publicWorlds = publicDiscoveryWorlds(snapshot); + if (!publicWorlds.contains(selectedWorld) || selectedWorld.realms().size() != 1) { + return Optional.empty(); + } + + RealmView publicRealm = selectedWorld.realms().getFirst(); + List selectedWorldMatches = + visibleWorlds(snapshot).stream() + .filter(world -> world.slug().equals(selectedWorld.slug())) + .filter( + world -> + world.realms().stream() + .anyMatch(realm -> realm.tenantId() == publicRealm.tenantId())) + .toList(); + if (selectedWorldMatches.size() != 1) { + return Optional.empty(); + } + + WorldView currentWorld = selectedWorldMatches.getFirst(); + List currentVisibleRealms = visibleRealms(currentWorld); + WorldView visibleWorld = + new WorldView(currentWorld.slug(), currentWorld.displayName(), currentVisibleRealms); + return Optional.of( + new RealmDiscoverySnapshot( + visibleWorld, currentVisibleRealms, catalogFingerprint(snapshot))); + } + /** Resolves only worlds exposed by the no-caller public discovery surface. */ public Optional resolvePublicWorldFromAuthoritySnapshot(String selector) { if (selector == null || selector.isBlank()) { @@ -533,10 +582,16 @@ private CatalogSnapshot loadAuthorityWorldSnapshot() { if (authorityPointerSupplier == null) { return loadWorldSnapshot(); } - return catalogSnapshot(toWorlds(healthyTenantPointers(loadAuthorityPointers()))); + List pointers = List.copyOf(loadAuthorityPointers()); + return catalogSnapshot(toWorlds(healthyTenantPointers(pointers)), pointers); } private static CatalogSnapshot catalogSnapshot(List sourceWorlds) { + return catalogSnapshot(sourceWorlds, null); + } + + private static CatalogSnapshot catalogSnapshot( + List sourceWorlds, List authorityPointers) { List worlds = normalizeWorlds(sourceWorlds); Map publicProductionRealmCounts = new HashMap<>(); for (WorldView world : worlds) { @@ -546,7 +601,64 @@ private static CatalogSnapshot catalogSnapshot(List sourceWorlds) { } } } - return new CatalogSnapshot(worlds, Map.copyOf(publicProductionRealmCounts)); + return new CatalogSnapshot(worlds, Map.copyOf(publicProductionRealmCounts), authorityPointers); + } + + /** + * Creates a deterministic, locally scoped comparison value over the validated catalog projection. + * This digest is neither an authority token nor an interoperable schema. + */ + private static String catalogFingerprint(CatalogSnapshot snapshot) { + CatalogFingerprintEncoder encoder = + new CatalogFingerprintEncoder("firemud:gamesession:world-catalog-discovery:v1"); + if (snapshot.authorityPointers() != null) { + encoder.writeMarker(0x50); + encoder.writeCount(snapshot.authorityPointers().size()); + for (GameplayAdmissionPointerSnapshot pointer : snapshot.authorityPointers()) { + encoder.writeMarker(0x51); + encoder.writeString(pointer.worldSlug()); + encoder.writeString(pointer.worldDisplayName()); + encoder.writeString(pointer.realmSlug()); + encoder.writeString(pointer.realmDisplayName()); + encoder.writeLong(pointer.tenantId()); + encoder.writeLong(pointer.gameInstanceId()); + encoder.writeLong(pointer.pointerVersion()); + encoder.writeBoolean(pointer.visible()); + encoder.writeBoolean(pointer.publicProductionRealm()); + encoder.writeBoolean(pointer.requiresCharacterSelection()); + encoder.writeString(pointer.stateScope()); + encoder.writeString(pointer.characterCreationPolicy()); + encoder.writeLong(pointer.catalogRevision()); + encoder.writeUuid(pointer.realmId()); + encoder.writeUuid(pointer.playableStateNamespaceId()); + } + return encoder.finish(); + } + + encoder.writeCount(snapshot.worlds().size()); + for (WorldView world : snapshot.worlds()) { + encoder.writeMarker(0x41); + encoder.writeString(world.slug()); + encoder.writeString(world.displayName()); + encoder.writeCount(world.realms().size()); + for (RealmView realm : world.realms()) { + encoder.writeMarker(0x52); + encoder.writeString(realm.slug()); + encoder.writeString(realm.displayName()); + encoder.writeLong(realm.tenantId()); + encoder.writeLong(realm.gameInstanceId()); + encoder.writeLong(realm.pointerVersion()); + encoder.writeBoolean(realm.visible()); + encoder.writeBoolean(realm.publicProductionRealm()); + encoder.writeBoolean(realm.requiresCharacterSelection()); + encoder.writeString(realm.stateScope()); + encoder.writeString(realm.characterCreationPolicy()); + encoder.writeLong(realm.catalogRevision()); + encoder.writeUuid(realm.realmId()); + encoder.writeUuid(realm.playableStateNamespaceId()); + } + } + return encoder.finish(); } private static List normalizeWorlds(List worlds) { @@ -781,7 +893,27 @@ private static RealmView copyRealmView(RealmView input) { } private record CatalogSnapshot( - List worlds, Map publicProductionRealmCounts) {} + List worlds, + Map publicProductionRealmCounts, + List authorityPointers) {} + + /** Immutable response-local public world data plus an opaque local comparison value. */ + public record DiscoverySnapshot(List worlds, String fingerprint) { + public DiscoverySnapshot { + worlds = List.copyOf(worlds); + Objects.requireNonNull(fingerprint, "fingerprint must not be null"); + } + } + + /** Immutable response-local realm data plus an opaque local comparison value. */ + public record RealmDiscoverySnapshot( + WorldView world, List realms, String fingerprint) { + public RealmDiscoverySnapshot { + Objects.requireNonNull(world, "world must not be null"); + realms = List.copyOf(realms); + Objects.requireNonNull(fingerprint, "fingerprint must not be null"); + } + } public record WorldView(String slug, String displayName, List realms) { public WorldView { @@ -879,4 +1011,79 @@ private MutableWorldAccumulator(String slug, String displayName) { this.displayName = displayName; } } + + /** Fixed-order, explicitly framed encoding used only for local snapshot comparison. */ + private static final class CatalogFingerprintEncoder { + private final MessageDigest digest; + + private CatalogFingerprintEncoder(String domainTag) { + try { + digest = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + writeString(domainTag); + } + + private void writeMarker(int marker) { + digest.update((byte) 0x01); + digest.update((byte) marker); + } + + private void writeCount(int value) { + digest.update((byte) 0x02); + writeRawInt(value); + } + + private void writeString(String value) { + digest.update((byte) 0x10); + if (value == null) { + digest.update((byte) 0x00); + return; + } + digest.update((byte) 0x01); + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + writeRawInt(bytes.length); + digest.update(bytes); + } + + private void writeLong(long value) { + digest.update((byte) 0x20); + for (int shift = Long.SIZE - Byte.SIZE; shift >= 0; shift -= Byte.SIZE) { + digest.update((byte) ((value >>> shift) & 0xff)); + } + } + + private void writeBoolean(boolean value) { + digest.update((byte) 0x30); + digest.update((byte) (value ? 0x01 : 0x00)); + } + + private void writeUuid(UUID value) { + digest.update((byte) 0x40); + if (value == null) { + digest.update((byte) 0x00); + return; + } + digest.update((byte) 0x01); + writeRawLong(value.getMostSignificantBits()); + writeRawLong(value.getLeastSignificantBits()); + } + + private String finish() { + return HexFormat.of().formatHex(digest.digest()); + } + + private void writeRawInt(int value) { + for (int shift = Integer.SIZE - Byte.SIZE; shift >= 0; shift -= Byte.SIZE) { + digest.update((byte) ((value >>> shift) & 0xff)); + } + } + + private void writeRawLong(long value) { + for (int shift = Long.SIZE - Byte.SIZE; shift >= 0; shift -= Byte.SIZE) { + digest.update((byte) ((value >>> shift) & 0xff)); + } + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransport.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransport.java new file mode 100644 index 0000000000..4e3b4466b0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransport.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamesession.command.text; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.service.SessionIdParsing; + +/** + * Preserves the proxy connection identifier observed at transport intake for direct-text + * correlation only. This metadata is not authenticated ingress, caller identity, or LOGIN/JOIN + * authority, and it must never be reconstructed from a numeric transport session ID. + */ +public record ObservedDirectTextTransport(String transportSessionId, UUID proxyConnectionId) { + private static final String TRUSTED_TCP_PROXY_MODE = "trusted_tcp_proxy"; + + public ObservedDirectTextTransport { + SessionIdParsing.require(transportSessionId); + if (proxyConnectionId == null + || proxyConnectionId.version() != 4 + || proxyConnectionId.variant() != 2 + || new UUID(0L, 0L).equals(proxyConnectionId)) { + throw new IllegalArgumentException("Proxy connection UUIDv4 required"); + } + } + + /** Returns a direct-text observation only for the original canonical proxy UUID in proxy mode. */ + public static Optional fromHandshake( + String connectionMode, String transportSessionId, String originalProxyConnectionId) { + if (!TRUSTED_TCP_PROXY_MODE.equals(connectionMode) + || originalProxyConnectionId == null + || originalProxyConnectionId.isBlank()) { + return Optional.empty(); + } + try { + UUID proxyConnectionId = UUID.fromString(originalProxyConnectionId); + if (!proxyConnectionId.toString().equals(originalProxyConnectionId)) { + return Optional.empty(); + } + return Optional.of(new ObservedDirectTextTransport(transportSessionId, proxyConnectionId)); + } catch (IllegalArgumentException malformed) { + return Optional.empty(); + } + } +} 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/TextCommandDispatchRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDispatchRequest.java index 6b8a7422b7..b6cc65db33 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDispatchRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDispatchRequest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.command.text; +import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -7,4 +8,16 @@ record TextCommandDispatchRequest( String sessionId, TextCommand command, boolean requiresSoloTick, - Optional sessionContext) {} + Optional sessionContext, + Optional observedDirectTextTransport) { + TextCommandDispatchRequest { + Objects.requireNonNull(observedDirectTextTransport, "transport observation must not be null"); + observedDirectTextTransport.ifPresent( + observed -> { + if (!Objects.equals(sessionId, observed.transportSessionId())) { + throw new IllegalArgumentException( + "Observed transport session ID must match dispatch session ID"); + } + }); + } +} 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..85ac46887f 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 @@ -243,11 +243,34 @@ public TextCommandInterpretationResult interpret( parser.parse(rawLine, activeRegistry), requiresSoloTick, context, - activeRegistry); + activeRegistry, + Optional.empty()); } public TextCommandInterpretationResult interpret( String sessionId, TextCommand command, boolean requiresSoloTick) { + return interpret(sessionId, command, requiresSoloTick, Optional.empty()); + } + + public TextCommandInterpretationResult interpret( + String sessionId, + TextCommand command, + boolean requiresSoloTick, + ObservedDirectTextTransport observedDirectTextTransport) { + Objects.requireNonNull(observedDirectTextTransport, "transport observation must not be null"); + if (!Objects.equals(sessionId, observedDirectTextTransport.transportSessionId())) { + throw new IllegalArgumentException( + "Observed transport session ID must match interpreter session ID"); + } + return interpret( + sessionId, command, requiresSoloTick, Optional.of(observedDirectTextTransport)); + } + + private TextCommandInterpretationResult interpret( + String sessionId, + TextCommand command, + boolean requiresSoloTick, + Optional observedDirectTextTransport) { Optional context = sessionAuthenticationService.resolveSessionContext(sessionId); TextCommandRegistry activeRegistry = registryFor(context); @@ -255,7 +278,13 @@ public TextCommandInterpretationResult interpret( admittedRegistryResolver == null ? command : parser.parse(command.rawLine(), activeRegistry); - return interpret(sessionId, activeCommand, requiresSoloTick, context, activeRegistry); + return interpret( + sessionId, + activeCommand, + requiresSoloTick, + context, + activeRegistry, + observedDirectTextTransport); } private TextCommandInterpretationResult interpret( @@ -263,7 +292,8 @@ private TextCommandInterpretationResult interpret( TextCommand command, boolean requiresSoloTick, Optional maybeContext, - TextCommandRegistry activeRegistry) { + TextCommandRegistry activeRegistry, + Optional observedDirectTextTransport) { TextCommandDefinition definition = activeRegistry .findDefinition(command.commandId()) @@ -311,7 +341,8 @@ private TextCommandInterpretationResult interpret( TextCommandInterpretationResult dispatchResult = dispatcher.dispatch( definition.dispatchGroup(), - new TextCommandDispatchRequest(sessionId, command, requiresSoloTick, maybeContext)); + new TextCommandDispatchRequest( + sessionId, command, requiresSoloTick, maybeContext, observedDirectTextTransport)); Optional promptContext = promptContextAfterDispatch(sessionId, definition, dispatchResult, maybeContext); commandHistoryRecorder.record( 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/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index d2433f654d..f23d704bd1 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,6 +34,7 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( worldsHandler.browseView()))); + case JOIN -> errorResult("FEATURE_UNAVAILABLE", "JOIN is not available."); case REALMS -> handleRealms(request.command()); case CHARS -> handleChars(request); default -> diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java new file mode 100644 index 0000000000..ce8ff2ccc6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java @@ -0,0 +1,352 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin.State; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered companion owner. Writes require the caller's writable READ COMMITTED transaction; + * independent primary readback is mandatory before remote effects. Protected DB delivery and + * current authenticated custody belong to composition, never to decoded SQL evidence. + */ +public final class DirectTextAuthenticatedLobbyRepository { + public static final String SCOPE = "game_session_direct_text_authenticated_lobby_scope"; + public static final String CURRENT = "game_session_direct_text_authenticated_lobby_current"; + public static final String JOIN = "game_session_direct_text_authenticated_lobby_join"; + private static final String ORIGINAL = "game_session_initial_gameplay_login_journal"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected transaction-bound DSLContext must remain shared with its owner") + public DirectTextAuthenticatedLobbyRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Serializes with actual parent abandonment, not a companion boolean or an unlocked snapshot. */ + public void verifyOriginal( + InitialGameplayLoginAttemptCoordinates original, CanonicalGameplayLoginResult verified) { + lockOriginal(original, verified, false); + } + + public void retainScope( + DirectTextAuthenticatedLobbyScope scope, CanonicalGameplayLoginResult verified, Clock clock) { + lockOriginal(scope.original(), verified, false); + requireEvidence(scope, verified); + scope.requireCurrent(scope.original(), verified, scope.transport(), clock); + byte[] bytes = scope.encode(); + var e = verified.evidence(); + dsl.execute( + "INSERT INTO " + + SCOPE + + " (scope_record_id, original_request_id," + + " original_caller_context_id, original_attempt_fence, account_id, proxy_connection_id," + + " transport_session_id, verified_token_jti, verified_token_sha256," + + " verified_token_generation, verified_issuance_fence, scope_bytes)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scope.recordId(), + scope.original().requestId(), + scope.original().callerContextId(), + scope.original().expectedAttemptFence(), + e.accountId(), + scope.transport().proxyConnectionId(), + scope.transport().transportSessionId(), + e.tokenJti(), + e.tokenSha256(), + Long.parseLong(e.tokenGeneration()), + Long.parseLong(e.issuanceFence()), + bytes); + var retained = requiredScope(dsl, scope.recordId()); + requireExact(scope, retained); + dsl.execute( + "INSERT INTO " + + CURRENT + + " (original_request_id, scope_record_id, scope_sequence)" + + " SELECT original_request_id, scope_record_id, scope_sequence FROM " + + SCOPE + + " WHERE scope_record_id = ? ON CONFLICT (original_request_id) DO UPDATE" + + " SET scope_record_id = EXCLUDED.scope_record_id, scope_sequence = EXCLUDED.scope_sequence", + scope.recordId()); + } + + public DirectTextAuthenticatedLobbyScope current( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + Clock clock) { + lockOriginal(original, verified, false); + Record row = + dsl.fetchOne( + "SELECT s.* FROM " + + SCOPE + + " s JOIN " + + CURRENT + + " c ON c.scope_record_id = s.scope_record_id WHERE c.original_request_id = ?", + original.requestId()); + if (row == null) throw unavailable(); + var scope = decodeScope(row); + scope.requireCurrent(original, verified, transport, clock); + return scope; + } + + /** Exactly one attempt per retained scope; concurrent continuations read the winner's request. */ + public DirectTextAuthenticatedLobbyJoin freezeCurrentJoin( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + Clock clock) { + var scope = current(original, verified, transport, clock); + Record prior = joinRow(dsl, scope.recordId()); + if (prior != null) return decodeJoin(scope, prior); + UUID requestId; + do { + requestId = UUID.randomUUID(); + } while (requestId.equals(original.requestId()) + || requestId.equals(original.callerContextId()) + || requestId.equals(scope.recordId()) + || requestId.equals(transport.proxyConnectionId()) + || requestId.equals(verified.evidence().tokenJti())); + var frozen = + new DirectTextAuthenticatedLobbyJoin( + scope, + DirectTextAuthenticatedLobbyJoin.requestFor(scope, requestId), + State.NEVER_DISPATCHED, + Optional.empty()); + dsl.execute( + "INSERT INTO " + + JOIN + + " (scope_record_id, join_request_id, request_bytes, state) VALUES (?, ?, ?, 'NEVER_DISPATCHED')", + scope.recordId(), + requestId, + frozen.request().toByteArray()); + return decodeJoin(scope, Objects.requireNonNull(joinRow(dsl, scope.recordId()))); + } + + /** One irreversible authorization. A false result NEVER permits an additional Account call. */ + public boolean claimDispatch( + DirectTextAuthenticatedLobbyJoin expected, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + Clock clock) { + var scope = current(expected.scope().original(), verified, transport, clock); + requireExact(expected.scope(), scope); + var retained = decodeJoin(scope, Objects.requireNonNull(joinRow(dsl, scope.recordId()))); + requireSameRequest(expected, retained); + if (retained.state() != State.NEVER_DISPATCHED) return false; + if (dsl.execute( + "UPDATE " + + JOIN + + " SET state = 'DISPATCH_POSSIBLE' WHERE scope_record_id = ? AND state = 'NEVER_DISPATCHED'", + scope.recordId()) + != 1) throw unavailable(); + return true; + } + + /** + * Historical retention only. Exact in-flight success can survive abandonment, custody loss, + * expiry and a newer selection; none of these writes applies a result to a transport. + */ + public void recordPositiveReply( + DirectTextAuthenticatedLobbyJoin expected, + CanonicalGameplayLoginResult verified, + JoinPublicProductionMembershipResponse reply) { + var scope = expected.scope(); + lockOriginal(scope.original(), verified, true); + requireEvidence(scope, verified); + DirectTextAuthenticatedLobbyJoin.requirePositiveReply(scope, reply); + var retainedScope = requiredScope(dsl, scope.recordId()); + requireExact(scope, retainedScope); + var retained = + decodeJoin(retainedScope, Objects.requireNonNull(joinRow(dsl, scope.recordId()))); + requireSameRequest(expected, retained); + if (retained.state() == State.COMPLETED) { + if (!retained.reply().filter(reply::equals).isPresent()) throw unavailable(); + return; + } + if (retained.state() != State.DISPATCH_POSSIBLE) throw unavailable(); + dsl.execute( + "UPDATE " + JOIN + " SET state = 'COMPLETED', reply_bytes = ? WHERE scope_record_id = ?", + reply.toByteArray(), + scope.recordId()); + } + + public DirectTextAuthenticatedLobbyScope readCommittedScope( + DirectTextAuthenticatedLobbyScope expected) { + requireNoTransaction(); + return dsl.connectionResult( + connection -> { + requireConnection(connection, false); + var result = + requiredScope(DSL.using(connection, SQLDialect.POSTGRES), expected.recordId()); + requireExact(expected, result); + return result; + }); + } + + public DirectTextAuthenticatedLobbyJoin readCommittedJoin( + DirectTextAuthenticatedLobbyJoin expected) { + requireNoTransaction(); + return dsl.connectionResult( + connection -> { + requireConnection(connection, false); + var reader = DSL.using(connection, SQLDialect.POSTGRES); + var scope = requiredScope(reader, expected.scope().recordId()); + requireExact(expected.scope(), scope); + Record row = joinRow(reader, scope.recordId()); + if (row == null) throw unavailable(); + var result = decodeJoin(scope, row); + requireSameRequest(expected, result); + return result; + }); + } + + private void lockOriginal( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + boolean allowAbandoned) { + requireMutation(); + var e = Objects.requireNonNull(verified).evidence(); + if (!original.requestId().equals(e.requestId()) + || !original.callerContextId().equals(e.callerContextId())) throw unavailable(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + ORIGINAL + " WHERE request_id = ? FOR UPDATE", original.requestId()); + if (row == null + || !original.callerContextId().equals(row.get("caller_context_id", UUID.class)) + || !Long.valueOf(original.expectedAttemptFence()) + .equals(row.get("expected_attempt_fence", Long.class)) + || row.get("abandoned", Boolean.class) == null + || !allowAbandoned && !Boolean.FALSE.equals(row.get("abandoned", Boolean.class)) + || !e.tokenJti().equals(row.get("verified_token_jti", UUID.class)) + || !e.tokenSha256().equals(row.get("verified_token_sha256", String.class)) + || !Long.valueOf(Long.parseLong(e.tokenGeneration())) + .equals(row.get("verified_token_generation", Long.class)) + || !Long.valueOf(Long.parseLong(e.issuanceFence())) + .equals(row.get("verified_issuance_fence", Long.class))) throw unavailable(); + } + + private static DirectTextAuthenticatedLobbyScope requiredScope(DSLContext reader, UUID id) { + Record row = reader.fetchOne("SELECT * FROM " + SCOPE + " WHERE scope_record_id = ?", id); + if (row == null) throw unavailable(); + return decodeScope(row); + } + + private static DirectTextAuthenticatedLobbyScope decodeScope(Record row) { + var scope = DirectTextAuthenticatedLobbyScope.decode(row.get("scope_bytes", byte[].class)); + var e = scope.evidence(); + if (!scope.recordId().equals(row.get("scope_record_id", UUID.class)) + || !scope.original().requestId().equals(row.get("original_request_id", UUID.class)) + || !scope + .original() + .callerContextId() + .equals(row.get("original_caller_context_id", UUID.class)) + || !Long.valueOf(scope.original().expectedAttemptFence()) + .equals(row.get("original_attempt_fence", Long.class)) + || !e.accountId().equals(row.get("account_id", UUID.class)) + || !scope.transport().proxyConnectionId().equals(row.get("proxy_connection_id", UUID.class)) + || !scope + .transport() + .transportSessionId() + .equals(row.get("transport_session_id", String.class)) + || !e.tokenJti().equals(row.get("verified_token_jti", UUID.class)) + || !e.tokenSha256().equals(row.get("verified_token_sha256", String.class)) + || !Long.valueOf(Long.parseLong(e.tokenGeneration())) + .equals(row.get("verified_token_generation", Long.class)) + || !Long.valueOf(Long.parseLong(e.issuanceFence())) + .equals(row.get("verified_issuance_fence", Long.class))) throw unavailable(); + return scope; + } + + private static Record joinRow(DSLContext reader, UUID scopeId) { + return reader.fetchOne("SELECT * FROM " + JOIN + " WHERE scope_record_id = ?", scopeId); + } + + private static DirectTextAuthenticatedLobbyJoin decodeJoin( + DirectTextAuthenticatedLobbyScope scope, Record row) { + var request = + DirectTextAuthenticatedLobbyJoin.decodeRequest(row.get("request_bytes", byte[].class)); + byte[] bytes = row.get("reply_bytes", byte[].class); + var result = + new DirectTextAuthenticatedLobbyJoin( + scope, + request, + State.valueOf(row.get("state", String.class)), + bytes == null + ? Optional.empty() + : Optional.of(DirectTextAuthenticatedLobbyJoin.decodeReply(scope, bytes))); + if (!scope.recordId().equals(row.get("scope_record_id", UUID.class)) + || !result.requestId().equals(row.get("join_request_id", UUID.class))) throw unavailable(); + return result; + } + + private static void requireEvidence( + DirectTextAuthenticatedLobbyScope scope, CanonicalGameplayLoginResult verified) { + if (!scope.evidence().equals(verified.evidence())) throw unavailable(); + } + + private static void requireExact( + DirectTextAuthenticatedLobbyScope expected, DirectTextAuthenticatedLobbyScope actual) { + if (!Arrays.equals(expected.encode(), actual.encode())) throw unavailable(); + } + + private static void requireSameRequest( + DirectTextAuthenticatedLobbyJoin expected, DirectTextAuthenticatedLobbyJoin actual) { + if (!expected.request().equals(actual.request())) throw unavailable(); + } + + private void requireMutation() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw unavailable(); + dsl.connectionResult( + connection -> { + requireConnection(connection, true); + return null; + }); + } + + private static void requireConnection(Connection connection, boolean mutation) + throws SQLException { + if (connection.getAutoCommit() == mutation + || connection.isReadOnly() + || mutation + && connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw unavailable(); + Record settings = + DSL.using(connection, SQLDialect.POSTGRES) + .fetchOne( + "SELECT pg_is_in_recovery() AS recovery, current_setting('synchronous_commit') AS durability"); + if (settings == null + || !Boolean.FALSE.equals(settings.get("recovery", Boolean.class)) + || !List.of("on", "remote_write", "remote_apply") + .contains(settings.get("durability", String.class))) throw unavailable(); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact retained direct-text lobby state is unavailable"); + } +} 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 11921b509e..02bf464974 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 @@ -85,7 +85,8 @@ public List findAllByOrderByWorldSlugAscRealmSlugAsc() return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), - GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc()) + GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc(), + GAMEPLAY_ADMISSION_POINTER.TENANT_ID.asc()) .fetch(this::toEntity); } @@ -98,7 +99,8 @@ public List findAllByTenantIdInOrderByWorldSlugAscReal .where(GAMEPLAY_ADMISSION_POINTER.TENANT_ID.in(tenantIds)) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), - GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc()) + GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc(), + GAMEPLAY_ADMISSION_POINTER.TENANT_ID.asc()) .fetch(this::toEntity); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java index 1bd9e0eade..f379a67f78 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java @@ -7,8 +7,10 @@ public interface GameplayAdmissionPointerAuthorityService { record PointerAuditKey(long tenantId, String worldSlug, String realmSlug) {} + /** Returns pointers ordered by world slug, realm slug, then tenant ID, all ascending. */ List listPointers(); + /** Returns selected tenants' pointers in the same order as {@link #listPointers()}. */ List listPointersForTenants(List tenantIds); List listPointersByTenant(long tenantId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyCustody.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyCustody.java new file mode 100644 index 0000000000..18b3afd951 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyCustody.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import java.util.function.Function; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; + +/** + * Missing protected receiving producer, deliberately not a bean or an observation-to-authority + * adapter. Implementations must authenticate the current exact original/result association and pin + * its private-result and transport custody for the entire callback, excluding replacement, closure + * and reset. A UUID observation, SQL witness or boolean current flag cannot implement this + * contract. Implementations must not retain the borrowed result beyond the current invocation. + */ +public interface DirectTextAuthenticatedLobbyCustody { + T withCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult borrowedResult, + Function action); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java new file mode 100644 index 0000000000..d23c662859 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import com.google.protobuf.InvalidProtocolBufferException; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Exact frozen request and optional historical positive reply; never a gameplay binding. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable; no builders are retained or exposed") +public record DirectTextAuthenticatedLobbyJoin( + DirectTextAuthenticatedLobbyScope scope, + JoinPublicProductionMembershipRequest request, + State state, + Optional reply) { + public static final int MAX_REQUEST_BYTES = 8192; + public static final int MAX_REPLY_BYTES = 1024; + + public enum State { + NEVER_DISPATCHED, + DISPATCH_POSSIBLE, + COMPLETED + } + + public DirectTextAuthenticatedLobbyJoin { + if (scope == null || request == null || state == null || reply == null) throw invalid(); + UUID id; + try { + id = UUID.fromString(request.getRequestId()); + DirectTextAuthenticatedLobbyScope.requireV4(id); + } catch (RuntimeException malformed) { + throw invalid(); + } + if (!id.toString().equals(request.getRequestId()) + || id.equals(scope.original().requestId()) + || id.equals(scope.original().callerContextId()) + || id.equals(scope.recordId()) + || id.equals(scope.transport().proxyConnectionId()) + || id.equals(scope.evidence().tokenJti()) + || request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.equals(requestFor(scope, id)) + || (state == State.COMPLETED) != reply.isPresent()) throw invalid(); + reply.ifPresent(value -> requirePositiveReply(scope, value)); + } + + public UUID requestId() { + return UUID.fromString(request.getRequestId()); + } + + public static PlayerExecutionContext contextFor( + DirectTextAuthenticatedLobbyScope scope, UUID id) { + return contextFor( + scope.evidence().accountId().toString(), scope.transport(), scope.issued().target(), id); + } + + public static PlayerExecutionContext contextFor( + String accountId, + net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport transport, + net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget target, + UUID id) { + DirectTextAuthenticatedLobbyScope.requireV4(id); + return PlayerExecutionContext.newBuilder() + .setAccountId(accountId) + .setTenantId(target.tenantId()) + .setRealmId(target.realmId()) + .setPlayableStateNamespaceId(target.playableStateNamespaceId()) + .setPlayableStateScope(target.playableStateScope()) + .setGameInstanceId(target.gameInstanceId()) + .setSessionId(transport.transportSessionId()) + .setRequestId(id.toString()) + .build(); + } + + public static JoinPublicProductionMembershipRequest requestFor( + DirectTextAuthenticatedLobbyScope scope, UUID id) { + return JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(contextFor(scope, id)) + .setConnectScopeId(scope.issued().connectScopeId()) + .setRequestId(id.toString()) + .build(); + } + + public static JoinPublicProductionMembershipRequest decodeRequest(byte[] bytes) { + try { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_REQUEST_BYTES) throw invalid(); + var request = JoinPublicProductionMembershipRequest.parseFrom(bytes); + if (!request.getUnknownFields().asMap().isEmpty() + || !request.hasPlayerContext() + || !request.getPlayerContext().getUnknownFields().asMap().isEmpty() + || !Arrays.equals(bytes, request.toByteArray())) throw invalid(); + return request; + } catch (InvalidProtocolBufferException | RuntimeException failure) { + throw invalid(); + } + } + + public static JoinPublicProductionMembershipResponse decodeReply( + DirectTextAuthenticatedLobbyScope scope, byte[] bytes) { + try { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_REPLY_BYTES) throw invalid(); + var reply = JoinPublicProductionMembershipResponse.parseFrom(bytes); + requirePositiveReply(scope, reply); + if (!Arrays.equals(bytes, reply.toByteArray())) throw invalid(); + return reply; + } catch (InvalidProtocolBufferException | RuntimeException failure) { + throw invalid(); + } + } + + /** AccountClient's locally manufactured errors cannot prove a negative terminal operation. */ + public static void requirePositiveReply( + DirectTextAuthenticatedLobbyScope scope, JoinPublicProductionMembershipResponse reply) { + if (reply == null + || !reply.getUnknownFields().asMap().isEmpty() + || reply.hasError() + || !reply.getSuccess() + || !Set.of("JOINED", "ALREADY_ACTIVE").contains(reply.getOutcomeCode()) + || !scope.evidence().accountId().toString().equals(reply.getAccountId()) + || !scope.issued().target().tenantId().equals(reply.getTenantId()) + || !reply.getMembershipId().matches("[1-9][0-9]{0,18}") + || reply.getMembershipVersion() <= 0 + || reply.getMembershipAuthorityGeneration() <= 0 + || reply.getSerializedSize() > MAX_REPLY_BYTES) throw invalid(); + RequestIdValidation.requirePositiveLong(reply.getMembershipId(), "membershipId"); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded lobby JOIN original required"); + } + + @Override + public String toString() { + return "DirectTextAuthenticatedLobbyJoin[nonsecret,non-admitting]"; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java new file mode 100644 index 0000000000..7ba5b8c1ff --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import java.time.Clock; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed, unregistered public-only lobby preparation. It borrows the current verified + * private LOGIN result on every operation, never stores it on the service, and never calls + * Authenticate, performs cleanup, selects an actor, binds gameplay or publishes wire success. + */ +public final class DirectTextAuthenticatedLobbyOwner { + private final DirectTextAuthenticatedLobbyRepository repository; + private final DirectTextWorldSelectionService selections; + private final AccountClient account; + private final Clock clock; + private final TransactionTemplate transaction; + + public DirectTextAuthenticatedLobbyOwner( + DirectTextAuthenticatedLobbyRepository repository, + DirectTextWorldSelectionService selections, + AccountClient account, + PlatformTransactionManager transactionManager, + Clock clock) { + this.repository = Objects.requireNonNull(repository); + this.selections = Objects.requireNonNull(selections); + this.account = Objects.requireNonNull(account); + this.clock = Objects.requireNonNull(clock); + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * One fresh explicit REALMS intent, from this selection owner's genuine guarded public handle. + * Scope issuance has no recoverable request identity: an unknown response is never reissued. + * Returned evidence is internal composition data, not a client-facing response. + */ + public DirectTextAuthenticatedLobbyScope realms( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody, + DirectTextWorldSelectionService.SelectionSnapshot menu, + String selector) { + requireNoTransaction(); + return current( + original, + verified, + custody, + transport -> { + transaction.executeWithoutResult(status -> repository.verifyOriginal(original, verified)); + var target = + selections + .resolve(menu, selector) + .orElseThrow(DirectTextAuthenticatedLobbyOwner::unavailable); + var accountTarget = DirectTextAuthenticatedLobbyScope.targetFor(target); + UUID scopeRecordId = distinctId(original, verified, transport, null); + UUID scopeRequestId = distinctId(original, verified, transport, scopeRecordId); + var context = + DirectTextAuthenticatedLobbyJoin.contextFor( + verified.evidence().accountId().toString(), + transport, + accountTarget, + scopeRequestId); + DirectTextAuthenticatedLobbyScope.requireLiveResult(original, verified, clock); + // Account call is outside SQL. No fallback, retry, private/playtest branch or arbitrary + // target. + var response = account.issueDirectTextConnectScope(context, accountTarget); + if (response == null + || response.getSerializedSize() > 8192 + || !response.getUnknownFields().asMap().isEmpty()) throw unavailable(); + var issued = + DirectTextIssuedConnectScope.fromAccountResponse( + verified.evidence().accountId().toString(), accountTarget, response, clock); + var scope = + new DirectTextAuthenticatedLobbyScope( + scopeRecordId, + InitialGameplayLoginContextState.installed(original, verified), + transport, + target, + issued); + scope.requireCurrent(original, verified, transport, clock); + transaction.executeWithoutResult( + status -> repository.retainScope(scope, verified, clock)); + var committed = repository.readCommittedScope(scope); + committed.requireCurrent(original, verified, transport, clock); + return committed; + }); + } + + /** + * Explicit JOIN of the retained CURRENT scope only. Concurrent or interrupted continuations use + * the same committed request. Only the single dispatch-claim winner calls Account; neither this + * owner nor a replacement owner re-arms a dispatch-possible original. AccountClient's bounded + * same-invocation retry uses the identical frozen request, not another logical attempt. + */ + public Observation join( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody) { + requireNoTransaction(); + var frozen = + current( + original, + verified, + custody, + transport -> + transaction.execute( + status -> repository.freezeCurrentJoin(original, verified, transport, clock))); + var committed = repository.readCommittedJoin(Objects.requireNonNull(frozen)); + boolean claimed = + current( + original, + verified, + custody, + transport -> + Boolean.TRUE.equals( + transaction.execute( + status -> + repository.claimDispatch(committed, verified, transport, clock)))); + if (!claimed) return observe(committed, original, verified, custody); + + // An ambiguous claim COMMIT/readback throws before Account. The persisted possible state is + // irreversible even if no RPC actually happened; later continuations cannot invent rollback. + var possible = repository.readCommittedJoin(committed); + if (possible.state() != DirectTextAuthenticatedLobbyJoin.State.DISPATCH_POSSIBLE) + throw unavailable(); + JoinPublicProductionMembershipResponse response = + current( + original, + verified, + custody, + transport -> { + possible.scope().requireCurrent(original, verified, transport, clock); + transaction.executeWithoutResult( + status -> { + var selected = repository.current(original, verified, transport, clock); + if (!selected.recordId().equals(possible.scope().recordId())) + throw unavailable(); + }); + var request = possible.request(); + return account.joinPublicProductionMembership( + request.getPlayerContext(), + request.getConnectScopeId(), + request.getRequestId(), + possible.scope().issued().connectScopeExpiresAtInstant()); + }); + try { + DirectTextAuthenticatedLobbyJoin.requirePositiveReply(possible.scope(), response); + } catch (IllegalArgumentException unknown) { + // Includes every generic local/transport/preflight error. No false terminal receipt. + return observe(possible, original, verified, custody); + } + // A positively correlated in-flight reply remains retainable even if custody is now lost or + // the original abandoned. This is historical SQL persistence, NOT reply application. + transaction.executeWithoutResult( + status -> repository.recordPositiveReply(possible, verified, response)); + var retained = repository.readCommittedJoin(possible); + if (!retained.reply().filter(response::equals).isPresent()) throw unavailable(); + return observe(retained, original, verified, custody); + } + + private Observation observe( + DirectTextAuthenticatedLobbyJoin originalJoin, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody) { + var retained = repository.readCommittedJoin(originalJoin); + try { + return current( + original, + verified, + custody, + transport -> { + var selected = + transaction.execute( + status -> repository.current(original, verified, transport, clock)); + if (selected == null || !selected.recordId().equals(retained.scope().recordId())) + throw unavailable(); + retained.scope().requireCurrent(original, verified, transport, clock); + return new Observation( + retained.scope().recordId(), + retained.requestId(), + retained.reply().isPresent() + ? Status.COMPLETED_CURRENT_NON_ADMITTING + : Status.RETAINED_UNRESOLVED, + retained.reply()); + }); + } catch (RuntimeException noCurrentAuthority) { + return new Observation( + retained.scope().recordId(), + retained.requestId(), + Status.HISTORICAL_ONLY, + Optional.empty()); + } + } + + private T current( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody, + Function action) { + DirectTextAuthenticatedLobbyScope.requireLiveResult(original, verified, clock); + return Objects.requireNonNull(custody) + .withCurrent( + original, + verified, + transport -> { + Objects.requireNonNull(transport); + DirectTextAuthenticatedLobbyScope.requireLiveResult(original, verified, clock); + return action.apply(transport); + }); + } + + private static UUID distinctId( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + UUID other) { + UUID id; + do { + id = UUID.randomUUID(); + } while (id.equals(original.requestId()) + || id.equals(original.callerContextId()) + || id.equals(transport.proxyConnectionId()) + || id.equals(verified.evidence().tokenJti()) + || id.equals(other)); + return id; + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Current authenticated direct-text lobby custody is unavailable"); + } + + public enum Status { + RETAINED_UNRESOLVED, + COMPLETED_CURRENT_NON_ADMITTING, + HISTORICAL_ONLY + } + + /** + * Historical membership observation only; currentReply is AS-OF this protected call's final + * selection check. It cannot authenticate, install a binding, or authorize actor selection/PLAY. + */ + public record Observation( + UUID scopeRecordId, + UUID requestId, + Status status, + Optional currentReply) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java new file mode 100644 index 0000000000..40b7f5a350 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java @@ -0,0 +1,230 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.MapperFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable nonsecret historical evidence. Neither construction nor decoding authenticates. */ +public final class DirectTextAuthenticatedLobbyScope { + public static final int MAX_BYTES = 128 * 1024; + private static final String SCHEMA = "direct-text-authenticated-lobby/v1"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .build(); + + private final UUID recordId; + private final InitialGameplayLoginContextState login; + private final ObservedDirectTextTransport transport; + private final CanonicalPlayableTarget publicTarget; + private final DirectTextIssuedConnectScope issued; + + public DirectTextAuthenticatedLobbyScope( + UUID recordId, + InitialGameplayLoginContextState login, + ObservedDirectTextTransport transport, + CanonicalPlayableTarget publicTarget, + DirectTextIssuedConnectScope issued) { + requireV4(recordId); + this.recordId = recordId; + this.login = Objects.requireNonNull(login); + this.transport = Objects.requireNonNull(transport); + this.publicTarget = Objects.requireNonNull(publicTarget); + this.issued = Objects.requireNonNull(issued); + if (login.state() != InitialGameplayLoginContextState.State.INSTALLED + || !login.evidence().accountId().toString().equals(issued.accountId()) + || !targetFor(publicTarget).equals(issued.target()) + || recordId.equals(login.coordinates().requestId()) + || recordId.equals(login.coordinates().callerContextId()) + || recordId.equals(transport.proxyConnectionId()) + || recordId.equals(login.evidence().tokenJti()) + || transport.transportSessionId().length() > 32) throw invalid(); + } + + public UUID recordId() { + return recordId; + } + + public InitialGameplayLoginAttemptCoordinates original() { + return login.coordinates(); + } + + public CanonicalGameplayLoginResult.NonSecretEvidence evidence() { + return login.evidence(); + } + + public ObservedDirectTextTransport transport() { + return transport; + } + + public CanonicalPlayableTarget publicTarget() { + return publicTarget; + } + + public DirectTextIssuedConnectScope issued() { + return issued; + } + + public void requireCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport currentTransport, + Clock clock) { + if (!original().equals(original) + || !evidence().equals(verified.evidence()) + || !transport.equals(currentTransport) + || !issued.isLive(clock)) throw invalid(); + requireLiveResult(original, verified, clock); + } + + /** Checks private lifecycle without retaining, returning or serializing compact bytes. */ + public static void requireLiveResult( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + Clock clock) { + var evidence = Objects.requireNonNull(verified).evidence(); + long now = clock.instant().getEpochSecond(); + if (!original.requestId().equals(evidence.requestId()) + || !original.callerContextId().equals(evidence.callerContextId()) + || now < evidence.issuedAtEpochSecond() + || now < evidence.notBeforeEpochSecond() + || now >= evidence.expiresAtEpochSecond()) throw invalid(); + byte[] borrowed = verified.compactJwtBytes(); + Arrays.fill(borrowed, (byte) 0); + } + + public byte[] encode() { + try { + var output = new BoundedOutput(); + JSON.writeValue( + output, + new Envelope( + SCHEMA, + recordId, + new String(login.encode(), StandardCharsets.UTF_8), + transport, + publicTarget, + issued.connectScopeId(), + issued.evaluatedAt(), + issued.connectScopeExpiresAt())); + return output.toByteArray(); + } catch (Exception failure) { + throw invalid(); + } + } + + public static DirectTextAuthenticatedLobbyScope decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw invalid(); + try { + Envelope value = JSON.readValue(bytes, Envelope.class); + if (value == null + || !SCHEMA.equals(value.schema()) + || value.loginState() == null + || value.loginState().length() > InitialGameplayLoginContextState.MAX_BYTES + || value.evaluatedAt() == null + || value.evaluatedAt().length() > 40 + || value.expiresAt() == null + || value.expiresAt().length() > 40) throw invalid(); + var login = + InitialGameplayLoginContextState.decode( + value.loginState().getBytes(StandardCharsets.UTF_8)); + // Historical decoding uses the ORIGINAL evaluation instant only to reconstruct the existing + // immutable value. It never extends expiry or establishes permission to use an expired scope. + var issued = + DirectTextIssuedConnectScope.fromAccountResponse( + login.evidence().accountId().toString(), + targetFor(value.publicTarget()), + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(value.connectScopeId()) + .setEvaluatedAt(value.evaluatedAt()) + .setConnectScopeExpiresAt(value.expiresAt()) + .build(), + Clock.fixed(Instant.parse(value.evaluatedAt()), ZoneOffset.UTC)); + var result = + new DirectTextAuthenticatedLobbyScope( + value.recordId(), login, value.transport(), value.publicTarget(), issued); + if (!Arrays.equals(bytes, result.encode())) throw invalid(); + return result; + } catch (RuntimeException failure) { + throw invalid(); + } + } + + public static DirectTextConnectScopeTarget targetFor(CanonicalPlayableTarget target) { + Objects.requireNonNull(target); + return new DirectTextConnectScopeTarget( + Long.toString(target.gameSessionTenantId()), + target.worldSlug(), + target.realmSlug(), + target.realmId().toString(), + target.playableStateNamespaceId().toString(), + target.playableStateScope(), + Long.toString(target.gameInstanceId()), + target.catalogRevision(), + target.pointerVersion()); + } + + public static void requireV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) throw invalid(); + } + + private record Envelope( + String schema, + UUID recordId, + String loginState, + ObservedDirectTextTransport transport, + CanonicalPlayableTarget publicTarget, + String connectScopeId, + String evaluatedAt, + String expiresAt) {} + + private static final class BoundedOutput extends ByteArrayOutputStream { + @Override + public synchronized void write(int value) { + requireCapacity(1); + super.write(value); + } + + @Override + public synchronized void write(byte[] bytes, int offset, int length) { + Objects.checkFromIndexSize(offset, length, bytes.length); + requireCapacity(length); + super.write(bytes, offset, length); + } + + private void requireCapacity(int additional) { + if (additional > MAX_BYTES - count) throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact authenticated lobby evidence required"); + } + + @Override + public String toString() { + return "DirectTextAuthenticatedLobbyScope[nonsecret,non-admitting]"; + } +} 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 8b50ddf4e2..dff5956b34 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 @@ -10,6 +10,7 @@ import net.firedevops.firemud.gamesession.command.text.BuiltInTextCommandMetadataResolvers; import net.firedevops.firemud.gamesession.command.text.GameplayLoggingContext; import net.firedevops.firemud.gamesession.command.text.LookCommandHandler; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandActionTag; import net.firedevops.firemud.gamesession.command.text.TextCommandDispatchGroup; @@ -211,8 +212,11 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) if (!ensureBootstrapSessionContextIfMissing(session, sessionId)) { return; } + Optional observed = resolveObservedDirectTextTransport(session); TextCommandInterpretationResult interpretation = - interpreter.interpret(sessionId, command, requiresSoloTick); + observed.isPresent() + ? interpreter.interpret(sessionId, command, requiresSoloTick, observed.orElseThrow()) + : interpreter.interpret(sessionId, command, requiresSoloTick); TextCommand resolvedCommand = interpretation.resolvedCommand() == null ? command : interpretation.resolvedCommand(); recordGameplayActivity(sessionId, interpretation); @@ -285,6 +289,17 @@ private String resolveTransportSessionId(WebSocketSession session) { return cached instanceof String text ? text : null; } + private Optional resolveObservedDirectTextTransport( + WebSocketSession session) { + Object observed = + session + .getAttributes() + .get(GameSessionWebSocketHandshakeInterceptor.OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); + return observed instanceof ObservedDirectTextTransport transport + ? Optional.of(transport) + : Optional.empty(); + } + private String resolveBootstrapGameInstanceIdText(WebSocketSession session) { Object cached = session diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java index 37404a76e8..cd33e18e16 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java @@ -6,6 +6,7 @@ import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.Map; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.stereotype.Component; @@ -29,6 +30,8 @@ public class GameSessionWebSocketHandshakeInterceptor implements HandshakeInterc static final String LOCALE_HEADER = "X-Firemud-Locale"; static final String ACCEPT_LANGUAGE_HEADER = "Accept-Language"; static final String SESSION_ID_ATTR = "firemud.websocket.sessionId"; + static final String OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR = + "firemud.websocket.observedDirectTextTransport"; static final String BOOTSTRAP_GAME_INSTANCE_ATTR = "firemud.websocket.bootstrapGameInstanceId"; static final String TENANT_ID_ATTR = "firemud.websocket.tenantId"; static final String WORLD_SLUG_ATTR = "firemud.websocket.worldSlug"; @@ -53,9 +56,17 @@ public boolean beforeHandshake( bootstrapGameInstanceId, request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); attributes.put(SESSION_ID_ATTR, sessionId); + attributes.remove(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); boolean firstParty = "first_party_web".equals(request.getHeaders().getFirst(CONNECTION_MODE_HEADER)) || StringUtils.hasText(request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); + if (!firstParty) { + ObservedDirectTextTransport.fromHandshake( + request.getHeaders().getFirst(CONNECTION_MODE_HEADER), + sessionId, + request.getHeaders().getFirst(PROXY_CONNECTION_HEADER)) + .ifPresent(value -> attributes.put(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR, value)); + } if (firstParty) { attributes.put(CONNECTION_MODE_ATTR, "first_party_web"); attributes.put(CONNECT_CONTEXT_ATTR, request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); diff --git a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution index d32bcc986e..002e8246e8 100644 --- a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution +++ b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution @@ -3,3 +3,4 @@ net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairR net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountClosedBarrierRedisScriptContribution net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution +net.firedevops.firemud.gamesession.command.text.DirectTextWorldMenuRedisScriptContribution diff --git a/services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql b/services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql new file mode 100644 index 0000000000..6ebfa4131c --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql @@ -0,0 +1,167 @@ +-- Unregistered, non-admitting SQL companion. The minimal original LOGIN journal is unchanged. +-- No credential, compact token, cleanup horizon or release authority belongs to these relations. +CREATE TABLE game_session_direct_text_authenticated_lobby_scope ( + scope_record_id UUID PRIMARY KEY, + scope_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, + original_request_id UUID NOT NULL REFERENCES game_session_initial_gameplay_login_journal(request_id), + original_caller_context_id UUID NOT NULL, + original_attempt_fence BIGINT NOT NULL CHECK (original_attempt_fence > 0), + account_id UUID NOT NULL CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::uuid), + proxy_connection_id UUID NOT NULL, + transport_session_id VARCHAR(32) NOT NULL CHECK (transport_session_id ~ '^[0-9]{1,32}$'), + verified_token_jti UUID NOT NULL, + verified_token_sha256 VARCHAR(64) NOT NULL CHECK (verified_token_sha256 ~ '^[0-9a-f]{64}$'), + verified_token_generation BIGINT NOT NULL CHECK (verified_token_generation = 1), + verified_issuance_fence BIGINT NOT NULL CHECK (verified_issuance_fence > 0), + scope_bytes BYTEA NOT NULL CHECK (octet_length(scope_bytes) BETWEEN 1 AND 131072), + UNIQUE (original_request_id, scope_record_id, scope_sequence), + CHECK (scope_record_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND proxy_connection_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND scope_record_id NOT IN (original_request_id, original_caller_context_id, proxy_connection_id, verified_token_jti)) +); + +CREATE TABLE game_session_direct_text_authenticated_lobby_current ( + original_request_id UUID PRIMARY KEY, + scope_record_id UUID NOT NULL UNIQUE, + scope_sequence BIGINT NOT NULL CHECK (scope_sequence > 0), + FOREIGN KEY (original_request_id, scope_record_id, scope_sequence) + REFERENCES game_session_direct_text_authenticated_lobby_scope + (original_request_id, scope_record_id, scope_sequence) +); + +CREATE TABLE game_session_direct_text_authenticated_lobby_join ( + scope_record_id UUID PRIMARY KEY REFERENCES game_session_direct_text_authenticated_lobby_scope(scope_record_id), + join_request_id UUID NOT NULL UNIQUE, + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) BETWEEN 1 AND 8192), + state VARCHAR(32) NOT NULL CHECK (state IN ('NEVER_DISPATCHED', 'DISPATCH_POSSIBLE', 'COMPLETED')), + reply_bytes BYTEA, + CHECK (join_request_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CHECK ((state = 'COMPLETED' AND reply_bytes IS NOT NULL + AND octet_length(reply_bytes) BETWEEN 1 AND 1024) + OR (state <> 'COMPLETED' AND reply_bytes IS NULL)) +); + +-- [jooq ignore start] +-- Every new claim takes the ACTUAL original row lock, including direct SQL writers. These +-- comparisons protect storage only: current authenticated Account/custody evidence is mandatory +-- at the manually composed Java owner and is not manufactured by this function. +CREATE FUNCTION require_gs_direct_text_lobby_original(s game_session_direct_text_authenticated_lobby_scope, allow_abandoned BOOLEAN) +RETURNS VOID AS $$ +DECLARE + original game_session_initial_gameplay_login_journal%ROWTYPE; +BEGIN + SELECT * INTO original FROM game_session_initial_gameplay_login_journal + WHERE request_id = s.original_request_id FOR UPDATE; + IF NOT FOUND OR (original.abandoned AND NOT allow_abandoned) + OR original.verified_token_jti IS NULL + OR ROW(original.caller_context_id, original.expected_attempt_fence, + original.verified_token_jti, original.verified_token_sha256, + original.verified_token_generation, original.verified_issuance_fence) + IS DISTINCT FROM ROW(s.original_caller_context_id, s.original_attempt_fence, + s.verified_token_jti, s.verified_token_sha256, + s.verified_token_generation, s.verified_issuance_fence) THEN + RAISE EXCEPTION 'Direct-text lobby original is unavailable' USING ERRCODE = '23514'; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_direct_text_lobby_scope() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Direct-text lobby scope retention is held' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW IS DISTINCT FROM OLD THEN + RAISE EXCEPTION 'Direct-text lobby scope is immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + PERFORM require_gs_direct_text_lobby_original(NEW, FALSE); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gs_direct_text_lobby_scope_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_direct_text_authenticated_lobby_scope + FOR EACH ROW EXECUTE FUNCTION guard_gs_direct_text_lobby_scope(); +CREATE TRIGGER gs_direct_text_lobby_scope_retention + BEFORE TRUNCATE ON game_session_direct_text_authenticated_lobby_scope + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_direct_text_lobby_scope(); + +CREATE FUNCTION guard_gs_direct_text_lobby_current() RETURNS TRIGGER AS $$ +DECLARE + s game_session_direct_text_authenticated_lobby_scope%ROWTYPE; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Direct-text lobby selection retention is held' USING ERRCODE = '23514'; + END IF; + SELECT * INTO s FROM game_session_direct_text_authenticated_lobby_scope + WHERE scope_record_id = NEW.scope_record_id; + IF NOT FOUND OR s.original_request_id <> NEW.original_request_id + OR s.scope_sequence <> NEW.scope_sequence THEN + RAISE EXCEPTION 'Direct-text lobby selection differs from retained scope' USING ERRCODE = '23514'; + END IF; + PERFORM require_gs_direct_text_lobby_original(s, FALSE); + IF TG_OP = 'UPDATE' AND (NEW.original_request_id <> OLD.original_request_id + OR NEW.scope_sequence <= OLD.scope_sequence) THEN + RAISE EXCEPTION 'Direct-text lobby selection cannot regress or rebind' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gs_direct_text_lobby_current_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_direct_text_authenticated_lobby_current + FOR EACH ROW EXECUTE FUNCTION guard_gs_direct_text_lobby_current(); +CREATE TRIGGER gs_direct_text_lobby_current_retention + BEFORE TRUNCATE ON game_session_direct_text_authenticated_lobby_current + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_direct_text_lobby_current(); + +CREATE FUNCTION guard_gs_direct_text_lobby_join() RETURNS TRIGGER AS $$ +DECLARE + s game_session_direct_text_authenticated_lobby_scope%ROWTYPE; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Direct-text lobby JOIN retention is held' USING ERRCODE = '23514'; + END IF; + SELECT * INTO s FROM game_session_direct_text_authenticated_lobby_scope + WHERE scope_record_id = NEW.scope_record_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Direct-text lobby JOIN scope is missing' USING ERRCODE = '23514'; + END IF; + IF NEW.join_request_id IN (s.scope_record_id, s.original_request_id, + s.original_caller_context_id, s.proxy_connection_id, s.verified_token_jti) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN requires its own identity' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF ROW(NEW.scope_record_id, NEW.join_request_id, NEW.request_bytes) + IS DISTINCT FROM ROW(OLD.scope_record_id, OLD.join_request_id, OLD.request_bytes) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN identity is immutable' USING ERRCODE = '23514'; + END IF; + -- A delayed exact positive result may be retained even after abandonment or replacement. + -- It never moves the current selection or applies membership/authentication to a transport. + IF OLD.state = 'DISPATCH_POSSIBLE' AND NEW.state = 'COMPLETED' + AND NEW.reply_bytes IS NOT NULL THEN + PERFORM require_gs_direct_text_lobby_original(s, TRUE); + RETURN NEW; + END IF; + IF NOT (OLD.state = 'NEVER_DISPATCHED' AND NEW.state = 'DISPATCH_POSSIBLE' + AND NEW.reply_bytes IS NULL) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN cannot reset or overwrite an original' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.state <> 'NEVER_DISPATCHED' OR NEW.reply_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Direct-text lobby JOIN must begin never-dispatched' USING ERRCODE = '23514'; + END IF; + PERFORM require_gs_direct_text_lobby_original(s, FALSE); + IF NOT EXISTS (SELECT 1 FROM game_session_direct_text_authenticated_lobby_current + WHERE original_request_id = s.original_request_id AND scope_record_id = s.scope_record_id) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN selection is no longer current' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gs_direct_text_lobby_join_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_direct_text_authenticated_lobby_join + FOR EACH ROW EXECUTE FUNCTION guard_gs_direct_text_lobby_join(); +CREATE TRIGGER gs_direct_text_lobby_join_retention + BEFORE TRUNCATE ON game_session_direct_text_authenticated_lobby_join + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_direct_text_lobby_join(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-direct-text-world-menu-cas.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-direct-text-world-menu-cas.lua new file mode 100644 index 0000000000..78c51d2916 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-direct-text-world-menu-cas.lua @@ -0,0 +1,49 @@ +-- Owner-only PUBLIC WORLDS UI CAS. No authenticated authority or initial-LOGIN state. +-- One tenantless full-hashed key; caller-observed time bounds UI expiry only, never authority. +-- Returns closed status strings; all refusals are non-mutating. No automatic CAS retry. +local maximum = 2097152 +if #KEYS ~= 1 or #ARGV ~= 5 then return 'INVALID_ARGS' end +local prefix = 'session:game:direct-text-worlds:v1:' +local key = KEYS[1] +if #key ~= #prefix + 36 or string.sub(key, 1, #prefix) ~= prefix then + return 'INVALID_ARGS' +end +local uuid = string.sub(key, #prefix + 1) +if not string.match(uuid, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-4%x%x%x%-[89ab]%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + or string.lower(uuid) ~= uuid then return 'INVALID_ARGS' end +local operation, expected, desired, deadline = ARGV[1], ARGV[2], ARGV[3], ARGV[4] +local observedNow = ARGV[5] +local function positiveSafeInteger(value) + if #value > 16 or not string.match(value, '^[1-9][0-9]*$') then return nil end + local number = tonumber(value) + if not number or number > 9007199254740991 then return nil end + return number +end +local now = positiveSafeInteger(observedNow) +if not now then return 'INVALID_ARGS' end +if #expected > maximum or #desired > maximum then return 'INVALID_ARGS' end +if operation ~= 'REPLACE' and operation ~= 'CLEAR' then return 'INVALID_ARGS' end +if operation == 'CLEAR' then + if desired ~= '' or deadline ~= '0' then return 'INVALID_ARGS' end +else + local expiry = positiveSafeInteger(deadline) + if #desired == 0 or not expiry then return 'INVALID_ARGS' end + if expiry <= now then return 'EXPIRED_MENU' end + if expiry - now > 300000 then return 'INVALID_ARGS' end +end +local kind = redis.call('TYPE', key).ok +if kind ~= 'none' and kind ~= 'string' then return 'INVALID_ARGS' end +if kind == 'string' and redis.call('STRLEN', key) > maximum then return 'INVALID_ARGS' end +local current = redis.call('GET', key) +-- An empty byte preimage denotes absence only, never an existing empty string. +if (expected == '' and current ~= false) or (expected ~= '' and current ~= expected) then + return 'PREIMAGE_MISMATCH' +end +if operation == 'CLEAR' then + if current == false then return 'MENU_UNCHANGED' end + redis.call('DEL', key) + return 'MENU_CLEARED' +end +if current == desired then return 'MENU_UNCHANGED' end +redis.call('SET', key, desired, 'PXAT', deadline) +return 'MENU_WRITTEN' diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-direct-text-world-menu-cas.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-direct-text-world-menu-cas.json new file mode 100644 index 0000000000..79c2b8fcb2 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-direct-text-world-menu-cas.json @@ -0,0 +1,76 @@ +{ + "scriptId": "game-session.direct-text-world-menu-cas.v1", + "resourcePath": "redis/lua/game-session-direct-text-world-menu-cas.lua", + "sha256": "0f5d0396608ba26475820643e2a5f059564e48ce5f1a36d02b6d89c78d3ea2b9", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "originalPublicWorldMenu", + "ownedPrefix": "session:game:direct-text-worlds:v1:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "operation" + }, + { + "name": "exactExpectedOuterBytesOrEmptyForAbsent" + }, + { + "name": "desiredOuterBytesOrEmptyForClear" + }, + { + "name": "originalMenuExpiryEpochMillisOrZeroForClear" + }, + { + "name": "nowEpochMillis" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "MENU_WRITTEN", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "MENU_CLEARED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "MENU_UNCHANGED", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "PREIMAGE_MISMATCH", + "category": "CONTENTION", + "effect": "NON_MUTATING" + }, + { + "code": "EXPIRED_MENU", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGS", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "SESSION", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "Reset-sensitive non-authoritative PUBLIC WORLDS UI only. One tenantless original proxy UUID key uses full-key hashing, no fixed slot or multikey claim. REPLACE and CLEAR use one exact expected byte preimage CAS; empty means absent only. Outer bytes are bounded to 2 MiB and inner original menu to 1 MiB. The owner observes nowEpochMillis once from its injected Clock per mutation. Java and Lua require canonical positive safe-integer epoch milliseconds; REPLACE requires original expiry greater than observed now and at most 300000 milliseconds later, and CLEAR requires zero expiry with the same bounded now input. REPLACE uses PXAT at the ORIGINAL menu expiry. Lua uses only KEYS, ARGV and current owned-key state, never server TIME. Exact retries never refresh expiry. The observed clock is UI-expiry bookkeeping only, never authentication, reset, restore or initial-LOGIN proof. Missing, reset, expired or source-stale state requires fresh WORLDS discovery, never old-menu reconstruction. A present malformed or undecodable envelope is refused by discovery, reassertion and clear until actual key expiry; no current supported administrative repair path is implemented. It establishes no trustworthy original expiry. Tail loss invalidates UI only; no AOF acknowledgement or external recovery qualifier applies. Correlation metadata and restored menus prove neither authenticated ingress, genuine resume nor admission. This family contains no Account identity, credentials, REALMS scope, JOIN intent or initial-LOGIN closure authority.", + "compatibilityLevel": "COMPATIBLE", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java new file mode 100644 index 0000000000..a8fd808577 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java @@ -0,0 +1,745 @@ +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.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.AdditionalAnswers.delegatesTo; +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.clearInvocations; +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; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.GenericContainer; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** + * Real disposable standalone Redis, registered script, scoped ACL and physical WHOAMI. Catalog and + * canonical-route evidence are controlled fixtures; transport construction is NOT genuine ingress, + * hidden socket rebind, deployment custody, authentication, admission or Account/JOIN proof. + */ +@SuppressWarnings("resource") +class DirectTextWorldMenuRedisStoreIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String ADMIN = "world_menu_fixture_admin"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final String ADMIN_PASSWORD = UUID.randomUUID().toString(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + private static RedisClient writer; + private static RedisClient administrator; + private final List ownedKeys = new ArrayList<>(); + private StatefulRedisConnection adminConnection; + private RedisCommands admin; + + @BeforeAll + static void start() { + assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "Docker unavailable; Redis menu proof skipped"); + REDIS.start(); + RedisClient bootstrap = client(null, null); + try (var connection = bootstrap.connect(ByteArrayCodec.INSTANCE)) { + var commands = connection.sync(); + commands.aclSetuser( + PRINCIPAL, + baseAcl(PASSWORD) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GETRANGE) + .addCommand(CommandType.EXISTS) + .addCommand(CommandType.GET) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.STRLEN) + .addCommand(CommandType.SET) + .addCommand(CommandType.DEL)); + commands.aclSetuser( + ADMIN, + baseAcl(ADMIN_PASSWORD) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.DEL) + .addCommand(CommandType.PEXPIRETIME)); + } finally { + bootstrap.shutdown(); + } + writer = client(PRINCIPAL, PASSWORD); + administrator = client(ADMIN, ADMIN_PASSWORD); + } + + private static AclSetuserArgs baseAcl(String password) { + return new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(DirectTextWorldMenuRedisStore.OWNED_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI); + } + + @BeforeEach + void openAdmin() { + adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); + admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(ADMIN); + } + + @AfterEach + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG", + justification = + "RedisCommands takes binary keys; byte[][] supplies exactly one owned fixture key for native Redis deletion.") + void cleanExactOwnedKeys() { + if (adminConnection != null) { + try { + for (byte[] key : ownedKeys) admin.del(new byte[][] {key}); + } finally { + adminConnection.close(); + } + } + } + + @AfterAll + static void stop() { + if (writer != null) writer.shutdown(); + if (administrator != null) administrator.shutdown(); + REDIS.stop(); + } + + @Test + void sharedSameEdgeReplacementRestoresOriginalOrdinalsAndAbsoluteDeadline() { + var fixture = fixture(Clock.systemUTC()); + var first = fixture.selection(); + var transport = observation(); + var menu = store(first, fixture.clock()).discoverAndReplace(transport).orElseThrow(); + byte[] original = admin.get(key(transport)); + long deadline = admin.pexpiretime(key(transport)); + assertThat(deadline).isEqualTo(menu.expiresAt().toEpochMilli()); + + var replacement = fixture.selection(); + var replacementStore = store(replacement, fixture.clock()); + var restored = replacementStore.find(transport).orElseThrow(); + assertThat(restored.selectors()).containsExactly("other/second", "studio/forest"); + assertThat(restored.worlds()).isEqualTo(menu.worlds()); + assertThat(restored.expiresAt()).isEqualTo(menu.expiresAt()); + assertThat(replacement.resolve(restored, "1")).contains(fixture.targets().get(1)); + assertThat(replacement.resolve(restored, "2")).contains(fixture.targets().get(0)); + assertThat(replacementStore.reassert(transport, restored)).isTrue(); + assertThat(admin.get(key(transport))).isEqualTo(original); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(deadline); + + var newEdge = observation(); + assertThat(replacementStore.find(newEdge)).isEmpty(); + assertThat(replacementStore.clear(newEdge)).isTrue(); + assertThat(admin.get(key(transport))).isEqualTo(original); + assertThat(admin.get(key(newEdge))).isNull(); + + when(fixture.routes().readVisiblePublicProductionTargets()).thenReturn(List.of()); + assertThat(replacementStore.find(transport)).isEmpty(); + assertThat(replacementStore.reassert(transport, restored)).isFalse(); + assertThat(replacementStore.discoverAndReplace(transport)).isEmpty(); + assertThat(admin.get(key(transport))).isEqualTo(original); + } + + @Test + void oneFreshCompositionRetainsPhysicalMenuWhileLaterUsesRestoreFreshSources() { + var fixture = fixture(Clock.systemUTC()); + var reads = new AtomicInteger(); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + reads.incrementAndGet(); + return List.of(world(fixture.targets().get(1)), world(fixture.targets().get(0))); + }); + var selection = new DirectTextWorldSelectionService(catalog, fixture.routes(), fixture.clock()); + var store = store(selection, fixture.clock()); + var transport = observation(); + var menu = store.discoverAndReplace(transport).orElseThrow(); + assertThat(reads.get()).isEqualTo(2); + verify(fixture.routes()).readVisiblePublicProductionTargets(); + byte[] original = admin.get(key(transport)); + long expiry = admin.pexpiretime(key(transport)); + assertThat(expiry).isEqualTo(menu.expiresAt().toEpochMilli()); + + reads.set(0); + clearInvocations(fixture.routes()); + var restored = store.find(transport).orElseThrow(); + assertThat(reads.get()).isEqualTo(2); + verify(fixture.routes()).readVisiblePublicProductionTargets(); + reads.set(0); + clearInvocations(fixture.routes()); + assertThat(store.reassert(transport, restored)).isTrue(); + assertThat(reads.get()).isEqualTo(2); + verify(fixture.routes()).readVisiblePublicProductionTargets(); + assertThat(store.reassert(transport, fixture.selection().browse().orElseThrow())).isFalse(); + assertThat(admin.get(key(transport))).isEqualTo(original); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(expiry); + } + + @Test + void sourceMovementAfterCompositionLeavesOnlyStaleUiNeverRecoverableAuthority() { + var fixture = fixture(Clock.systemUTC()); + var worlds = + new AtomicReference<>( + List.of(world(fixture.targets().get(1)), world(fixture.targets().get(0)))); + var catalog = GameplayWorldCatalog.forWorldSupplier(worlds::get); + var selection = new DirectTextWorldSelectionService(catalog, fixture.routes(), fixture.clock()); + var transport = observation(); + var store = + new DirectTextWorldMenuRedisStore( + selection, + fixture.clock(), + () -> { + // Move source only after browse/preparation, immediately before the physical CAS. + worlds.set(List.of()); + return writer.connect(ByteArrayCodec.INSTANCE); + }, + installed()); + var menu = store.discoverAndReplace(transport).orElseThrow(); + byte[] original = admin.get(key(transport)); + long expiry = admin.pexpiretime(key(transport)); + assertThat(original).isNotEmpty(); + assertThat(expiry).isEqualTo(menu.expiresAt().toEpochMilli()); + + assertThat(selection.resolve(menu, "1")).isEmpty(); + assertThat(store.find(transport)).isEmpty(); + assertThat(store.reassert(transport, menu)).isFalse(); + var replacement = + new DirectTextWorldSelectionService(catalog, fixture.routes(), fixture.clock()); + assertThat(store(replacement, fixture.clock()).find(transport)).isEmpty(); + assertThat(admin.get(key(transport))).isEqualTo(original); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(expiry); + admin.del(new byte[][] {key(transport)}); + assertThat(store.reassert(transport, menu)).isFalse(); + assertThat(admin.get(key(transport))).isNull(); + } + + @Test + void physicalScriptCacheLossLoadsOnceWhileWarmAndReadOnlyUsesDoNotLoad() throws Exception { + var fixture = fixture(Clock.systemUTC()); + var selection = fixture.selection(); + var transport = observation(); + byte[] source; + try (var input = + getClass() + .getClassLoader() + .getResourceAsStream(DirectTextWorldMenuRedisScriptContribution.RESOURCE_PATH)) { + source = java.util.Objects.requireNonNull(input).readAllBytes(); + } + String sha1 = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(source)); + List> uses = new ArrayList<>(); + Supplier> observedConnections = + () -> { + var physical = writer.connect(ByteArrayCodec.INSTANCE); + var observed = delegatedCommands(physical.sync()); + uses.add(observed); + return delegatedConnection(physical, observed); + }; + var store = + new DirectTextWorldMenuRedisStore( + selection, fixture.clock(), observedConnections, installed()); + flushScripts(); + var menu = store.discoverAndReplace(transport).orElseThrow(); + verify(uses.get(0)).scriptLoad(eq(source)); + verifyEvaluations(uses.get(0), sha1, 2); + byte[] original = admin.get(key(transport)); + long deadline = admin.pexpiretime(key(transport)); + + assertThat(store.reassert(transport, menu)).isTrue(); + verify(uses.get(1), never()).scriptLoad(any(byte[].class)); + verifyEvaluations(uses.get(1), sha1, 1); + + var controller = client(null, null); + try (var inspection = controller.connect(ByteArrayCodec.INSTANCE)) { + long originalPttl = inspection.sync().pttl(key(transport)); + assertThat(originalPttl).isPositive(); + flushScripts(); + // SCRIPT FLUSH discards code only, not the original menu or its physical deadline/PTTL. + assertThat(admin.get(key(transport))).isEqualTo(original); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(deadline); + assertThat(store.find(transport)).isPresent(); + verify(uses.get(2), never()).scriptLoad(any(byte[].class)); + verifyEvaluations(uses.get(2), sha1, 0); + assertThat(store.reassert(transport, menu)).isTrue(); + verify(uses.get(3)).scriptLoad(eq(source)); + verifyEvaluations(uses.get(3), sha1, 2); + assertThat(admin.get(key(transport))).isEqualTo(original); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(deadline); + assertThat(inspection.sync().pttl(key(transport))).isBetween(1L, originalPttl); + } finally { + controller.shutdown(); + } + + flushScripts(); + assertThat(store.clear(transport)).isTrue(); + verify(uses.get(4)).scriptLoad(eq(source)); + verifyEvaluations(uses.get(4), sha1, 2); + assertThat(admin.get(key(transport))).isNull(); + assertThat(store.reassert(transport, menu)).isFalse(); + verify(uses.get(5), never()).scriptLoad(any(byte[].class)); + verifyEvaluations(uses.get(5), sha1, 0); + for (var use : uses) verify(use).aclWhoami(); + } + + @Test + void exactTransportBindingRefusesReadReassertDiscoveryAndDeleteWithoutMutating() { + var fixture = fixture(Clock.systemUTC()); + var selection = fixture.selection(); + var store = store(selection, fixture.clock()); + var transport = observation(); + var menu = store.discoverAndReplace(transport).orElseThrow(); + byte[] original = admin.get(key(transport)); + long expiry = admin.pexpiretime(key(transport)); + var wrong = new ObservedDirectTextTransport("102", transport.proxyConnectionId()); + assertThat(store.find(wrong)).isEmpty(); + assertThat(store.reassert(wrong, menu)).isFalse(); + assertThat(store.discoverAndReplace(wrong)).isEmpty(); + assertThat(store.clear(wrong)).isFalse(); + assertThat(admin.get(key(transport))).isEqualTo(original); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(expiry); + assertThat(store.clear(transport)).isTrue(); + assertThat(admin.get(key(transport))).isNull(); + assertThat(store.find(transport)).isEmpty(); + } + + @ParameterizedTest + @ValueSource(strings = {"reassert", "delete-before-reassert", "discover", "clear"}) + void competingPreimageIsRefusedByRealLuaWithoutAutomaticRetry(String operation) { + var fixture = fixture(Clock.systemUTC()); + var selection = fixture.selection(); + var transport = observation(); + var menu = store(selection, fixture.clock()).discoverAndReplace(transport).orElseThrow(); + byte[] competitor = ascii("administrator-seeded-malformed-competing-ui"); + Supplier> racingConnection = + () -> { + var physical = writer.connect(ByteArrayCodec.INSTANCE); + var intercepted = delegatedCommands(physical.sync()); + doAnswer( + invocation -> { + byte[] prior = physical.sync().getrange(invocation.getArgument(0), 0, 2097152); + // Controlled administrator seed AFTER the actual bounded read, before real CAS. + if ("delete-before-reassert".equals(operation)) { + admin.del(new byte[][] {key(transport)}); + } else { + admin.set(key(transport), competitor); + } + // Cache loss must not bypass the original preimage on the load/retry path. + flushScripts(); + return prior; + }) + .when(intercepted) + .getrange(any(byte[].class), anyLong(), anyLong()); + return delegatedConnection(physical, intercepted); + }; + var racing = + new DirectTextWorldMenuRedisStore( + selection, fixture.clock(), racingConnection, installed()); + if ("discover".equals(operation)) { + assertThat(racing.discoverAndReplace(transport)).isEmpty(); + } else { + assertThat( + "clear".equals(operation) + ? racing.clear(transport) + : racing.reassert(transport, menu)) + .isFalse(); + } + if ("delete-before-reassert".equals(operation)) { + assertThat(admin.get(key(transport))).isNull(); + } else { + assertThat(admin.get(key(transport))).isEqualTo(competitor); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(-1L); + } + } + + @Test + void expiredAndDeletedUiRequiresFreshDiscoveryAndNeverRefreshesDeadline() throws Exception { + // The controlled menu was created 298 seconds ago; Redis's own wall clock enforces PXAT. + var clock = Clock.fixed(Instant.now().minusSeconds(298), ZoneOffset.UTC); + var fixture = fixture(clock); + var selection = fixture.selection(); + var transport = observation(); + var store = store(selection, Clock.systemUTC()); + var menu = store.discoverAndReplace(transport).orElseThrow(); + long expiry = admin.pexpiretime(key(transport)); + assertThat(expiry).isEqualTo(menu.expiresAt().toEpochMilli()); + assertThat(store.reassert(transport, menu)).isTrue(); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(expiry); + long wait = Math.max(0L, expiry - System.currentTimeMillis()) + 100L; + Thread.sleep(wait); + assertThat(admin.get(key(transport))).isNull(); + assertThat(store.find(transport)).isEmpty(); + assertThat(store.reassert(transport, menu)).isFalse(); + assertThat(admin.get(key(transport))).isNull(); + // Fresh WORLDS is the only replacement. Administrator deletion models disposable UI loss. + var freshFixture = fixture(Clock.systemUTC()); + var freshSelection = freshFixture.selection(); + var freshStore = store(freshSelection, freshFixture.clock()); + var fresh = freshStore.discoverAndReplace(transport).orElseThrow(); + admin.del(new byte[][] {key(transport)}); + assertThat(freshStore.find(transport)).isEmpty(); + assertThat(freshStore.reassert(transport, fresh)).isFalse(); + assertThat(admin.get(key(transport))).isNull(); + } + + @Test + void futureDeadlineAndMalformedBoundedStateCannotBeInstalledOrAdopted() { + var fixture = fixture(Clock.offset(Clock.systemUTC(), Duration.ofSeconds(10))); + var selection = fixture.selection(); + var transport = observation(); + // The owner rejects an original expiry >5 minutes after its single observed clock input. + assertThat(store(selection, Clock.systemUTC()).discoverAndReplace(transport)).isEmpty(); + assertThat(admin.get(key(transport))).isNull(); + var expiredFixture = fixture(Clock.offset(Clock.systemUTC(), Duration.ofSeconds(-301))); + var expiredSelection = expiredFixture.selection(); + // A menu expired relative to the owner's observation is refused without reconstruction. + assertThat(store(expiredSelection, Clock.systemUTC()).discoverAndReplace(transport)).isEmpty(); + assertThat(admin.get(key(transport))).isNull(); + var current = fixture(Clock.systemUTC()); + var currentSelection = current.selection(); + var currentStore = store(currentSelection, current.clock()); + byte[] oversized = new byte[2097153]; + admin.set(key(transport), oversized); + assertThat(currentStore.find(transport)).isEmpty(); + assertThat(currentStore.clear(transport)).isFalse(); + assertThat(currentStore.reassert(transport, currentSelection.browse().orElseThrow())).isFalse(); + assertThat(currentStore.discoverAndReplace(transport)).isEmpty(); + assertThat(admin.get(key(transport))).isEqualTo(oversized); + } + + @Test + void realPrincipalAndInstalledDigestMismatchAreDeniedBeforeMutation() { + var fixture = fixture(Clock.systemUTC()); + var selection = fixture.selection(); + var transport = observation(); + var wrongPrincipal = + new DirectTextWorldMenuRedisStore( + selection, + fixture.clock(), + () -> administrator.connect(ByteArrayCodec.INSTANCE), + installed()); + assertThatThrownBy(() -> wrongPrincipal.discoverAndReplace(transport)) + .isInstanceOf(IllegalStateException.class); + var original = installed().require(DirectTextWorldMenuRedisScriptContribution.SCRIPT_ID); + ObjectNode changed = (ObjectNode) JSON.valueToTree(original); + changed.put("sha256", "0".repeat(64)); + var mismatched = JSON.treeToValue(changed, RedisScriptDescriptor.class); + var badCatalog = + RedisScriptCatalog.fromContributions( + List.of( + new RedisScriptContribution() { + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + return List.of(mismatched); + } + })); + assertThatThrownBy( + () -> + new DirectTextWorldMenuRedisStore( + selection, + fixture.clock(), + () -> writer.connect(ByteArrayCodec.INSTANCE), + badCatalog)) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.get(key(transport))).isNull(); + } + + @Test + void lostSuccessfulWriteReplyEscapesAsUnknownRatherThanFakeSuccess() { + var fixture = fixture(Clock.systemUTC()); + var selection = fixture.selection(); + var transport = observation(); + var failure = new IllegalStateException("controlled lost script reply"); + Supplier> replyLoss = + () -> { + var physical = writer.connect(ByteArrayCodec.INSTANCE); + var intercepted = delegatedCommands(physical.sync()); + doAnswer( + invocation -> { + String result = + physical + .sync() + .evalsha( + invocation.getArgument(0, String.class), + ScriptOutputType.STATUS, + invocation.getArgument(2, byte[][].class), + invocation.getArgument(3, byte[].class), + invocation.getArgument(4, byte[].class), + invocation.getArgument(5, byte[].class), + invocation.getArgument(6, byte[].class), + invocation.getArgument(7, byte[].class)); + assertThat(result).isEqualTo("MENU_WRITTEN"); + throw failure; + }) + .when(intercepted) + .evalsha( + anyString(), + eq(ScriptOutputType.STATUS), + any(byte[][].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class)); + return delegatedConnection(physical, intercepted); + }; + var losing = + new DirectTextWorldMenuRedisStore(selection, fixture.clock(), replyLoss, installed()); + assertThatThrownBy(() -> losing.discoverAndReplace(transport)).isSameAs(failure); + assertThat(admin.get(key(transport))).isNotEmpty(); + var replacement = fixture.selection(); + var menu = store(replacement, fixture.clock()).find(transport).orElseThrow(); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(menu.expiresAt().toEpochMilli()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void unexpiredOriginalAndFindRestoredHandlesCannotRecreateDeletedOrResetMenu( + boolean restoredHandle) { + var clock = mock(Clock.class); + var now = Instant.now(); + when(clock.instant()).thenReturn(now); + when(clock.millis()).thenReturn(now.toEpochMilli()); + var fixture = fixture(clock); + var selection = fixture.selection(); + var store = store(selection, clock); + var transport = observation(); + var original = store.discoverAndReplace(transport).orElseThrow(); + var retained = restoredHandle ? store.find(transport).orElseThrow() : original; + byte[] originalBytes = admin.get(key(transport)); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(original.expiresAt().toEpochMilli()); + + // Exact-key DEL models missing/reset UI state while both handles remain unexpired. + admin.del(new byte[][] {key(transport)}); + assertThat(store.reassert(transport, retained)).isFalse(); + assertThat(store.find(transport)).isEmpty(); + assertThat(admin.get(key(transport))).isNull(); + + when(clock.instant()).thenReturn(now.plusSeconds(1)); + when(clock.millis()).thenReturn(now.plusSeconds(1).toEpochMilli()); + clearInvocations(fixture.routes()); + var fresh = store.discoverAndReplace(transport).orElseThrow(); + verify(fixture.routes()).readVisiblePublicProductionTargets(); + assertThat(fresh).isNotSameAs(retained); + assertThat(fresh.expiresAt()).isEqualTo(original.expiresAt().plusSeconds(1)); + byte[] freshBytes = admin.get(key(transport)); + assertThat(freshBytes).isNotEqualTo(originalBytes); + long freshDeadline = admin.pexpiretime(key(transport)); + assertThat(freshDeadline).isEqualTo(fresh.expiresAt().toEpochMilli()); + // Even a valid but different present preimage cannot be adopted by the old handle. + assertThat(store.reassert(transport, retained)).isFalse(); + assertThat(admin.get(key(transport))).isEqualTo(freshBytes); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(freshDeadline); + assertThat(store.reassert(transport, fresh)).isTrue(); + assertThat(admin.pexpiretime(key(transport))).isEqualTo(freshDeadline); + } + + private DirectTextWorldMenuRedisStore store( + DirectTextWorldSelectionService selection, Clock clock) { + return new DirectTextWorldMenuRedisStore( + selection, clock, () -> writer.connect(ByteArrayCodec.INSTANCE), installed()); + } + + private static void flushScripts() { + // The default fixture controller exists only in this isolated disposable Redis. Application + // and scoped administrator ACLs are unchanged; neither receives SCRIPT FLUSH permission. + var controller = client(null, null); + try (var connection = controller.connect(ByteArrayCodec.INSTANCE)) { + assertThat(connection.sync().scriptFlush()).isEqualTo("OK"); + } finally { + controller.shutdown(); + } + } + + private static void verifyEvaluations( + RedisCommands commands, String sha1, int count) { + verify(commands, times(count)) + .evalsha( + eq(sha1), + eq(ScriptOutputType.STATUS), + any(byte[][].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class)); + } + + private ObservedDirectTextTransport observation() { + var observed = new ObservedDirectTextTransport("101", UUID.randomUUID()); + ownedKeys.add(key(observed)); + return observed; + } + + private static byte[] key(ObservedDirectTextTransport transport) { + return ascii(DirectTextWorldMenuRedisStore.OWNED_PREFIX + transport.proxyConnectionId()); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static RedisScriptCatalog installed() { + return RedisScriptCatalog.loadInstalled(DirectTextWorldMenuRedisStore.class.getClassLoader()); + } + + private static RedisClient client(String principal, String password) { + var uri = RedisURI.builder().withHost(REDIS.getHost()).withPort(REDIS.getMappedPort(6379)); + if (principal != null) uri.withAuthentication(principal, password); + var client = RedisClient.create(uri.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + @SuppressWarnings("unchecked") + private static RedisCommands delegatedCommands( + RedisCommands actual) { + return mock(RedisCommands.class, delegatesTo(actual)); + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection delegatedConnection( + StatefulRedisConnection physical, RedisCommands commands) { + StatefulRedisConnection connection = + mock(StatefulRedisConnection.class, delegatesTo(physical)); + when(connection.sync()).thenReturn(commands); + return connection; + } + + private static Fixture fixture(Clock clock) { + var first = target(false); + var second = target(true); + var targets = List.of(first, second); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(targets); + targets.forEach(target -> when(routes.readCurrentTarget(target)).thenReturn(target)); + return new Fixture( + clock, + targets, + GameplayWorldCatalog.forWorldViews(List.of(world(second), world(first))), + routes); + } + + private record Fixture( + Clock clock, + List targets, + GameplayWorldCatalog catalog, + CanonicalPlayerRouteReadService routes) { + DirectTextWorldSelectionService selection() { + return new DirectTextWorldSelectionService(catalog, routes, clock); + } + } + + private static WorldView world(CanonicalPlayableTarget target) { + return new WorldView( + target.worldSlug(), + target.worldDisplayName(), + List.of( + new RealmView( + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.pointerVersion(), + true, + true, + false, + target.playableStateScope(), + target.characterCreationPolicy(), + target.catalogRevision(), + target.realmId(), + target.playableStateNamespaceId()))); + } + + private static CanonicalPlayableTarget target(boolean second) { + return new CanonicalPlayableTarget( + "gameplay", + second ? "other" : "studio", + UUID.randomUUID(), + second ? "second" : "forest", + "World", + UUID.randomUUID(), + "public", + "Public", + second ? 909L : 101L, + second ? 808L : 202L, + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + UUID.randomUUID(), + 303L, + 1L, + 7L, + "d".repeat(64), + 82L, + "original-open", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "c".repeat(64), + 27L, + "sha256:" + "f".repeat(64), + Outcome.COMMITTED, + false, + Instant.parse("2026-10-01T00:00:00Z"), + "ALLOW_NEW"); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index a0f9a955c6..0af1d18ac7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1157,7 +1157,10 @@ private static List regionMigrationHistoryImage(DSLContext dsl) { } private static int upgradeRegionSchema(TestSchema schema) { + // This retained upgrade proves the exact region-bridge migration pair, independently of + // unrelated migrations added later. Fresh-schema/current-version coverage remains separate. return regionMigrations(schema.dataSource(), schema.schema()) + .target("1051.1") .load() .migrate() .migrationsExecuted; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java index 88e3ff6ffa..61d1fe3926 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java @@ -13,6 +13,8 @@ import java.util.Map; import java.util.UUID; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -43,6 +45,40 @@ class GameplayAdmissionPointerMigrationIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void pointerListsOrderMatchingSlugsByTenantWithoutChangingRows() { + DriverManagerDataSource dataSource = isolatedDataSource(); + migrateToVersion(dataSource, "5"); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + // Insert the matching selectors in descending tenant order, with world and realm controls. + insertPointer(dsl, 1L, 20L, "demo", "live", 201L, true, true, "SHARED"); + insertPointer(dsl, 2L, 10L, "demo", "live", 101L, true, true, "SHARED"); + insertPointer(dsl, 3L, 20L, "alpha", "preview", 202L, false, false, "ISOLATED"); + insertPointer(dsl, 4L, 10L, "demo", "preview", 102L, true, false, "SHARED"); + migrateToVersion(dataSource, "8"); + DatabaseGameplayAdmissionPointerAuthorityService service = + new DatabaseGameplayAdmissionPointerAuthorityService( + new GameplayAdmissionPointerRepository(dsl), + new GameplayAdmissionPointerEventRepository(dsl)); + var rowsBefore = dsl.fetch("SELECT * FROM gameplay_admission_pointer ORDER BY id"); + List expected = + List.of( + service.findPointer(20L, "alpha", "preview").orElseThrow(), + service.findPointer(10L, "demo", "live").orElseThrow(), + service.findPointer(20L, "demo", "live").orElseThrow(), + service.findPointer(10L, "demo", "preview").orElseThrow()); + + assertThat(service.listPointers()).containsExactlyElementsOf(expected); + assertThat(service.listPointersForTenants(List.of(20L, 10L))) + .containsExactlyElementsOf(expected); + assertThat(service.listPointersForTenants(List.of(10L, 20L))) + .containsExactlyElementsOf(expected); + assertThat(service.listPointersForTenants(List.of(10L))) + .containsExactly(expected.get(1), expected.get(3)); + assertThat(dsl.fetch("SELECT * FROM gameplay_admission_pointer ORDER BY id")) + .isEqualTo(rowsBefore); + } + @Test void v8RepairsOnlyProvenRetainedBootstrapPairAndLeavesDemoAndRuntimeIdentityUnchanged() throws IOException { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java new file mode 100644 index 0000000000..e0f920accf --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java @@ -0,0 +1,1034 @@ +package integration.net.firedevops.firemud.gamesession.service.directtext; + +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.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.sql.DriverManager; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin.State; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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.json.JsonMapper; + +/** + * Native PostgreSQL migration/owner proof with controlled RSA Account responses, guarded catalog + * reads and custody fixtures. No live ingress, protected production DB delivery, PKI, hidden + * rebind, registration, cleanup, enrollment, activation, actor selection or gameplay admission is + * proved. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class DirectTextAuthenticatedLobbyIntegrationTest { + private static final Instant NOW = Instant.parse("2026-11-01T12:00:00Z"); + private static final Clock VERIFY_CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String PARENT = "game_session_initial_gameplay_login_journal"; + private static final String SCOPE = DirectTextAuthenticatedLobbyRepository.SCOPE; + private static final String CURRENT = DirectTextAuthenticatedLobbyRepository.CURRENT; + private static final String JOIN = DirectTextAuthenticatedLobbyRepository.JOIN; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static KeyPair keys; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DriverManagerDataSource source; + private DSLContext dsl; + private DataSourceTransactionManager manager; + private TransactionTemplate tx; + private InitialGameplayLoginCoordinationJournalRepository journal; + private DirectTextAuthenticatedLobbyRepository repository; + private DirectTextAuthenticatedLobbyOwner owner; + private DirectTextWorldSelectionService selection; + private AccountClient account; + private CanonicalGameplayLoginResult verified; + private InitialGameplayLoginAttemptCoordinates original; + private ControlledCustody custody; + private final MutableClock clock = new MutableClock(); + private CanonicalPlayableTarget target; + private String parentBeforeMigration; + + @BeforeAll + static void signingAndPostgres() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + keys = generator.generateKeyPair(); + } + + @BeforeEach + void migratePopulatedOriginalThenComposeInactiveOwner() throws Exception { + schema = "gs_direct_text_lobby_" + UUID.randomUUID().toString().replace("-", ""); + source = new DriverManagerDataSource(); + source.setDriverClassName("org.postgresql.Driver"); + source.setUrl(postgres.getJdbcUrl()); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + source.setSchema(schema); + migration("1051.1").migrate(); + dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + manager = new DataSourceTransactionManager(source); + tx = new TransactionTemplate(manager); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + tx.setTimeout(15); + journal = new InitialGameplayLoginCoordinationJournalRepository(dsl); + original = new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); + verified = verified(original, ACCOUNT, UUID.randomUUID(), "5"); + tx.executeWithoutResult( + status -> { + journal.reserve(original); + journal.recordVerifiedResult(original, verified); + }); + parentBeforeMigration = parentJson(); + migration(null).migrate(); + repository = new DirectTextAuthenticatedLobbyRepository(dsl); + account = mock(AccountClient.class); + target = target(); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(target)); + when(routes.readCurrentTarget(target)).thenReturn(target); + var world = + new WorldView( + target.worldSlug(), + target.worldDisplayName(), + List.of( + new RealmView( + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.pointerVersion(), + true, + true, + false, + target.playableStateScope(), + target.characterCreationPolicy(), + target.catalogRevision(), + target.realmId(), + target.playableStateNamespaceId()))); + selection = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldSupplier(() -> List.of(world)), routes, clock); + custody = + new ControlledCustody( + original, verified, new ObservedDirectTextTransport("00042", UUID.randomUUID())); + when(account.issueDirectTextConnectScope(any(), any())) + .thenAnswer( + call -> + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-" + UUID.randomUUID()) + .setEvaluatedAt(NOW.minusSeconds(1).toString()) + .setConnectScopeExpiresAt(NOW.plusSeconds(60).toString()) + .build()); + owner = owner(repository, manager); + } + + private Flyway migration(String targetVersion) { + var config = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); + if (targetVersion != null) config.target(targetVersion); + return config.load(); + } + + @AfterEach + void closeOnlyOwnedResultAndSchema() throws Exception { + if (verified != null) verified.close(); + if (schema != null) { + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + } + + @Test + void forwardMigrationPreservesPopulatedMinimalParentAndFullExactNonsecretScope() { + assertThat(parentJson()).isEqualTo(parentBeforeMigration); + var scope = realms(); + var stored = repository.readCommittedScope(scope); + assertThat(stored.encode()).containsExactly(scope.encode()); + assertThat(stored.publicTarget()).isEqualTo(target); + assertThat(stored.evidence()).isEqualTo(verified.evidence()); + assertThat(stored.transport()).isEqualTo(custody.transport); + assertThat(stored.issued().evaluatedAt()).isEqualTo(NOW.minusSeconds(1).toString()); + assertThat(stored.issued().connectScopeExpiresAt()).isEqualTo(NOW.plusSeconds(60).toString()); + assertThat(new String(stored.encode(), StandardCharsets.UTF_8)) + .doesNotContain("fixture-transient-secret", "eyJhbGci", "authToken", "password"); + assertThat(parentJson()).isEqualTo(parentBeforeMigration); + reject("DELETE FROM " + PARENT + " WHERE request_id = ?", original.requestId()); + } + + @Test + void actualOwnerReadsCommittedExactRequestBeforeAccountAndRetainsPositiveReply() { + var scope = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var row = + dsl.fetchSingle( + "SELECT * FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()); + assertThat(row.get("state", String.class)).isEqualTo("DISPATCH_POSSIBLE"); + var request = + DirectTextAuthenticatedLobbyJoin.decodeRequest( + row.get("request_bytes", byte[].class)); + assertThat(request.getPlayerContext()) + .isEqualTo( + call.getArgument( + 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); + assertThat(request.getPlayerContext().getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(request.getPlayerContext().getSessionId()) + .isEqualTo(custody.transport.transportSessionId()); + assertThat(request.getConnectScopeId()).isEqualTo(scope.issued().connectScopeId()); + assertThat(request.getConnectScopeId()).isEqualTo(call.getArgument(1, String.class)); + assertThat(request.getRequestId()).isEqualTo(call.getArgument(2, String.class)); + assertThat(call.getArgument(3, Instant.class)) + .isEqualTo(scope.issued().connectScopeExpiresAtInstant()); + return positive(); + }); + var completed = owner.join(original, verified, custody); + assertThat(completed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); + assertThat(completed.currentReply()).contains(positive()); + var continuation = owner(repository, manager).join(original, verified, custody); + assertThat(continuation.requestId()).isEqualTo(completed.requestId()); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + + @Test + void independentConnectionsAllocateOneFrozenWinnerAndOnlyOneDispatchClaim() throws Exception { + realms(); + var gate = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var one = + executor.submit( + () -> { + await(gate); + return freeze(); + }); + var two = + executor.submit( + () -> { + await(gate); + return freeze(); + }); + gate.countDown(); + var first = one.get(10, TimeUnit.SECONDS); + var second = two.get(10, TimeUnit.SECONDS); + assertThat(second.request()).isEqualTo(first.request()); + assertThat(first.requestId()) + .isNotIn( + original.requestId(), + original.callerContextId(), + first.scope().recordId(), + custody.transport.proxyConnectionId(), + verified.evidence().tokenJti()); + var a = executor.submit(() -> claim(first)); + var b = executor.submit(() -> claim(second)); + assertThat(List.of(a.get(10, TimeUnit.SECONDS), b.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(repository.readCommittedJoin(first).state()).isEqualTo(State.DISPATCH_POSSIBLE); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } finally { + gate.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void actualParentAbandonmentAndDispatchClaimSerializeInBothOrders(boolean abandonmentFirst) + throws Exception { + realms(); + var frozen = freeze(); + var locked = new CountDownLatch(1); + var release = new CountDownLatch(1); + var followerStarted = new CountDownLatch(1); + var followerPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var winner = + executor.submit( + () -> + tx.execute( + status -> { + repository.verifyOriginal(original, verified); + if (abandonmentFirst) journal.abandon(original); + else + assertThat( + repository.claimDispatch( + frozen, verified, custody.transport, clock)) + .isTrue(); + locked.countDown(); + await(release); + return true; + })); + assertThat(locked.await(5, TimeUnit.SECONDS)).isTrue(); + var follower = + executor.submit( + () -> { + try { + return tx.execute( + status -> { + followerPid.set( + dsl.fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class)); + followerStarted.countDown(); + if (abandonmentFirst) + return repository.claimDispatch( + frozen, verified, custody.transport, clock); + journal.abandon(original); + return true; + }); + } catch (IllegalStateException denied) { + return false; + } + }); + assertThat(followerStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitActualLockWait(followerPid.get()); + assertThat(follower.isDone()).isFalse(); + release.countDown(); + assertThat(winner.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(follower.get(10, TimeUnit.SECONDS)).isEqualTo(!abandonmentFirst); + var retained = repository.readCommittedJoin(frozen); + assertThat(retained.state()) + .isEqualTo(abandonmentFirst ? State.NEVER_DISPATCHED : State.DISPATCH_POSSIBLE); + assertThat(journal.readCommitted(original).orElseThrow().abandoned()).isTrue(); + assertThatThrownBy(() -> claim(frozen)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(this::realms).isInstanceOf(IllegalStateException.class); + verify(account, times(1)).issueDirectTextConnectScope(any(), any()); + if (!abandonmentFirst) { + tx.executeWithoutResult( + status -> repository.recordPositiveReply(retained, verified, positive())); + assertThat(repository.readCommittedJoin(retained).reply()).contains(positive()); + } + } finally { + release.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void freshExplicitRealmsPreservesOlderUnknownAndForbidsStaleDispatch() { + var older = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(unknown()); + var first = owner.join(original, verified, custody); + var oldOriginal = + dsl.fetchSingle( + "SELECT request_bytes FROM " + JOIN + " WHERE scope_record_id = ?", + older.recordId()) + .get("request_bytes", byte[].class); + var newer = realms(); + assertThat(newer.recordId()).isNotEqualTo(older.recordId()); + assertThat(repository.readCommittedScope(older).encode()).containsExactly(older.encode()); + assertThat( + dsl.fetchSingle( + "SELECT request_bytes FROM " + JOIN + " WHERE scope_record_id = ?", + older.recordId()) + .get("request_bytes", byte[].class)) + .containsExactly(oldOriginal); + var oldJoin = + new DirectTextAuthenticatedLobbyJoin( + older, + DirectTextAuthenticatedLobbyJoin.decodeRequest(oldOriginal), + State.DISPATCH_POSSIBLE, + Optional.empty()); + assertThatThrownBy(() -> claim(oldJoin)).isInstanceOf(IllegalStateException.class); + var second = owner.join(original, verified, custody); + assertThat(second.requestId()).isNotEqualTo(first.requestId()); + assertThat(dsl.fetchCount(DSL.table(SCOPE))).isEqualTo(2); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(2); + assertThat(parentJson()).isEqualTo(parentBeforeMigration); + } + + @Test + void lostReplyLeavesOriginalUnresolvedAcrossOwnerReplacementAndExpiryOrResetDoesNotEraseIt() { + realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("Controlled lost reply")); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + var continued = owner(repository, manager).join(original, verified, custody); + assertThat(continued.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + var before = joinJson(); + clock.now = NOW.plusSeconds(60); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalArgumentException.class); + clock.now = NOW; + custody.reset(); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + assertThat(joinJson()).isEqualTo(before); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void lostCommittedFreezeOrDispatchResponseRetainsSameOriginalWithoutAutomaticReissue( + boolean loseFreeze) { + realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(positive()); + var loseCommit = new AtomicBoolean(); + var instrumented = spy(repository); + if (loseFreeze) { + doAnswer( + call -> { + Object value = call.callRealMethod(); + loseCommit.set(true); + return value; + }) + .when(instrumented) + .freezeCurrentJoin(any(), any(), any(), any()); + } else { + doAnswer( + call -> { + Object value = call.callRealMethod(); + loseCommit.set(true); + return value; + }) + .when(instrumented) + .claimDispatch(any(), any(), any(), any()); + } + var losingManager = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return manager.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + manager.commit(status); + if (loseCommit.getAndSet(false)) + throw new IllegalStateException("Controlled committed owner reply loss"); + } + + @Override + public void rollback(TransactionStatus status) { + manager.rollback(status); + } + }; + assertThatThrownBy(() -> owner(instrumented, losingManager).join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + UUID retainedId = + dsl.fetchSingle("SELECT join_request_id FROM " + JOIN).get("join_request_id", UUID.class); + verify(account, times(0)).joinPublicProductionMembership(any(), any(), any(), any()); + var continued = owner(repository, manager).join(original, verified, custody); + assertThat(continued.requestId()).isEqualTo(retainedId); + assertThat(continued.status()) + .isEqualTo( + loseFreeze + ? DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING + : DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + verify(account, times(loseFreeze ? 1 : 0)) + .joinPublicProductionMembership(any(), any(), any(), any()); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void lostResultPersistenceOutcomeNeverRearmsOrOverwrites(boolean committedBeforeLoss) { + realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(positive()); + var loseAfterCommit = new AtomicBoolean(); + var instrumented = spy(repository); + doAnswer( + call -> { + call.callRealMethod(); + if (committedBeforeLoss) loseAfterCommit.set(true); + else throw new IllegalStateException("Controlled result transaction rollback"); + return null; + }) + .when(instrumented) + .recordPositiveReply(any(), any(), any()); + var losingManager = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return manager.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + manager.commit(status); + if (loseAfterCommit.getAndSet(false)) + throw new IllegalStateException("Controlled committed reply loss"); + } + + @Override + public void rollback(TransactionStatus status) { + manager.rollback(status); + } + }; + assertThatThrownBy(() -> owner(instrumented, losingManager).join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + var continued = owner(repository, manager).join(original, verified, custody); + assertThat(continued.status()) + .isEqualTo( + committedBeforeLoss + ? DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING + : DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } + + @Test + void positiveInflightResultAfterAbandonmentAndTransportResetIsHistoricalOnly() { + var scope = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + tx.executeWithoutResult(status -> journal.abandon(original)); + custody.resetAfterCurrentCallback(); + return positive(); + }); + var observed = owner.join(original, verified, custody); + assertThat(observed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); + assertThat(observed.currentReply()).isEmpty(); + byte[] reply = + dsl.fetchSingle( + "SELECT reply_bytes FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()) + .get("reply_bytes", byte[].class); + assertThat(DirectTextAuthenticatedLobbyJoin.decodeReply(scope, reply)).isEqualTo(positive()); + } + + @Test + void delayedPositiveResultDoesNotMoveANewerCurrentScope() { + var old = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + var newer = realms(); + assertThat(newer.recordId()).isNotEqualTo(old.recordId()); + return positive(); + }); + var observed = owner.join(original, verified, custody); + assertThat(observed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); + assertThat(observed.currentReply()).isEmpty(); + var currentId = + dsl.fetchSingle("SELECT scope_record_id FROM " + CURRENT) + .get("scope_record_id", UUID.class); + assertThat(currentId).isNotEqualTo(old.recordId()); + assertThat( + dsl.fetchSingle( + "SELECT state FROM " + JOIN + " WHERE scope_record_id = ?", old.recordId()) + .get("state", String.class)) + .isEqualTo("COMPLETED"); + } + + @Test + void currentVerifiedIdentityAndCompleteWitnessAreRequiredNotMerelyMatchingSqlOrFlags() + throws Exception { + realms(); + try (var differentAccount = + verified(original, UUID.randomUUID(), verified.evidence().tokenJti(), "5"); + var differentWitness = verified(original, ACCOUNT, UUID.randomUUID(), "6")) { + assertThatThrownBy( + () -> + tx.execute( + status -> + repository.current(original, differentAccount, custody.transport, clock))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx.execute( + status -> + repository.current(original, differentWitness, custody.transport, clock))) + .isInstanceOf(IllegalStateException.class); + } + var wrongFence = + new InitialGameplayLoginAttemptCoordinates( + original.requestId(), original.callerContextId(), 8); + assertThatThrownBy( + () -> + tx.executeWithoutResult(status -> repository.verifyOriginal(wrongFence, verified))) + .isInstanceOf(IllegalStateException.class); + var missing = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 1); + try (var result = verified(missing, ACCOUNT, UUID.randomUUID(), "1")) { + assertThatThrownBy( + () -> tx.executeWithoutResult(status -> repository.verifyOriginal(missing, result))) + .isInstanceOf(IllegalStateException.class); + tx.executeWithoutResult(status -> journal.reserve(missing)); + assertThatThrownBy( + () -> tx.executeWithoutResult(status -> repository.verifyOriginal(missing, result))) + .isInstanceOf(IllegalStateException.class); + } + verified.close(); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isZero(); + } + + @Test + void directSqlProtectsEveryCompanionAndRefusesInvalidIdentityTransitionsAndPointerRegression() { + var oldScope = realms(); + var frozen = freeze(); + reject( + "UPDATE " + JOIN + " SET state = 'COMPLETED', reply_bytes = ?", positive().toByteArray()); + reject("UPDATE " + JOIN + " SET join_request_id = ?", original.requestId()); + reject("UPDATE " + JOIN + " SET request_bytes = ?", new byte[] {1}); + assertThat(claim(frozen)).isTrue(); + reject("UPDATE " + JOIN + " SET state = 'NEVER_DISPATCHED'"); + tx.executeWithoutResult(status -> repository.recordPositiveReply(frozen, verified, positive())); + reject( + "UPDATE " + JOIN + " SET reply_bytes = ?", + positive().toBuilder().setReplayed(true).build().toByteArray()); + reject("UPDATE " + SCOPE + " SET account_id = ?", UUID.randomUUID()); + reject("UPDATE " + SCOPE + " SET scope_bytes = ?", new byte[] {1}); + realms(); + reject( + "UPDATE " + + CURRENT + + " SET scope_record_id = ?, scope_sequence = (SELECT scope_sequence FROM " + + SCOPE + + " WHERE scope_record_id = ?)", + oldScope.recordId(), + oldScope.recordId()); + for (String table : List.of(JOIN, CURRENT, SCOPE)) { + assertThatThrownBy(() -> dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("retention is held") + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("retention is held") + .isInstanceOf(DataAccessException.class); + } + assertThat(dsl.fetchCount(DSL.table(SCOPE))).isEqualTo(2); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } + + @Test + void nonDurableUnjoinedOrAmbientTransactionsCannotSupplyReadbackOrDispatchEvidence() { + realms(); + assertThatThrownBy(this::freezeWithoutTransaction).isInstanceOf(IllegalStateException.class); + var frozen = freeze(); + assertThatThrownBy(() -> tx.execute(status -> repository.readCommittedJoin(frozen))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx.execute( + status -> { + dsl.execute("SET LOCAL synchronous_commit = 'off'"); + return repository.claimDispatch(frozen, verified, custody.transport, clock); + })) + .isInstanceOf(IllegalStateException.class); + var unjoined = + new DirectTextAuthenticatedLobbyRepository(DSL.using(source, SQLDialect.POSTGRES)); + assertThatThrownBy( + () -> + tx.execute( + status -> unjoined.claimDispatch(frozen, verified, custody.transport, clock))) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.readCommittedJoin(frozen).state()).isEqualTo(State.NEVER_DISPATCHED); + } + + private DirectTextAuthenticatedLobbyOwner owner( + DirectTextAuthenticatedLobbyRepository repo, PlatformTransactionManager transactions) { + return new DirectTextAuthenticatedLobbyOwner(repo, selection, account, transactions, clock); + } + + private DirectTextAuthenticatedLobbyScope realms() { + return owner.realms(original, verified, custody, selection.browse().orElseThrow(), "1"); + } + + private DirectTextAuthenticatedLobbyJoin freeze() { + return tx.execute(status -> freezeWithoutTransaction()); + } + + private DirectTextAuthenticatedLobbyJoin freezeWithoutTransaction() { + return repository.freezeCurrentJoin(original, verified, custody.transport, clock); + } + + private boolean claim(DirectTextAuthenticatedLobbyJoin frozen) { + return Boolean.TRUE.equals( + tx.execute(status -> repository.claimDispatch(frozen, verified, custody.transport, clock))); + } + + private String parentJson() { + return dsl.fetchSingle( + "SELECT to_jsonb(p)::text AS value FROM " + PARENT + " p WHERE request_id = ?", + original.requestId()) + .get("value", String.class); + } + + private String joinJson() { + return dsl.fetchSingle("SELECT to_jsonb(j)::text AS value FROM " + JOIN + " j") + .get("value", String.class); + } + + private void reject(String sql, Object... values) { + assertThatThrownBy(() -> dsl.execute(sql, values)) + .isInstanceOfSatisfying( + DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + } + + private void awaitActualLockWait(int pid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + if (Boolean.TRUE.equals( + dsl.fetchSingle("SELECT cardinality(pg_blocking_pids(?)) > 0 AS waiting", pid) + .get("waiting", Boolean.class))) return; + Thread.onSpinWait(); + } + throw new IllegalStateException( + "Independent original owner did not reach a PostgreSQL lock wait"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Bounded lobby fixture timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Lobby fixture interrupted", failure); + } + } + + private static JoinPublicProductionMembershipResponse positive() { + return JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(ACCOUNT.toString()) + .setTenantId("101") + .setMembershipId("90") + .setMembershipVersion(3) + .setMembershipAuthorityGeneration(1) + .build(); + } + + private static JoinPublicProductionMembershipResponse unknown() { + return JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("AUTH_UNAVAILABLE") + .setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE")) + .build(); + } + + private static CanonicalPlayableTarget target() { + return new CanonicalPlayableTarget( + "gameplay", + "studio", + UUID.randomUUID(), + "forest", + "Forest", + UUID.randomUUID(), + "public", + "Live", + 101, + 202, + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + UUID.randomUUID(), + 303, + 1, + 7, + "d".repeat(64), + 82, + "original-open", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "c".repeat(64), + 27, + "sha256:" + "f".repeat(64), + Outcome.COMMITTED, + false, + NOW.minusSeconds(1), + "ALLOW_NEW"); + } + + /** Controlled protected-call exclusion only; no claim of a real TCP/private-result producer. */ + private static final class ControlledCustody implements DirectTextAuthenticatedLobbyCustody { + private final InitialGameplayLoginAttemptCoordinates original; + private final CanonicalGameplayLoginResult result; + private final ObservedDirectTextTransport transport; + private boolean live = true; + private boolean resetAfterCallback; + + ControlledCustody( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult result, + ObservedDirectTextTransport transport) { + this.original = original; + this.result = result; + this.transport = transport; + } + + synchronized void reset() { + live = false; + } + + synchronized void resetAfterCurrentCallback() { + resetAfterCallback = true; + } + + @Override + public synchronized T withCurrent( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult borrowed, + Function action) { + if (!live || !original.equals(coordinates) || borrowed != result) + throw new IllegalStateException("Controlled custody unavailable"); + try { + return action.apply(transport); + } finally { + if (resetAfterCallback) live = false; + } + } + } + + private static final class MutableClock extends Clock { + private Instant now = NOW; + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return Clock.fixed(now, zone); + } + + @Override + public Instant instant() { + return now; + } + } + + /** Real signature/aggregate validation with locally controlled keys, not real Account custody. */ + private static CanonicalGameplayLoginResult verified( + InitialGameplayLoginAttemptCoordinates original, UUID accountId, UUID jti, String fence) + throws Exception { + long now = NOW.getEpochSecond(); + var claims = + new LinkedHashMap( + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("sub", accountId.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("jti", jti.toString()), + Map.entry("iat", now - 2), + Map.entry("nbf", now - 2), + Map.entry("exp", now + 120), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", fence), + Map.entry("membershipVersion", Map.of()), + Map.entry( + "authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1, 1)))); + var encoder = Base64.getUrlEncoder().withoutPadding(); + String input = + encoder.encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"test-key\",\"typ\":\"JWT\"}" + .getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(JSON.writeValueAsBytes(claims)); + var signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keys.getPrivate()); + signer.update(input.getBytes(StandardCharsets.US_ASCII)); + String token = input + "." + encoder.encodeToString(signer.sign()); + var request = + AuthenticateRequest.newBuilder() + .setRequestId(original.requestId().toString()) + .setEmail("player@example.test") + .setPassword("fixture-transient-secret") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(original.callerContextId().toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + var response = + AuthenticateResponse.newBuilder() + .setAuthToken(token) + .setAccountId(accountId.toString()) + .setRequestId(original.requestId().toString()) + .setCallerContextId(original.callerContextId().toString()) + .setTokenJti(jti.toString()) + .setTokenSha256( + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.US_ASCII)))) + .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) + .setIssuedAtEpochSeconds(now - 2) + .setNotBeforeEpochSeconds(now - 2) + .setExpiresAtEpochSeconds(now + 120) + .setTokenGeneration("1") + .setIssuanceFence(fence) + .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) + .setOutboxCheckpointsCanonicalJson( + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + accountId, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/firemud-account-service", + "outboxSequence", + "0")))) + .setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of())) + .build(); + var pin = + new AccountPublicJwksCache.SourceIdentity( + "test", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "binding-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + var key = (RSAPublicKey) keys.getPublic(); + String jwks = + JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + "test-key", + "n", + unsigned(key.getModulus().toByteArray()), + "e", + unsigned(key.getPublicExponent().toByteArray()))))); + var cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + pin, jwks.getBytes(StandardCharsets.UTF_8)), + pin, + VERIFY_CLOCK, + Duration.ofSeconds(30)); + return CanonicalGameplayLoginResult.fromAuthenticatedResponse( + response, request, new AccountAsymmetricJwtVerifier(cache, VERIFY_CLOCK), VERIFY_CLOCK); + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } + + private static String unsigned(byte[] bytes) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes); + } +} 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 887eb3a632..88aea73f47 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 @@ -1,11 +1,13 @@ 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.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; 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,6 +17,11 @@ 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.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.account.AuthenticationErrorCodes; @@ -27,6 +34,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,13 +45,666 @@ 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.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; class AccountClientTest { private static final String ACCOUNT_UUID = "00000000-0000-4000-8000-000000000042"; + private static final Instant JOIN_TEST_NOW = Instant.parse("2026-10-02T00:00:00Z"); + + @Test + void directTextScopeCapturesExactCompleteRequest() throws Exception { + RetryFixture fixture = newRetryFixture(); + var expected = + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("account-issued-scope") + .setConnectScopeExpiresAt("2030-01-01T00:00:00Z") + .build(); + when(fixture.initialStub().issueDirectTextConnectScope(any())).thenReturn(expected); + // Session/request are bounded opaque text, not numeric IDs. Preserve their exact bytes. + var context = + directTextContext().toBuilder() + .setSessionId(" transport-session ") + .setRequestId(" scope-request ") + .build(); + var target = directTextTarget(); + + assertThat(fixture.client().issueDirectTextConnectScope(context, target)).isEqualTo(expected); + + var captor = ArgumentCaptor.forClass(IssueDirectTextConnectScopeRequest.class); + verify(fixture.initialStub()).issueDirectTextConnectScope(captor.capture()); + assertThat(captor.getValue()) + .isEqualTo( + IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(context) + .setTenantId("22") + .setWorldSlug("demo-world") + .setRealmSlug("production") + .setRealmId(target.realmId()) + .setPlayableStateNamespaceId(target.playableStateNamespaceId()) + .setPlayableStateScope("SHARED") + .setGameInstanceId("9") + .setCatalogRevision(7L) + .setPointerVersion(4L) + .build()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " 00000000-0000-4000-8000-000000000042", + "00000000-0000-4000-8000-000000000042 " + }) + void directTextMethodsRejectNonCanonicalAccountBeforeDispatch(String accountId) throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var client = newClient(stub); + var context = directTextContext().toBuilder().setAccountId(accountId).build(); + + assertThat(client.issueDirectTextConnectScope(context, directTextTarget()).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(join(client, context).getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + org.mockito.Mockito.verifyNoInteractions(stub); + } + + @Test + void directTextMethodsRejectMissingAndMalformedCallerFieldsBeforeDispatch() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var client = newClient(stub); + var context = directTextContext(); + for (var malformed : + List.of( + context.toBuilder().clearAccountId().build(), + context.toBuilder().clearSessionId().build(), + context.toBuilder().setSessionId(" ").build(), + context.toBuilder().setSessionId("s".repeat(129)).build(), + context.toBuilder().clearRequestId().build(), + context.toBuilder().setRequestId(" ").build(), + context.toBuilder().setRequestId("r".repeat(129)).build(), + context.toBuilder().setTenantId("0").build(), + context.toBuilder().setTenantId("tenant-name").build(), + context.toBuilder().setTenantId(" 22").build(), + context.toBuilder().setGameInstanceId("-1").build(), + context.toBuilder().setGameInstanceId("runtime-name").build(), + context.toBuilder().setGameInstanceId("9223372036854775808").build(), + context.toBuilder().clearRealmId().build(), + context.toBuilder().setRealmId("realm-name").build(), + context.toBuilder().setPlayableStateNamespaceId("namespace-name").build(), + context.toBuilder().clearPlayableStateNamespaceId().build(), + context.toBuilder().clearPlayableStateScope().build(), + context.toBuilder().setPlayableStateScope("shared").build(), + context.toBuilder().setPlayableStateScope("SHARED ").build())) { + assertThat( + client + .issueDirectTextConnectScope(malformed, directTextTarget()) + .getError() + .getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat( + client + .joinPublicProductionMembership( + malformed, + "account-issued-scope", + malformed.getRequestId(), + JOIN_TEST_NOW.plusSeconds(60)) + .getError() + .getCode()) + .isEqualTo("INVALID_ARGUMENT"); + } + assertThat(client.issueDirectTextConnectScope(null, directTextTarget()).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(client.issueDirectTextConnectScope(context, null).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(join(client, null).getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + org.mockito.Mockito.verifyNoInteractions(stub); + } + + @Test + void scopeIssuanceRejectsEachIndependentContextTargetMismatch() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var client = newClient(stub); + var context = directTextContext(); + for (var mismatched : + List.of( + context.toBuilder().setTenantId("23").build(), + context.toBuilder().setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce902").build(), + context.toBuilder() + .setPlayableStateNamespaceId("42d234a2-7487-4dda-a7e5-a3831214328f") + .build(), + context.toBuilder().setPlayableStateScope("ISOLATED").build(), + context.toBuilder().setGameInstanceId("10").build())) { + assertThat( + client + .issueDirectTextConnectScope(mismatched, directTextTarget()) + .getError() + .getCode()) + .isEqualTo("INVALID_ARGUMENT"); + } + org.mockito.Mockito.verifyNoInteractions(stub); + } + + @Test + void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { + var target = directTextTarget(); + String[][] malformed = { + {"0", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "9"}, + { + "tenant", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "9" + }, + {"22", " ", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "9"}, + { + "22", + "w".repeat(129), + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "9" + }, + { + "22", + "world", + "r".repeat(129), + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "9" + }, + {"22", "world", "realm", "realm", target.playableStateNamespaceId(), "SHARED", "9"}, + {"22", "world", "realm", target.realmId(), "namespace", "SHARED", "9"}, + {"22", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "shared", "9"}, + {"22", "world", "realm", target.realmId(), target.playableStateNamespaceId(), "SHARED", "0"} + }; + for (var fields : malformed) { + assertThatThrownBy( + () -> + new DirectTextConnectScopeTarget( + fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], + 7L, 4L)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + new DirectTextConnectScopeTarget( + "22", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "9", + 0L, + 4L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new DirectTextConnectScopeTarget( + "22", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "9", + 7L, + -1L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void joinRejectsMissingOversizedOrMismatchedRetainedIdentity() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var client = newClient(stub); + for (String scope : new String[] {null, "", " ", "s".repeat(2049)}) { + assertThat( + client + .joinPublicProductionMembership( + directTextContext(), scope, "join-request-1", JOIN_TEST_NOW.plusSeconds(60)) + .getError() + .getCode()) + .isEqualTo("INVALID_ARGUMENT"); + } + for (String request : new String[] {null, "", " ", "r".repeat(129), "different-request"}) { + assertThat( + client + .joinPublicProductionMembership( + directTextContext(), "scope", request, JOIN_TEST_NOW.plusSeconds(60)) + .getError() + .getCode()) + .isEqualTo("INVALID_ARGUMENT"); + } + org.mockito.Mockito.verifyNoInteractions(stub); + } + + @Test + void directTextMethodsReturnUnavailableForMissingStub() throws Exception { + var client = newRetryFixture(new TestClock(JOIN_TEST_NOW)).client(); + setStub(client, null); + assertThat( + client + .issueDirectTextConnectScope(directTextContext(), directTextTarget()) + .getError() + .getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + assertThat(join(client, directTextContext()).getError().getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + } + + @ParameterizedTest + @EnumSource(value = Status.Code.class, mode = EnumSource.Mode.EXCLUDE, names = "OK") + void scopeIssuanceNeverRetriesTransportFailureAndSanitizesErrors(Status.Code status) + throws Exception { + var fixture = newRetryFixture(); + when(fixture.initialStub().issueDirectTextConnectScope(any())) + .thenThrow( + Status.fromCode(status) + .withDescription("private upstream details") + .asRuntimeException()); + + var response = + fixture.client().issueDirectTextConnectScope(directTextContext(), directTextTarget()); + + assertThat(response.getError().getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(response.getError().getMessage()).isEqualTo("Account authority unavailable"); + verify(fixture.initialStub()).issueDirectTextConnectScope(any()); + verify(fixture.retryStub(), never()).issueDirectTextConnectScope(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void scopeIssuancePreservesCompletedApplicationFailure() throws Exception { + var fixture = newRetryFixture(); + var expected = + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("CONNECT_SCOPE_MISMATCH") + .setMessage("Refresh REALMS")) + .build(); + when(fixture.initialStub().issueDirectTextConnectScope(any())).thenReturn(expected); + assertThat( + fixture.client().issueDirectTextConnectScope(directTextContext(), directTextTarget())) + .isSameAs(expected); + verify(fixture.initialStub()).issueDirectTextConnectScope(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @ParameterizedTest + @ValueSource(strings = {"JOINED", "ALREADY_ACTIVE"}) + void joinPreservesProducerSuccessAndReplayEvidence(String outcome) throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var expected = joinSuccess(outcome, "ALREADY_ACTIVE".equals(outcome)); + when(fixture.initialStub().joinPublicProductionMembership(any())).thenReturn(expected); + + assertThat(join(fixture.client(), directTextContext())).isSameAs(expected); + + var captor = ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + verify(fixture.initialStub()).joinPublicProductionMembership(captor.capture()); + assertThat(captor.getValue()) + .isEqualTo( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(directTextContext()) + .setConnectScopeId("account-issued-scope") + .setRequestId("join-request-1") + .build()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinPreservesTypedNonSuccessWithOrWithoutErrorWithoutRetry() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var normal = + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(false) + .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setAccountId(ACCOUNT_UUID) + .setTenantId("22") + .setMembershipId("0") + .build(); + for (var expected : + List.of( + normal, + normal.toBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setMessage("Joining is disabled")) + .build())) { + when(fixture.initialStub().joinPublicProductionMembership(any())).thenReturn(expected); + assertThat(join(fixture.client(), directTextContext())).isSameAs(expected); + } + verify(fixture.initialStub(), times(2)).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinAcceptsBoundedOpaqueIdentityWithoutTrimmingOrRegeneration() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var requestId = " " + "r".repeat(126) + " "; + var scopeId = " " + "s".repeat(2046) + " "; + var context = + directTextContext().toBuilder() + .setSessionId("s".repeat(128)) + .setRequestId(requestId) + .build(); + var expected = joinSuccess("JOINED", false); + when(fixture.initialStub().joinPublicProductionMembership(any())).thenReturn(expected); + + assertThat( + fixture + .client() + .joinPublicProductionMembership( + context, scopeId, requestId, JOIN_TEST_NOW.plusSeconds(60))) + .isSameAs(expected); + + var captor = ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + verify(fixture.initialStub()).joinPublicProductionMembership(captor.capture()); + assertThat(captor.getValue()) + .isEqualTo( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(context) + .setConnectScopeId(scopeId) + .setRequestId(requestId) + .build()); + } + + @Test + void joinRejectsForeignOrMalformedSuccessfulIdentityWithoutRetry() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var success = joinSuccess("JOINED", false); + for (String account : + List.of( + "", + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + ACCOUNT_UUID, + "00000000-0000-4000-8000-000000000043")) { + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenReturn(success.toBuilder().setAccountId(account).build()); + assertThat(join(fixture.client(), directTextContext()).getError().getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + } + for (String tenant : List.of("", "tenant", "0", "23", " 22", "022")) { + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenReturn(success.toBuilder().setTenantId(tenant).build()); + assertThat(join(fixture.client(), directTextContext()).getError().getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + } + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @ParameterizedTest + @ValueSource(strings = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void joinRetriesOnceWithSameImmutableRequestAfterChannelRebuild(String status) throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenThrow(Status.fromCode(Status.Code.valueOf(status)).asRuntimeException()); + var expected = joinSuccess("JOINED", true); + when(fixture.retryStub().joinPublicProductionMembership(any())).thenReturn(expected); + + assertThat(join(fixture.client(), directTextContext())).isSameAs(expected); + + var first = ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + var retry = ArgumentCaptor.forClass(JoinPublicProductionMembershipRequest.class); + verify(fixture.initialStub()).joinPublicProductionMembership(first.capture()); + verify(fixture.retryStub()).joinPublicProductionMembership(retry.capture()); + assertThat(retry.getValue()).isSameAs(first.getValue()); + assertThat(retry.getValue()) + .isEqualTo( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(directTextContext()) + .setConnectScopeId("account-issued-scope") + .setRequestId("join-request-1") + .build()); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @ParameterizedTest + @ValueSource(strings = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void joinExhaustedRetryRemainsUnavailableAndNeverCallsThirdTime(String status) throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + var failure = + Status.fromCode(Status.Code.valueOf(status)) + .withDescription("private details") + .asRuntimeException(); + when(fixture.initialStub().joinPublicProductionMembership(any())).thenThrow(failure); + when(fixture.retryStub().joinPublicProductionMembership(any())).thenThrow(failure); + + var response = join(fixture.client(), directTextContext()); + + assertThat(response.getOutcomeCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(response.getError().getMessage()).isEqualTo("Account authority unavailable"); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinChannelReloadFailureRemainsUnavailableWithoutRedispatch() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(fixture.channelFactory().buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenThrow(new IllegalStateException("private reload details")); + + assertThat(join(fixture.client(), directTextContext()).getError().getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinAlsoCorrelatesSuccessfulRetryBeforeReturningIt() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(fixture.retryStub().joinPublicProductionMembership(any())) + .thenReturn(joinSuccess("JOINED", true).toBuilder().setTenantId("23").build()); + + assertThat(join(fixture.client(), directTextContext()).getError().getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void directTextGenericFailuresAreUnavailableWithoutRetryOrUpstreamMessages() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + when(fixture.initialStub().issueDirectTextConnectScope(any())) + .thenThrow(new IllegalStateException("private scope detail")); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenThrow(new IllegalStateException("private join detail")); + + assertThat( + fixture + .client() + .issueDirectTextConnectScope(directTextContext(), directTextTarget()) + .getError() + .getMessage()) + .isEqualTo("Account authority unavailable"); + assertThat(join(fixture.client(), directTextContext()).getError().getMessage()) + .isEqualTo("Account authority unavailable"); + verify(fixture.initialStub()).issueDirectTextConnectScope(any()); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).issueDirectTextConnectScope(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @ParameterizedTest + @EnumSource( + value = Status.Code.class, + mode = EnumSource.Mode.EXCLUDE, + names = {"OK", "UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void joinOtherTransportFailuresAreSanitizedCommandFailuresWithoutRetry(Status.Code status) + throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenThrow( + Status.fromCode(status) + .withDescription("private account details") + .asRuntimeException()); + + var response = join(fixture.client(), directTextContext()); + + assertThat(response.getOutcomeCode()).isEqualTo("JOIN_FAILED"); + assertThat(response.getError().getCode()).isEqualTo("JOIN_FAILED"); + assertThat(response.getError().getMessage()).isEqualTo("Account JOIN request failed"); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinRejectsNullPastOrEqualExpiryBeforeFirstDispatch() throws Exception { + var fixture = newRetryFixture(new TestClock(JOIN_TEST_NOW)); + for (Instant expiry : new Instant[] {null, JOIN_TEST_NOW.minusNanos(1), JOIN_TEST_NOW}) { + assertThat( + fixture + .client() + .joinPublicProductionMembership( + directTextContext(), "account-issued-scope", "join-request-1", expiry) + .getError() + .getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + } + verify(fixture.initialStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinRechecksExpiryAfterInitialStubPreparationBeforeFirstDispatch() throws Exception { + var clock = new TestClock(JOIN_TEST_NOW); + var fixture = newRetryFixture(clock); + when(fixture.initialStub().withDeadlineAfter(5L, TimeUnit.SECONDS)) + .thenAnswer( + invocation -> { + clock.set(JOIN_TEST_NOW.plusSeconds(60)); + return fixture.initialStub(); + }); + + assertThat(join(fixture.client(), directTextContext()).getError().getCode()) + .isEqualTo("CONNECT_SCOPE_INVALID"); + verify(fixture.initialStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @ParameterizedTest + @ValueSource(strings = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void joinExpiryAfterAmbiguityIsUnavailableNotNoCommitEvidence(String status) throws Exception { + var clock = new TestClock(JOIN_TEST_NOW); + var fixture = newRetryFixture(clock); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenAnswer( + invocation -> { + clock.set(JOIN_TEST_NOW.plusSeconds(60)); + throw Status.fromCode(Status.Code.valueOf(status)).asRuntimeException(); + }); + + assertThat(join(fixture.client(), directTextContext()).getError().getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory(), never()) + .buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + @Test + void joinRechecksExpiryDuringChannelReloadBeforeRetry() throws Exception { + var clock = new TestClock(JOIN_TEST_NOW); + var fixture = newRetryFixture(clock); + when(fixture.initialStub().joinPublicProductionMembership(any())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(fixture.channelFactory().buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenAnswer( + invocation -> { + clock.set(JOIN_TEST_NOW.plusSeconds(60)); + return mock(ManagedChannel.class); + }); + + assertThat(join(fixture.client(), directTextContext()).getError().getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + verify(fixture.initialStub()).joinPublicProductionMembership(any()); + verify(fixture.retryStub(), never()).joinPublicProductionMembership(any()); + verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); + } + + private static DirectTextConnectScopeTarget directTextTarget() { + return new DirectTextConnectScopeTarget( + "22", + "demo-world", + "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "42d234a2-7487-4dda-a7e5-a3831214328e", + "SHARED", + "9", + 7L, + 4L); + } + + private static PlayerExecutionContext directTextContext() { + var target = directTextTarget(); + return PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setSessionId("transport-session") + .setTenantId(target.tenantId()) + .setRealmId(target.realmId()) + .setPlayableStateNamespaceId(target.playableStateNamespaceId()) + .setPlayableStateScope(target.playableStateScope()) + .setGameInstanceId(target.gameInstanceId()) + .setRequestId("join-request-1") + .build(); + } + + private static JoinPublicProductionMembershipResponse joinSuccess( + String outcome, boolean replayed) { + return JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode(outcome) + .setAccountId(ACCOUNT_UUID) + .setTenantId("22") + .setMembershipId("81") + .setMembershipVersion(12L) + .setMembershipAuthorityGeneration(3L) + .setReplayed(replayed) + .build(); + } + + private static JoinPublicProductionMembershipResponse join( + AccountClient client, PlayerExecutionContext context) { + return client.joinPublicProductionMembership( + context, "account-issued-scope", "join-request-1", JOIN_TEST_NOW.plusSeconds(60)); + } @Test void authenticateReturnsUnavailableWhenStubIsNotInitialized() throws Exception { @@ -532,7 +1196,8 @@ private static AccountClient newClient( new ServiceEndpointsProperties(), new CommonGrpcClientProperties(), channelFactory, - BlockingGrpcStubCustomizer.noop()); + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(JOIN_TEST_NOW, ZoneOffset.UTC)); setStub(client, stub); return client; } @@ -540,7 +1205,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 +1216,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 +1238,34 @@ 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 Instant current; + + private TestClock(Instant current) { + this.current = current; + } + + private void set(Instant current) { + this.current = current; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return Clock.fixed(current, zone); + } + + @Override + public Instant instant() { + return current; + } } private record RetryFixture( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java new file mode 100644 index 0000000000..23eb9a459e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class DirectTextIssuedConnectScopeTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000042"; + private static final String EVALUATED_AT = "2026-08-02T00:00:00.120Z"; + private static final String EXPIRES_AT = "2026-08-02T00:02:00Z"; + private static final Instant NOW = Instant.parse("2026-08-02T00:01:00Z"); + + @Test + void retainsExactResolvedTargetAndAccountOwnedWireTimes() { + var target = target(); + var response = + response("opaque/account-scope:without-uuid-assumptions", EVALUATED_AT, EXPIRES_AT); + + var scope = + DirectTextIssuedConnectScope.fromAccountResponse(ACCOUNT_ID, target, response, clock(NOW)); + + assertThat(scope.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(scope.target()).isSameAs(target); + assertThat(scope.connectScopeId()).isEqualTo("opaque/account-scope:without-uuid-assumptions"); + assertThat(scope.evaluatedAt()).isEqualTo(EVALUATED_AT); + assertThat(scope.evaluatedAtInstant()).isEqualTo(Instant.parse(EVALUATED_AT)); + assertThat(scope.connectScopeExpiresAt()).isEqualTo(EXPIRES_AT); + assertThat(scope.connectScopeExpiresAtInstant()).isEqualTo(Instant.parse(EXPIRES_AT)); + } + + @Test + void enforcesExpiryAtTheExactAccountExpiryBoundary() { + var scope = + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT_ID, target(), response("scope", EVALUATED_AT, EXPIRES_AT), clock(NOW)); + + assertThat(scope.isLive(clock(Instant.parse("2026-08-02T00:01:59.999999999Z")))).isTrue(); + assertThat(scope.isLive(clock(Instant.parse(EXPIRES_AT)))).isFalse(); + assertThatThrownBy( + () -> + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT_ID, + target(), + response("scope", EVALUATED_AT, EXPIRES_AT), + clock(Instant.parse(EXPIRES_AT)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsAccountErrorsAndMalformedOrContradictoryEvidence() { + var valid = response("scope", EVALUATED_AT, EXPIRES_AT); + var error = + valid.toBuilder().setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE")).build(); + + assertRejected(error, ACCOUNT_ID, target(), clock(NOW)); + assertRejected( + valid.toBuilder().clearConnectScopeId().build(), ACCOUNT_ID, target(), clock(NOW)); + assertRejected(valid.toBuilder().clearEvaluatedAt().build(), ACCOUNT_ID, target(), clock(NOW)); + assertRejected( + valid.toBuilder().setEvaluatedAt("2026-08-02T00:00:00+00:00").build(), + ACCOUNT_ID, + target(), + clock(NOW)); + assertRejected( + valid.toBuilder().setConnectScopeExpiresAt("not-a-timestamp").build(), + ACCOUNT_ID, + target(), + clock(NOW)); + assertRejected( + response("scope", "2026-08-02T00:03:00Z", EXPIRES_AT), ACCOUNT_ID, target(), clock(NOW)); + assertRejected( + response("scope", EVALUATED_AT, "2026-08-02T00:00:00Z"), ACCOUNT_ID, target(), clock(NOW)); + } + + @Test + void requiresCanonicalNonNilCallerAccountUuid() { + for (String malformed : + new String[] { + "42", + "00000000-0000-4000-8000-00000000004A", + "00000000-0000-0000-0000-000000000000", + " " + ACCOUNT_ID + }) { + assertRejected(response("scope", EVALUATED_AT, EXPIRES_AT), malformed, target(), clock(NOW)); + } + } + + @Test + void boundsOpaqueScopeWithoutChangingItsBytes() { + String maximumScope = "s".repeat(2048); + var retained = + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT_ID, target(), response(maximumScope, EVALUATED_AT, EXPIRES_AT), clock(NOW)); + assertThat(retained.connectScopeId()).isEqualTo(maximumScope); + assertRejected( + response(maximumScope + "s", EVALUATED_AT, EXPIRES_AT), ACCOUNT_ID, target(), clock(NOW)); + } + + @Test + void retainsAccountEvaluationWithoutInventingLocalFreshnessPolicy() { + String accountEvaluation = "2026-08-02T00:01:30Z"; + var retained = + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT_ID, target(), response("scope", accountEvaluation, EXPIRES_AT), clock(NOW)); + assertThat(retained.evaluatedAt()).isEqualTo(accountEvaluation); + assertThat(retained.isLive(clock(NOW))).isTrue(); + } + + @Test + void retainsOriginalResponseValuesAfterBuilderReuse() { + var responseBuilder = response("opaque-scope", EVALUATED_AT, EXPIRES_AT).toBuilder(); + var scope = + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT_ID, target(), responseBuilder.build(), clock(NOW)); + responseBuilder.setConnectScopeId("replacement").setEvaluatedAt("2026-08-02T00:00:01Z"); + + assertThat(scope.connectScopeId()).isEqualTo("opaque-scope"); + assertThat(scope.evaluatedAt()).isEqualTo(EVALUATED_AT); + assertThat(scope.evaluatedAtInstant()).isEqualTo(Instant.parse(EVALUATED_AT)); + } + + private static void assertRejected( + IssueDirectTextConnectScopeResponse response, + String accountId, + DirectTextConnectScopeTarget target, + Clock clock) { + assertThatThrownBy( + () -> + DirectTextIssuedConnectScope.fromAccountResponse( + accountId, target, response, clock)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IssueDirectTextConnectScopeResponse response( + String scopeId, String evaluatedAt, String expiresAt) { + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scopeId) + .setEvaluatedAt(evaluatedAt) + .setConnectScopeExpiresAt(expiresAt) + .build(); + } + + private static DirectTextConnectScopeTarget target() { + return new DirectTextConnectScopeTarget( + "22", + "demo-world", + "production", + "00000000-0000-4000-8000-000000000101", + "00000000-0000-4000-8000-000000000102", + "SHARED", + "9", + 7L, + 4L); + } + + private static Clock clock(Instant instant) { + return Clock.fixed(instant, ZoneOffset.UTC); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActivityTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActivityTextCommandDispatchHandlerTest.java index 515dcdee63..8b8140344c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActivityTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActivityTextCommandDispatchHandlerTest.java @@ -27,6 +27,7 @@ void enqueuesBuiltInActivityCommand() { "session-1", new TextCommand(TextCommandType.AFK, List.of("ON"), "AFK ON"), false, + Optional.empty(), Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); @@ -50,6 +51,7 @@ void enqueuesAuthoredActivityCommandWithoutTypeSpecificGate() { "MEDITATE", new TextCommandPayload.AuthoredActionInvocation("meditate", List.of())), true, + Optional.empty(), Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java index cf6a3a5a6c..8f6ffef769 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java @@ -45,7 +45,8 @@ void enqueuesGameplayScopedAuthoredActionWithItsAdmittedSnapshot() { "session-1", authoredAction("wave-salute", "salute captain", List.of("captain")), false, - Optional.of(context))); + Optional.of(context), + Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); verify(commandService).enqueue("session-1", "salute captain", false, admission); @@ -63,7 +64,8 @@ void rejectsGameplayScopedAuthoredActionWithoutAnAdmittedSnapshot() { "session-1", authoredAction("wave-salute", "salute captain", List.of("captain")), false, - Optional.of(context))); + Optional.of(context), + Optional.empty())); assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) @@ -79,6 +81,7 @@ void rejectsAuthoredActionsWithoutGameplayContext() { "session-1", authoredAction("wave-salute", "salute captain", List.of("captain")), false, + Optional.empty(), Optional.empty())); assertThat(result.commandResult().accepted()).isFalse(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java new file mode 100644 index 0000000000..987d2e10e5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java @@ -0,0 +1,612 @@ +package unit.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.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.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisCommandExecutionException; +import io.lettuce.core.RedisCommandTimeoutException; +import io.lettuce.core.RedisConnectionException; +import io.lettuce.core.RedisNoScriptException; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldMenuRedisScriptContribution; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldMenuRedisStore; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService.ReadUnavailableException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Controlled public source/physical-connection doubles; no genuine ingress is established. */ +class DirectTextWorldMenuRedisStoreTest { + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-11-01T12:00:00Z"), ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final ObservedDirectTextTransport transport = + new ObservedDirectTextTransport( + "101", UUID.fromString("aaaaaaaa-1111-4111-8111-111111111111")); + private final CanonicalPlayerRouteReadService routes = + mock(CanonicalPlayerRouteReadService.class); + private final AtomicInteger catalogReads = new AtomicInteger(); + private final DirectTextWorldSelectionService selection = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldSupplier( + () -> { + catalogReads.incrementAndGet(); + return List.of(); + }), + routes, + CLOCK); + private final StatefulRedisConnection connection = mockConnection(); + private final RedisCommands commands = mockCommands(); + private final AtomicReference stored = new AtomicReference<>(); + private final AtomicReference outcome = new AtomicReference<>("MENU_WRITTEN"); + private DirectTextWorldMenuRedisStore store; + private byte[] source; + private String sha1; + + @BeforeEach + void prepare() throws Exception { + try (var input = + DirectTextWorldMenuRedisStore.class + .getClassLoader() + .getResourceAsStream(DirectTextWorldMenuRedisScriptContribution.RESOURCE_PATH)) { + source = java.util.Objects.requireNonNull(input).readAllBytes(); + } + sha1 = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(source)); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of()); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn("gamesession_coord_app"); + when(commands.getrange(any(byte[].class), eq(0L), eq(2097152L))) + .thenAnswer(invocation -> stored.get() == null ? new byte[0] : stored.get()); + when(commands.exists(any(byte[].class))) + .thenAnswer(invocation -> stored.get() == null ? 0L : 1L); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-1") + .digest(invocation.getArgument(0, byte[].class)))); + when(commands.evalsha( + anyString(), + eq(ScriptOutputType.STATUS), + any(byte[][].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class))) + .thenAnswer( + invocation -> { + assertThat( + new String( + invocation.getArgument(7, byte[].class), StandardCharsets.US_ASCII)) + .isEqualTo(Long.toString(CLOCK.millis())); + boolean clear = + "CLEAR" + .equals( + new String( + invocation.getArgument(3, byte[].class), StandardCharsets.US_ASCII)); + assertThat( + new String( + invocation.getArgument(6, byte[].class), StandardCharsets.US_ASCII)) + .isEqualTo(clear ? "0" : Long.toString(CLOCK.millis() + 300_000L)); + byte[] expected = invocation.getArgument(4, byte[].class); + if (!Arrays.equals(expected, stored.get() == null ? new byte[0] : stored.get())) { + return "PREIMAGE_MISMATCH"; + } + if ("MENU_WRITTEN".equals(outcome.get())) { + stored.set(invocation.getArgument(5, byte[].class)); + } + return outcome.get(); + }); + store = new DirectTextWorldMenuRedisStore(selection, CLOCK, () -> connection, installed()); + } + + @Test + void clearUsesZeroExpiryAndTheSameBoundedClockArgument() { + outcome.set("MENU_UNCHANGED"); + assertThat(store.clear(transport)).isTrue(); + } + + @Test + void freshDiscoveryComposesOnceButFindAndRetainedReassertEachRestoreFreshSources() { + var menu = store.discoverAndReplace(transport).orElseThrow(); + assertThat(catalogReads.get()).isEqualTo(2); + verify(routes).readVisiblePublicProductionTargets(); + byte[] original = stored.get(); + + clearInvocations(routes); + catalogReads.set(0); + var restored = store.find(transport).orElseThrow(); + assertThat(catalogReads.get()).isEqualTo(2); + verify(routes).readVisiblePublicProductionTargets(); + assertThat(restored.expiresAt()).isEqualTo(menu.expiresAt()); + + for (var retained : List.of(menu, restored)) { + clearInvocations(routes); + catalogReads.set(0); + outcome.set("MENU_UNCHANGED"); + assertThat(store.reassert(transport, retained)).isTrue(); + assertThat(catalogReads.get()).isEqualTo(2); + verify(routes).readVisiblePublicProductionTargets(); + assertThat(stored.get()).isEqualTo(original); + } + } + + @ParameterizedTest + @ValueSource(longs = {-1L, 300L}) + void freshDiscoveryStillRejectsFutureOrExpiredLifetimeBeforeRedis(long clockOffsetSeconds) { + var bounded = + new DirectTextWorldMenuRedisStore( + selection, + Clock.offset(CLOCK, java.time.Duration.ofSeconds(clockOffsetSeconds)), + () -> connection, + installed()); + assertThat(bounded.discoverAndReplace(transport)).isEmpty(); + assertThat(catalogReads.get()).isEqualTo(2); + verify(routes).readVisiblePublicProductionTargets(); + verifyNoInteractions(commands, connection); + } + + @Test + void expiredRetainedHandleCannotUseTheFreshDiscoveryPath() { + var clock = mock(Clock.class); + when(clock.instant()).thenReturn(CLOCK.instant()); + when(clock.millis()).thenReturn(CLOCK.millis()); + var localSelection = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldViews(List.of()), routes, clock); + var localStore = + new DirectTextWorldMenuRedisStore(localSelection, clock, () -> connection, installed()); + var menu = localStore.discoverAndReplace(transport).orElseThrow(); + byte[] original = stored.get(); + when(clock.instant()).thenReturn(menu.expiresAt()); + when(clock.millis()).thenReturn(menu.expiresAt().toEpochMilli()); + clearInvocations(commands, connection, routes); + + assertThat(localStore.reassert(transport, menu)).isFalse(); + assertThat(localSelection.resolve(menu, "1")).isEmpty(); + assertThat(stored.get()).isEqualTo(original); + verifyNoInteractions(commands, connection, routes); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void selectionOwnerClockMovementRejectsFreshHandleEvenWhenStoreClockRemainsLive(boolean expired) { + var clock = mock(Clock.class); + var createdAt = CLOCK.instant(); + // browse sees a live original for both of its own clock reads. The selection owner's next + // read sees expiry or sub-millisecond rollback, while the independent store clock stays live. + when(clock.instant()) + .thenReturn( + createdAt, createdAt, expired ? createdAt.plusSeconds(300) : createdAt.minusNanos(1)); + var localSelection = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldViews(List.of()), routes, clock); + var localStore = + new DirectTextWorldMenuRedisStore(localSelection, CLOCK, () -> connection, installed()); + + assertThat(localStore.discoverAndReplace(transport)).isEmpty(); + verify(routes).readVisiblePublicProductionTargets(); + verifyNoInteractions(commands, connection); + } + + @Test + void verifiedSourceIsResolvedOnceAtConstructionAndWarmOperationsNeverLoad() { + var catalog = mock(RedisScriptCatalog.class); + String id = DirectTextWorldMenuRedisScriptContribution.SCRIPT_ID; + when(catalog.require(id)).thenReturn(installed().require(id)); + var cached = new DirectTextWorldMenuRedisStore(selection, CLOCK, () -> connection, catalog); + // Later catalog lookups would fail: all operations must use the already verified source. + when(catalog.require(id)).thenThrow(new IllegalStateException("unexpected repeated lookup")); + var menu = cached.discoverAndReplace(transport).orElseThrow(); + assertThat(cached.find(transport)).isPresent(); + outcome.set("MENU_UNCHANGED"); + assertThat(cached.reassert(transport, menu)).isTrue(); + outcome.set("MENU_CLEARED"); + assertThat(cached.clear(transport)).isTrue(); + verify(catalog).require(id); + verify(commands, never()).scriptLoad(any(byte[].class)); + verifyEvaluations(3); + verify(commands, times(4)).aclWhoami(); + } + + @ParameterizedTest + @ValueSource(strings = {"scriptId", "owner", "principal", "resourcePath", "role", "sha256"}) + void mismatchedInstalledDescriptorIsDeniedAtConstructionWithoutRedis(String field) { + var catalog = mock(RedisScriptCatalog.class); + String id = DirectTextWorldMenuRedisScriptContribution.SCRIPT_ID; + ObjectNode changed = (ObjectNode) JSON.valueToTree(installed().require(id)); + changed.put( + field, + switch (field) { + case "scriptId" -> "game-session.wrong-menu.v1"; + case "owner" -> "wrong-service"; + case "principal" -> "wrong_principal"; + case "resourcePath" -> "redis/lua/wrong-menu.lua"; + case "role" -> "CACHE_RATE_LIMIT"; + case "sha256" -> "0".repeat(64); + default -> throw new IllegalArgumentException(field); + }); + when(catalog.require(id)).thenReturn(JSON.treeToValue(changed, RedisScriptDescriptor.class)); + clearInvocations(commands); + assertThatThrownBy( + () -> new DirectTextWorldMenuRedisStore(selection, CLOCK, () -> connection, catalog)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(commands, connection); + } + + @Test + void noScriptLoadsExactVerifiedBytesAndRetriesExactShaOnce() { + var menu = store.discoverAndReplace(transport).orElseThrow(); + byte[] original = stored.get(); + when(evaluation()) + .thenThrow(new RedisNoScriptException("NOSCRIPT controlled loss")) + .thenReturn("MENU_UNCHANGED"); + clearInvocations(commands, connection); + assertThat(store.reassert(transport, menu)).isTrue(); + verify(commands).scriptLoad(eq(source)); + verifyEvaluations(2); + verify(connection).sync(); + verify(connection).close(); + assertThat(stored.get()).isEqualTo(original); + } + + @Test + void loadedDigestMismatchRefusesBeforeSecondEvaluation() { + when(evaluation()).thenThrow(new RedisNoScriptException("NOSCRIPT controlled loss")); + when(commands.scriptLoad(any(byte[].class))).thenReturn("wrong-loaded-hash"); + clearInvocations(commands); + assertThatThrownBy(() -> store.discoverAndReplace(transport)) + .isInstanceOf(IllegalStateException.class); + verify(commands).scriptLoad(eq(source)); + verifyEvaluations(1); + assertThat(stored.get()).isNull(); + } + + @Test + void nullReturnedStatusIsUnavailableWithoutLoadOrRetry() { + when(evaluation()).thenReturn(null); + clearInvocations(commands); + assertThatThrownBy(() -> store.discoverAndReplace(transport)) + .isInstanceOf(IllegalStateException.class); + verify(commands, never()).scriptLoad(any(byte[].class)); + verifyEvaluations(1); + assertThat(stored.get()).isNull(); + } + + @Test + void secondNoScriptEscapesWithoutAnotherLoadOrRetry() { + var second = new RedisNoScriptException("NOSCRIPT second loss"); + when(evaluation()) + .thenThrow(new RedisNoScriptException("NOSCRIPT first loss")) + .thenThrow(second); + clearInvocations(commands); + assertThatThrownBy(() -> store.discoverAndReplace(transport)).isSameAs(second); + verify(commands).scriptLoad(eq(source)); + verifyEvaluations(2); + assertThat(stored.get()).isNull(); + } + + @Test + void arbitraryErrorsAndUnknownWriteFailuresAreNeverLoadedOrRetried() { + for (RuntimeException failure : + List.of( + new RedisCommandExecutionException("NOSCRIPT text is not the typed exception"), + new RedisCommandExecutionException("ERR controlled failure"), + new RedisCommandTimeoutException("controlled timeout"), + new RedisConnectionException("controlled transport loss"))) { + // doAnswer also models a write that completed before its reply became unavailable. + org.mockito.Mockito.doAnswer( + invocation -> { + stored.set(invocation.getArgument(5, byte[].class)); + throw failure; + }) + .when(commands) + .evalsha( + anyString(), + eq(ScriptOutputType.STATUS), + any(byte[][].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class)); + stored.set(null); + clearInvocations(commands); + assertThatThrownBy(() -> store.discoverAndReplace(transport)).isSameAs(failure); + assertThat(stored.get()).isNotEmpty(); + verify(commands, never()).scriptLoad(any(byte[].class)); + verifyEvaluations(1); + } + } + + @Test + void retainsGenuineMenuAndRestoresOnlyToItsExactObservation() { + var menu = store.discoverAndReplace(transport).orElseThrow(); + var restored = store.find(transport).orElseThrow(); + assertThat(restored.expiresAt()).isEqualTo(menu.expiresAt()); + assertThat(selection.encodeSnapshot(restored)) + .hasValueSatisfying( + bytes -> assertThat(bytes).isEqualTo(selection.encodeSnapshot(menu).orElseThrow())); + byte[] original = stored.get(); + outcome.set("MENU_UNCHANGED"); + assertThat(store.reassert(transport, menu)).isTrue(); + assertThat(store.reassert(transport, restored)).isTrue(); + assertThat(stored.get()).isEqualTo(original); + assertThat(new String(stored.get(), StandardCharsets.UTF_8)) + .contains(transport.proxyConnectionId().toString(), "\"transportSessionId\":\"101\"") + .doesNotContain("accountId", "connectScope", "credential", "joinIntent"); + clearInvocations(commands, routes); + var wrong = new ObservedDirectTextTransport("102", transport.proxyConnectionId()); + assertThat(store.find(wrong)).isEmpty(); + assertThat(store.reassert(wrong, menu)).isFalse(); + assertThat(store.discoverAndReplace(wrong)).isEmpty(); + assertThat(store.clear(wrong)).isFalse(); + assertThat(store.find(new ObservedDirectTextTransport("0101", transport.proxyConnectionId()))) + .isEmpty(); + verify(commands, never()).scriptLoad(any(byte[].class)); + } + + @Test + void malformedOrUnboundedNumericCorrelationCannotReachRedis() { + var menu = selection.browse().orElseThrow(); + clearInvocations(commands, routes); + var signed = new ObservedDirectTextTransport("+101", transport.proxyConnectionId()); + var oversized = + new ObservedDirectTextTransport("0".repeat(100) + "101", transport.proxyConnectionId()); + assertThatThrownBy(() -> store.reassert(signed, menu)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> store.discoverAndReplace(signed)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> store.find(oversized)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> store.clear(signed)).isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(commands, routes); + } + + @ParameterizedTest + @ValueSource( + strings = { + "schema", + "unknown", + "duplicate", + "trailing", + "coerced", + "missing", + "uuid", + "base64", + "oversize" + }) + void rejectsMalformedOuterStateWithoutSourceReadsOrMutation(String change) { + assertThat(store.discoverAndReplace(transport)).isPresent(); + byte[] original = stored.get(); + ObjectNode tree = (ObjectNode) JSON.readTree(original); + switch (change) { + case "schema" -> tree.put("schemaVersion", "direct-text-world-menu/v2"); + case "unknown" -> tree.put("authority", true); + case "coerced" -> tree.put("transportSessionId", 101); + case "missing" -> tree.remove("transportSessionId"); + case "uuid" -> + tree.put( + "originalProxyConnectionUuid", + transport.proxyConnectionId().toString().toUpperCase(java.util.Locale.ROOT)); + case "base64" -> tree.put("encodedOriginalMenu", "!"); + default -> {} + } + byte[] changed = JSON.writeValueAsBytes(tree); + if ("duplicate".equals(change)) { + changed = + (new String(original, StandardCharsets.UTF_8) + .replaceFirst("\\{", "{\"transportSessionId\":\"101\",")) + .getBytes(StandardCharsets.UTF_8); + } else if ("trailing".equals(change)) { + changed = + (new String(original, StandardCharsets.UTF_8) + "{}").getBytes(StandardCharsets.UTF_8); + } else if ("oversize".equals(change)) { + changed = new byte[2097153]; + } + stored.set(changed); + var genuine = selection.browse().orElseThrow(); + clearInvocations(commands, routes); + assertThat(store.find(transport)).isEmpty(); + verifyNoInteractions(routes); + assertThat(store.clear(transport)).isFalse(); + assertThat(store.reassert(transport, genuine)).isFalse(); + assertThat(store.discoverAndReplace(transport)).isEmpty(); + verify(commands, never()).scriptLoad(any(byte[].class)); + assertThat(stored.get()).isEqualTo(changed); + } + + @Test + void missingAndInvalidInnerStateAreNotReconstructedAndSourceFailureEscapes() { + assertThat(store.find(transport)).isEmpty(); + verifyNoInteractions(routes); + var menu = store.discoverAndReplace(transport).orElseThrow(); + var unavailable = new ReadUnavailableException("controlled unavailable source"); + when(routes.readVisiblePublicProductionTargets()).thenThrow(unavailable); + assertThatThrownBy(() -> store.find(transport)).isSameAs(unavailable); + assertThatThrownBy(() -> store.reassert(transport, menu)).isSameAs(unavailable); + assertThatThrownBy(() -> store.discoverAndReplace(transport)).isSameAs(unavailable); + ObjectNode tree = (ObjectNode) JSON.readTree(stored.get()); + tree.put("encodedOriginalMenu", "e30="); + stored.set(JSON.writeValueAsBytes(tree)); + clearInvocations(routes); + assertThat(store.find(transport)).isEmpty(); + verifyNoInteractions(routes); + } + + @Test + void foreignHandlesCannotBeWrittenAndNoRawPayloadApiExists() { + var other = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldViews(List.of()), routes, CLOCK); + var foreign = other.browse().orElseThrow(); + clearInvocations(commands, routes); + assertThat(store.reassert(transport, foreign)).isFalse(); + assertThat(store.reassert(transport, null)).isFalse(); + verifyNoInteractions(commands, routes); + } + + @ParameterizedTest + @ValueSource(strings = {"PREIMAGE_MISMATCH", "EXPIRED_MENU", "INVALID_ARGS", "UNKNOWN"}) + void refusalsAndUnknownOutcomesNeverReportSuccessfulWrite(String result) { + var menu = store.discoverAndReplace(transport).orElseThrow(); + byte[] original = stored.get(); + outcome.set(result); + if ("PREIMAGE_MISMATCH".equals(result) || "EXPIRED_MENU".equals(result)) { + assertThat(store.reassert(transport, menu)).isFalse(); + } else { + assertThatThrownBy(() -> store.reassert(transport, menu)) + .isInstanceOf(IllegalStateException.class); + } + assertThat(stored.get()).isEqualTo(original); + stored.set(null); + if ("PREIMAGE_MISMATCH".equals(result) || "EXPIRED_MENU".equals(result)) { + assertThat(store.discoverAndReplace(transport)).isEmpty(); + } else { + assertThatThrownBy(() -> store.discoverAndReplace(transport)) + .isInstanceOf(IllegalStateException.class); + } + assertThat(stored.get()).isNull(); + } + + @Test + void redisFailuresEscapeWithoutFallbackOrFakeSuccess() { + var menu = selection.browse().orElseThrow(); + var failure = new IllegalStateException("controlled transport failure"); + when(commands.getrange(any(byte[].class), anyLong(), anyLong())).thenThrow(failure); + assertThatThrownBy(() -> store.find(transport)).isSameAs(failure); + assertThatThrownBy(() -> store.reassert(transport, menu)).isSameAs(failure); + assertThatThrownBy(() -> store.discoverAndReplace(transport)).isSameAs(failure); + assertThatThrownBy(() -> store.clear(transport)).isSameAs(failure); + verify(commands, never()).scriptLoad(any(byte[].class)); + } + + @Test + void principalAndReconnectMismatchDenyBeforeEval() { + when(commands.aclWhoami()).thenReturn("default"); + assertThatThrownBy(() -> store.discoverAndReplace(transport)) + .isInstanceOf(IllegalStateException.class); + when(commands.aclWhoami()).thenReturn("gamesession_coord_app"); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + assertThatThrownBy(() -> store.find(transport)).isInstanceOf(IllegalStateException.class); + verify(commands, never()) + .evalsha( + anyString(), eq(ScriptOutputType.STATUS), any(byte[][].class), any(byte[][].class)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void lostOriginalOrFindRestoredMenuCannotBeReassertedButExplicitDiscoveryRerunsSources( + boolean restoredHandle) { + var original = store.discoverAndReplace(transport).orElseThrow(); + var retained = restoredHandle ? store.find(transport).orElseThrow() : original; + stored.set(null); // Controlled DEL/reset of an unexpired original menu. + clearInvocations(commands, routes); + + assertThat(store.reassert(transport, retained)).isFalse(); + assertThat(stored.get()).isNull(); + verify(commands, never()).scriptLoad(any(byte[].class)); + + clearInvocations(routes); + var fresh = store.discoverAndReplace(transport).orElseThrow(); + assertThat(fresh).isNotSameAs(retained); + // One new guarded browse, not local reconstruction or a redundant second composition. + verify(routes).readVisiblePublicProductionTargets(); + assertThat(stored.get()).isNotEmpty(); + assertThat(store.find(transport)).isPresent(); + } + + @Test + void deletionAfterReassertPreReadIsRefusedWithoutRetryOrRecreation() { + var menu = store.discoverAndReplace(transport).orElseThrow(); + when(commands.getrange(any(byte[].class), anyLong(), anyLong())) + .thenAnswer(invocation -> stored.getAndSet(null)); + clearInvocations(commands); + + assertThat(store.reassert(transport, menu)).isFalse(); + assertThat(stored.get()).isNull(); + verify(commands).getrange(any(byte[].class), eq(0L), eq(2097152L)); + verify(commands, never()).scriptLoad(any(byte[].class)); + verifyEvaluations(1); + } + + private String evaluation() { + return commands.evalsha( + anyString(), + eq(ScriptOutputType.STATUS), + any(byte[][].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class)); + } + + private void verifyEvaluations(int count) { + verify(commands, times(count)) + .evalsha( + eq(sha1), + eq(ScriptOutputType.STATUS), + eq( + new byte[][] { + (DirectTextWorldMenuRedisStore.OWNED_PREFIX + transport.proxyConnectionId()) + .getBytes(StandardCharsets.US_ASCII) + }), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class), + any(byte[].class)); + } + + private static RedisScriptCatalog installed() { + return RedisScriptCatalog.loadInstalled(DirectTextWorldMenuRedisStore.class.getClassLoader()); + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection mockConnection() { + return mock(StatefulRedisConnection.class); + } + + @SuppressWarnings("unchecked") + private static RedisCommands mockCommands() { + return mock(RedisCommands.class); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java new file mode 100644 index 0000000000..71248237f4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java @@ -0,0 +1,914 @@ +package unit.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.clearInvocations; +import static org.mockito.Mockito.doThrow; +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.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService.InvalidAuthorityException; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService.ReadUnavailableException; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +class DirectTextWorldSelectionServiceTest { + private static final Instant NOW = Instant.parse("2026-10-31T12:00:00Z"); + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID OTHER = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final CanonicalPlayerRouteReadService reader = + mock(CanonicalPlayerRouteReadService.class); + private final MutableClock clock = new MutableClock(); + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void historicalEncodingRemainsClockIndependentWhileRestorationAndResolutionRefuseUnliveHandles( + boolean expired) { + var first = target(""); + var reads = new AtomicInteger(); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + reads.incrementAndGet(); + return List.of(world(first)); + }); + var source = service(catalog, List.of(first)); + var menu = source.browse().orElseThrow(); + byte[] original = source.encodeSnapshot(menu).orElseThrow(); + var foreignOwner = service(catalog, List.of(first)); + assertThat(reads.get()).isEqualTo(2); + clearInvocations(reader); + clock.now = expired ? menu.expiresAt() : NOW.minusNanos(1); + + // The new immediate-discovery helper must not change generic historical encoding semantics. + assertThat(source.encodeSnapshot(menu)) + .hasValueSatisfying(bytes -> assertThat(bytes).isEqualTo(original)); + assertThat(foreignOwner.encodeSnapshot(menu)).isEmpty(); + assertThat(source.encodeSnapshot(null)).isEmpty(); + assertThat(source.restoreSnapshot(original)).isEmpty(); + assertThat(source.resolve(menu, "1")).isEmpty(); + assertThat(reads.get()).isEqualTo(2); + verifyNoInteractions(reader); + } + + @Test + void restoresAcrossInstancesWithOriginalOrderOwnershipAndDeadline() { + var first = target(""); + var second = target("second"); + var source = service(List.of(world(second), world(first)), List.of(first, second)); + var original = source.browse().orElseThrow(); + byte[] stored = source.encodeSnapshot(original).orElseThrow(); + var replacement = service(List.of(world(second), world(first)), List.of(first, second)); + clock.now = NOW.plusSeconds(299); + + var restored = replacement.restoreSnapshot(stored).orElseThrow(); + + assertThat(restored.selectors()).containsExactly("other-tenant/other-world", "studio/forest"); + assertThat(restored.worlds()).containsExactly(world(second), world(first)); + assertThat(restored.expiresAt()).isEqualTo(original.expiresAt()); + assertThat(replacement.encodeSnapshot(restored).orElseThrow()).isEqualTo(stored); + assertThat(replacement.resolve(restored, "1")).contains(second); + assertThat(replacement.resolve(restored, "2")).contains(first); + assertThat(replacement.resolve(restored, "STUDIO/FOREST")).contains(first); + assertThat(replacement.resolve(restored, "studio")).contains(first); + clearInvocations(reader); + assertThat(source.resolve(restored, "1")).isEmpty(); + assertThat(replacement.resolve(original, "1")).isEmpty(); + assertThat(replacement.encodeSnapshot(original)).isEmpty(); + assertThat(replacement.encodeSnapshot(null)).isEmpty(); + verifyNoInteractions(reader); + + clock.now = NOW.plusSeconds(300).minusNanos(1); + assertThat(replacement.restoreSnapshot(stored)).isPresent(); + assertThat(replacement.resolve(restored, "1")).contains(second); + clearInvocations(reader); + clock.now = NOW.plusSeconds(300); + assertThat(replacement.restoreSnapshot(stored)).isEmpty(); + assertThat(replacement.resolve(restored, "1")).isEmpty(); + verifyNoInteractions(reader); + } + + @ParameterizedTest + @ValueSource(strings = {"short", "long", "future", "expired"}) + void rejectsInvalidOriginalTimesBeforeReadingSources(String change) { + var first = target(""); + var source = service(List.of(world(first)), List.of(first)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + Instant created = "future".equals(change) ? NOW.plusSeconds(1) : NOW; + Instant expires = created.plusSeconds("short".equals(change) ? 299 : 300); + if ("long".equals(change)) { + expires = expires.plusNanos(1); + } + Instant deadline = expires; + byte[] altered = + alterSnapshot( + stored, + snapshot -> { + snapshot.set("createdAt", JSON.valueToTree(created)); + snapshot.set("expiresAt", JSON.valueToTree(deadline)); + }); + if ("expired".equals(change)) { + clock.now = deadline; + } + clearInvocations(reader); + + assertThat(source.restoreSnapshot(altered)).isEmpty(); + verifyNoInteractions(reader); + } + + @ParameterizedTest + @ValueSource( + strings = {"subset", "reorder", "duplicate", "empty", "fingerprint", "target", "world"}) + void refusesSyntheticMenusEvenWhenTheCatalogFingerprintIsRetained(String change) { + var first = target(""); + var second = target("second"); + var source = service(List.of(world(first), world(second)), List.of(first, second)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + byte[] altered = + alterSnapshot( + stored, + snapshot -> { + ArrayNode choices = (ArrayNode) snapshot.get("choices"); + switch (change) { + case "subset" -> choices.remove(1); + case "empty" -> choices.removeAll(); + case "duplicate" -> choices.set(1, choices.get(0)); + case "reorder" -> { + var originalFirst = choices.get(0); + choices.set(0, choices.get(1)); + choices.set(1, originalFirst); + } + case "fingerprint" -> snapshot.put("fingerprint", "forged"); + case "target" -> + ((ObjectNode) choices.get(0)) + .set("target", JSON.valueToTree(target("owner-namespace"))); + case "world" -> + ((ObjectNode) choices.get(0)) + .set("world", JSON.valueToTree(world(first, true))); + default -> throw new AssertionError(change); + } + }); + + assertThat(source.restoreSnapshot(altered)).isEmpty(); + // Decodable but changed evidence was checked against the actual source, not just its digest. + verify(reader, times(2)).readVisiblePublicProductionTargets(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "unknown-target", + "unknown-world", + "missing-target-field", + "null-realms", + "coerced-number" + }) + void refusesMalformedNestedRecordsWithoutConsultingSources(String change) { + var first = target(""); + var source = service(List.of(world(first)), List.of(first)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + byte[] altered = + alterSnapshot( + stored, + snapshot -> { + var choice = snapshot.get("choices").get(0); + ObjectNode target = (ObjectNode) choice.get("target"); + ObjectNode world = (ObjectNode) choice.get("world"); + switch (change) { + case "unknown-target" -> target.put("unexpected", true); + case "unknown-world" -> world.put("unexpected", true); + case "missing-target-field" -> target.remove("positiveDurableAbort"); + case "null-realms" -> world.putNull("realms"); + case "coerced-number" -> target.put("gameInstanceId", "202"); + default -> throw new AssertionError(change); + } + }); + clearInvocations(reader); + + assertThat(source.restoreSnapshot(altered)).isEmpty(); + verifyNoInteractions(reader); + } + + @ParameterizedTest + @ValueSource(strings = {"reorder", "changed", "duplicate", "empty"}) + void refusesRestorationAgainstChangedCurrentCatalog(String change) { + var first = target(""); + var second = target("second"); + AtomicReference> worlds = + new AtomicReference<>(List.of(world(first), world(second))); + var catalog = GameplayWorldCatalog.forWorldSupplier(worlds::get); + var source = service(catalog, List.of(first, second)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + worlds.set( + switch (change) { + case "reorder" -> List.of(world(second), world(first)); + case "changed" -> List.of(world(first, true), world(second)); + case "duplicate" -> List.of(world(first), world(first)); + case "empty" -> List.of(); + default -> throw new AssertionError(change); + }); + + assertThat(service(catalog, List.of(first, second)).restoreSnapshot(stored)).isEmpty(); + } + + @Test + void restorationRetainsFullCanonicalOwnerChecksBeforeAndAfterCreatingTheHandle() { + var first = target(""); + var source = service(List.of(world(first)), List.of(first)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + var replacement = service(List.of(world(first)), List.of(first)); + when(reader.readVisiblePublicProductionTargets()) + .thenReturn(List.of(target("owner-namespace"))); + assertThat(replacement.restoreSnapshot(stored)).isEmpty(); + + when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(first)); + var restored = replacement.restoreSnapshot(stored).orElseThrow(); + when(reader.readCurrentTarget(first)).thenReturn(target("owner-namespace")); + assertThat(replacement.resolve(restored, "1")).isEmpty(); + } + + @Test + void restorationRechecksOriginalExpiryAfterCanonicalAndCatalogReads() { + var first = target(""); + AtomicReference readEffect = new AtomicReference<>(() -> {}); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + readEffect.get().run(); + return List.of(world(first)); + }); + var source = service(catalog, List.of(first)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + var replacement = service(catalog, List.of(first)); + when(reader.readVisiblePublicProductionTargets()) + .thenAnswer( + invocation -> { + clock.now = NOW.plusSeconds(300); + return List.of(first); + }); + assertThat(replacement.restoreSnapshot(stored)).isEmpty(); + + clock.now = NOW; + when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(first)); + AtomicInteger reads = new AtomicInteger(); + readEffect.set( + () -> { + if (reads.incrementAndGet() == 2) { + clock.now = NOW.plusSeconds(300); + } + }); + assertThat(replacement.restoreSnapshot(stored)).isEmpty(); + } + + @Test + void restorationKeepsParsingRefusalSeparateFromUnavailableAndInvalidSources() { + var first = target(""); + var source = service(List.of(world(first)), List.of(first)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + var replacement = service(List.of(world(first)), List.of(first)); + var unavailable = new ReadUnavailableException("owner unreachable"); + when(reader.readVisiblePublicProductionTargets()).thenThrow(unavailable); + clearInvocations(reader); + assertThat(replacement.restoreSnapshot(null)).isEmpty(); + assertThat(replacement.restoreSnapshot(new byte[] {'{'})).isEmpty(); + verifyNoInteractions(reader); + assertThatThrownBy(() -> replacement.restoreSnapshot(stored)).isSameAs(unavailable); + doThrow(new InvalidAuthorityException("owner invalid")) + .when(reader) + .readVisiblePublicProductionTargets(); + assertThat(replacement.restoreSnapshot(stored)).isEmpty(); + + var catalogUnavailable = + new GameplayWorldCatalog.AuthorityPointerUnavailableException("unavailable"); + var unreachableCatalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + throw catalogUnavailable; + }); + var catalogReplacement = new DirectTextWorldSelectionService(unreachableCatalog, reader, clock); + assertThatThrownBy(() -> catalogReplacement.restoreSnapshot(stored)) + .isSameAs(catalogUnavailable); + var defaultOff = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldViews(List.of(world(first))), + CanonicalPlayerRouteReadService.unavailable(), + clock); + assertThatThrownBy(() -> defaultOff.restoreSnapshot(stored)) + .isInstanceOf(ReadUnavailableException.class); + } + + @Test + void restorationDoesNotHideCatalogDriftDuringFreshCompositionOrDuplicateCanonicalSources() { + var first = target(""); + AtomicReference> worlds = new AtomicReference<>(List.of(world(first))); + var catalog = GameplayWorldCatalog.forWorldSupplier(worlds::get); + var source = service(catalog, List.of(first)); + byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); + when(reader.readVisiblePublicProductionTargets()) + .thenAnswer( + invocation -> { + worlds.set(List.of()); + return List.of(first); + }); + assertThat(source.restoreSnapshot(stored)).isEmpty(); + worlds.set(List.of(world(first))); + when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(first, first)); + assertThat(source.restoreSnapshot(stored)).isEmpty(); + } + + private static byte[] alterSnapshot(byte[] stored, Consumer alteration) { + ObjectNode envelope = (ObjectNode) JSON.readTree(stored); + alteration.accept((ObjectNode) envelope.get("snapshot")); + return JSON.writeValueAsBytes(envelope); + } + + @Test + void correlatesExactEvidenceInCatalogOrderAndRetainsCompleteTarget() { + var first = target(""); + var second = target("second"); + var service = service(List.of(world(second), world(first)), List.of(first, second)); + + var menu = service.browse().orElseThrow(); + + assertThat(menu.selectors()).containsExactly("other-tenant/other-world", "studio/forest"); + assertThat(menu.worlds()).containsExactly(world(second), world(first)); + assertThat(menu.expiresAt()).isEqualTo(NOW.plusSeconds(300)); + assertThat(service.resolve(menu, "1")).containsSame(second); + assertThat(service.resolve(menu, "2")).containsSame(first); + verify(reader).readCurrentTarget(first); + verify(reader).readCurrentTarget(second); + } + + @Test + void pairsAreCaseFoldedAndBareTenantRequiresExactlyOneSnapshotWorld() { + var first = target(""); + // The current real catalog permits only one public realm per numeric tenant. Distinct runtime + // tenants below deliberately exercise the selection ambiguity guard with valid target records. + var sameFriendlyTenant = target("same-tenant"); + var service = + service( + List.of(world(first), world(sameFriendlyTenant)), List.of(first, sameFriendlyTenant)); + var menu = service.browse().orElseThrow(); + + assertThat(service.resolve(menu, "STUDIO/FOREST")).contains(first); + assertThat(service.resolve(menu, "studio/other-world")).contains(sameFriendlyTenant); + assertThat(service.resolve(menu, "studio")).isEmpty(); + assertThat(service.resolve(menu, "forest")).isEmpty(); + assertThat(service.resolve(menu, "other-world")).isEmpty(); + + var single = service(List.of(world(first)), List.of(first)); + assertThat(single.resolve(single.browse().orElseThrow(), "STUDIO")).contains(first); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + " ", + "forest", + "101", + "202", + "0", + "-1", + "+1", + "2147483648", + "studio/forest/extra", + " studio/forest", + "studio/forest " + }) + void invalidSelectorsDoNotReadSources(String selector) { + var first = target(""); + AtomicInteger catalogReads = new AtomicInteger(); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + catalogReads.incrementAndGet(); + return List.of(world(first)); + }); + var service = service(catalog, List.of(first)); + var menu = service.browse().orElseThrow(); + clearInvocations(reader); + int before = catalogReads.get(); + + assertThat(service.resolve(menu, selector)).isEmpty(); + assertThat(service.resolve(menu, null)).isEmpty(); + assertThat(service.resolve(null, "1")).isEmpty(); + assertThat(catalogReads.get()).isEqualTo(before); + verifyNoInteractions(reader); + } + + @Test + void reorderedCatalogNeverReinterpretsAnOldOrdinal() { + var first = target(""); + var second = target("second"); + AtomicReference> worlds = + new AtomicReference<>(List.of(world(first), world(second))); + var service = + service(GameplayWorldCatalog.forWorldSupplier(worlds::get), List.of(first, second)); + var oldMenu = service.browse().orElseThrow(); + worlds.set(List.of(world(second), world(first))); + + assertThat(service.resolve(oldMenu, "1")).isEmpty(); + // Selection came from the old vector, not the current reordered catalog. + verify(reader).readCurrentTarget(first); + var refreshed = service.browse().orElseThrow(); + assertThat(service.resolve(refreshed, "1")).containsSame(second); + } + + @Test + void changedCatalogDuringBrowseIsRefused() { + var first = target(""); + AtomicReference> worlds = new AtomicReference<>(List.of(world(first))); + var catalog = GameplayWorldCatalog.forWorldSupplier(worlds::get); + when(reader.readVisiblePublicProductionTargets()) + .thenAnswer( + invocation -> { + worlds.set(List.of()); + return List.of(first); + }); + + assertThat(new DirectTextWorldSelectionService(catalog, reader, clock).browse()).isEmpty(); + } + + @Test + void originalProjectionAndSelectorOutputsAreImmutableAfterSourceMutation() { + var first = target(""); + ArrayList worlds = new ArrayList<>(List.of(world(first))); + var service = service(GameplayWorldCatalog.forWorldSupplier(() -> worlds), List.of(first)); + var menu = service.browse().orElseThrow(); + worlds.clear(); + + assertThat(menu.selectors()).containsExactly("studio/forest"); + assertThat(menu.worlds()).containsExactly(world(first)); + assertThatThrownBy(() -> menu.selectors().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> menu.worlds().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> menu.worlds().getFirst().realms().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(service.resolve(menu, "1")).isEmpty(); + } + + @Test + void expiryIsExclusiveAtFiveMinutesAndExpiredSelectionsHaveNoSourceEffects() { + var first = target(""); + AtomicInteger catalogReads = new AtomicInteger(); + var service = + service( + GameplayWorldCatalog.forWorldSupplier( + () -> { + catalogReads.incrementAndGet(); + return List.of(world(first)); + }), + List.of(first)); + var menu = service.browse().orElseThrow(); + clock.now = NOW.plusSeconds(300).minusNanos(1); + assertThat(service.resolve(menu, "1")).contains(first); + clearInvocations(reader); + int before = catalogReads.get(); + clock.now = NOW.plusSeconds(300); + + assertThat(service.resolve(menu, "1")).isEmpty(); + clock.now = NOW.plusSeconds(301); + assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + assertThat(catalogReads.get()).isEqualTo(before); + verifyNoInteractions(reader); + } + + @Test + void expiryIsRecheckedAfterCanonicalAndCatalogReads() { + var first = target(""); + AtomicReference onCatalogRead = new AtomicReference<>(() -> {}); + var service = + service( + GameplayWorldCatalog.forWorldSupplier( + () -> { + onCatalogRead.get().run(); + return List.of(world(first)); + }), + List.of(first)); + var menu = service.browse().orElseThrow(); + when(reader.readCurrentTarget(first)) + .thenAnswer( + invocation -> { + clock.now = NOW.plusSeconds(300); + return first; + }); + assertThat(service.resolve(menu, "1")).isEmpty(); + + clock.now = NOW; + when(reader.readCurrentTarget(first)).thenReturn(first); + onCatalogRead.set(() -> clock.now = NOW.plusSeconds(300)); + assertThat(service.resolve(menu, "1")).isEmpty(); + } + + @Test + void browseTimeConsumesTheSameBoundedMenuLifetime() { + var first = target(""); + var service = service(List.of(world(first)), List.of(first)); + when(reader.readVisiblePublicProductionTargets()) + .thenAnswer( + invocation -> { + clock.now = NOW.plusSeconds(300); + return List.of(first); + }); + assertThat(service.browse()).isEmpty(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "realm", + "namespace", + "revision", + "pointer", + "runtime", + "tenant", + "world", + "realm-slug", + "world-display", + "realm-display", + "scope", + "policy" + }) + void missingOrContradictoryCatalogCorrelationIsRefused(String change) { + var original = target(""); + var changed = target(change); + assertThat(service(List.of(world(original)), List.of(changed)).browse()).isEmpty(); + } + + @Test + void displayNamesAloneNeverCorrelateAndMissingTargetsFailClosed() { + var first = target(""); + assertThat(service(List.of(world(first)), List.of()).browse()).isEmpty(); + assertThat(service(List.of(world(first)), List.of(target("tenant"))).browse()).isEmpty(); + // A synthetic catalog view without real UUID evidence cannot supply canonical identity. + var realm = world(first).realms().getFirst(); + var incomplete = + new RealmView( + realm.slug(), + realm.displayName(), + realm.tenantId(), + realm.gameInstanceId(), + realm.pointerVersion(), + true, + true, + false, + realm.stateScope(), + realm.characterCreationPolicy(), + realm.catalogRevision()); + assertThat( + service(List.of(new WorldView("forest", "Forest", List.of(incomplete))), List.of(first)) + .browse()) + .isEmpty(); + } + + @Test + void duplicateFriendlyPairsAndRuntimeWorldIdentitiesAreInvalidEvenIfOneRowWouldMatch() { + var first = target(""); + assertThat(service(List.of(world(first)), List.of(first, first)).browse()).isEmpty(); + assertThat(service(List.of(world(first)), List.of(first, target("duplicate-pair"))).browse()) + .isEmpty(); + assertThat(service(List.of(world(first)), List.of(first, target("duplicate-runtime"))).browse()) + .isEmpty(); + assertThat(service(List.of(world(first)), List.of(first, target("duplicate-world"))).browse()) + .isEmpty(); + assertThat(service(List.of(world(first)), Arrays.asList(first, null)).browse()).isEmpty(); + } + + @ParameterizedTest + @ValueSource(strings = {"uppercase-tenant", "uppercase-world", "bad-tenant", "bad-world"}) + void inconsistentCanonicalSlugsAreNotNormalizedIntoAuthority(String change) { + var invalid = target(change); + assertThat(service(List.of(world(invalid)), List.of(invalid)).browse()).isEmpty(); + } + + @ParameterizedTest + @ValueSource( + strings = {"owner-namespace", "canonical-tenant", "hold-digest", "proof-digest", "terminal"}) + void changedCanonicalOwnerEvidenceCannotReuseTheRetainedSelection(String change) { + var first = target(""); + var service = service(List.of(world(first)), List.of(first)); + var menu = service.browse().orElseThrow(); + when(reader.readCurrentTarget(first)).thenReturn(target(change)); + + assertThat(service.resolve(menu, "1")).isEmpty(); + } + + @Test + void selectionEvidenceChangeInvalidatesFingerprintEvenWithoutTargetCounterpart() { + var first = target(""); + AtomicReference> worlds = new AtomicReference<>(List.of(world(first))); + var service = service(GameplayWorldCatalog.forWorldSupplier(worlds::get), List.of(first)); + var menu = service.browse().orElseThrow(); + worlds.set(List.of(world(first, true))); + + assertThat(service.resolve(menu, "1")).isEmpty(); + } + + @ParameterizedTest + @ValueSource( + strings = {"realm", "namespace", "revision", "pointer", "world-display", "scope", "policy"}) + void catalogOnlyDriftCannotReuseTheRetainedTarget(String change) { + var first = target(""); + AtomicReference> worlds = new AtomicReference<>(List.of(world(first))); + var service = service(GameplayWorldCatalog.forWorldSupplier(worlds::get), List.of(first)); + var menu = service.browse().orElseThrow(); + worlds.set(List.of(world(target(change)))); + + assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + verify(reader).readCurrentTarget(first); + } + + @Test + void reachableInvalidCanonicalEvidenceIsEmptyButUnavailableReadsEscapeUnchanged() { + var first = target(""); + var service = service(List.of(world(first)), List.of(first)); + var menu = service.browse().orElseThrow(); + var unavailable = new ReadUnavailableException("owner unreachable"); + when(reader.readCurrentTarget(first)).thenThrow(unavailable); + assertThatThrownBy(() -> service.resolve(menu, "1")).isSameAs(unavailable); + doThrow(new InvalidAuthorityException("owner stale")).when(reader).readCurrentTarget(first); + assertThat(service.resolve(menu, "1")).isEmpty(); + when(reader.readVisiblePublicProductionTargets()).thenThrow(unavailable); + assertThatThrownBy(service::browse).isSameAs(unavailable); + doThrow(new InvalidAuthorityException("invalid catalog")) + .when(reader) + .readVisiblePublicProductionTargets(); + assertThat(service.browse()).isEmpty(); + } + + @Test + void catalogUnavailabilityEscapesDuringBrowseAndResolve() { + var first = target(""); + AtomicReference readEffect = new AtomicReference<>(() -> {}); + var service = + service( + GameplayWorldCatalog.forWorldSupplier( + () -> { + readEffect.get().run(); + return List.of(world(first)); + }), + List.of(first)); + var menu = service.browse().orElseThrow(); + var unavailable = new GameplayWorldCatalog.AuthorityPointerUnavailableException("unavailable"); + readEffect.set( + () -> { + throw unavailable; + }); + assertThatThrownBy(service::browse).isSameAs(unavailable); + assertThatThrownBy(() -> service.resolve(menu, "1")).isSameAs(unavailable); + } + + @Test + void aSnapshotFromAnotherCompositionIsNotAccepted() { + var first = target(""); + var source = service(List.of(world(first)), List.of(first)); + var menu = source.browse().orElseThrow(); + var other = service(List.of(world(first)), List.of(first)); + clearInvocations(reader); + + assertThat(other.resolve(menu, "1")).isEmpty(); + verifyNoInteractions(reader); + } + + @Test + void canonicalTargetsNeverRestoreCatalogCollisionCardinalityOrHiddenRowOmissions() { + var first = target(""); + var second = target("second"); + var authority = mock(GameplayAdmissionPointerAuthorityService.class); + var catalog = new GameplayWorldCatalog(authority); + var publicPointer = pointer(first, "forest", "public", true, true, 1L); + List> guardedSources = + List.of( + // Folded global world-slug collision, even though canonical friendly pairs differ. + List.of(publicPointer, pointer(second, "FOREST", "public", true, true, 1L)), + // Two visible public realms for the same tenant. + List.of(publicPointer, pointer(first, "forest", "another-public", true, true, 1L)), + // An incomplete hidden row poisons the public tenant's authority. + List.of(publicPointer, pointer(first, "forest", "hidden", false, false, 0L)), + List.of(pointer(first, "forest", "public", false, true, 1L))); + var service = service(catalog, List.of(first, second)); + for (var pointers : guardedSources) { + when(authority.listPointers()).thenReturn(pointers); + var menu = service.browse().orElseThrow(); + assertThat(menu.selectors()).isEmpty(); + assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + } + } + + @Test + void pointerBackedCatalogOrderIsRetainedAndOmittedRowChangesStillInvalidateTheMenu() { + var first = target(""); + var second = target("second"); + var authority = mock(GameplayAdmissionPointerAuthorityService.class); + var firstPointer = pointer(first, "forest", "public", true, true, 1L); + var secondPointer = pointer(second, "other-world", "public", true, true, 1L); + // This hidden private realm is complete, so it does not poison the healthy first tenant. + var hidden = pointer(first, "forest", "hidden", false, false, 1L); + when(authority.listPointers()).thenReturn(List.of(secondPointer, firstPointer, hidden)); + var service = service(new GameplayWorldCatalog(authority), List.of(first, second)); + var menu = service.browse().orElseThrow(); + + assertThat(menu.selectors()).containsExactly("other-tenant/other-world", "studio/forest"); + assertThat(service.resolve(menu, "2")).containsSame(first); + when(authority.listPointers()) + .thenReturn( + List.of( + secondPointer, firstPointer, pointer(first, "forest", "hidden", false, false, 2L))); + assertThat(service.resolve(menu, "2")).isEmpty(); + assertThat(menu.selectors()).containsExactly("other-tenant/other-world", "studio/forest"); + } + + @Test + void actualDefaultOffCanonicalOwnerRemainsUnavailableRatherThanAnInvalidSelection() { + var service = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldViews(List.of(world(target("")))), + CanonicalPlayerRouteReadService.unavailable(), + clock); + + assertThatThrownBy(service::browse).isInstanceOf(ReadUnavailableException.class); + } + + private DirectTextWorldSelectionService service( + List worlds, List targets) { + return service(GameplayWorldCatalog.forWorldViews(worlds), targets); + } + + private DirectTextWorldSelectionService service( + GameplayWorldCatalog catalog, List targets) { + when(reader.readVisiblePublicProductionTargets()).thenReturn(targets); + for (var target : targets) { + if (target != null) { + when(reader.readCurrentTarget(target)).thenReturn(target); + } + } + return new DirectTextWorldSelectionService(catalog, reader, clock); + } + + private static WorldView world(CanonicalPlayableTarget target) { + return world(target, false); + } + + private static WorldView world(CanonicalPlayableTarget target, boolean characterSelection) { + return new WorldView( + target.worldSlug(), + target.worldDisplayName(), + List.of( + new RealmView( + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.pointerVersion(), + true, + true, + characterSelection, + target.playableStateScope(), + target.characterCreationPolicy(), + target.catalogRevision(), + target.realmId(), + target.playableStateNamespaceId()))); + } + + private static GameplayAdmissionPointerSnapshot pointer( + CanonicalPlayableTarget target, + String world, + String realm, + boolean visible, + boolean publicProduction, + long catalogRevision) { + return new GameplayAdmissionPointerSnapshot( + world, + target.worldDisplayName(), + realm, + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.pointerVersion(), + visible, + publicProduction, + false, + target.playableStateScope(), + target.characterCreationPolicy(), + catalogRevision, + target.realmId(), + target.playableStateNamespaceId()); + } + + /** Controlled owner evidence uses real record invariants, never numeric-to-UUID derivation. */ + private static CanonicalPlayableTarget target(String change) { + boolean second = "second".equals(change) || "same-tenant".equals(change); + boolean otherWorld = second || "duplicate-runtime".equals(change); + String tenantSlug = + switch (change) { + case "second", "duplicate-runtime", "duplicate-world", "tenant-slug" -> "other-tenant"; + case "uppercase-tenant" -> "STUDIO"; + case "bad-tenant" -> "bad/tenant"; + default -> "studio"; + }; + String worldSlug = + switch (change) { + case "uppercase-world" -> "FOREST"; + case "bad-world" -> "bad/world"; + case "world" -> "changed-world"; + default -> otherWorld ? "other-world" : "forest"; + }; + return new CanonicalPlayableTarget( + "owner-namespace".equals(change) ? "another-owner" : "gameplay", + tenantSlug, + second || "canonical-tenant".equals(change) || "duplicate-world".equals(change) + ? OTHER + : TENANT, + worldSlug, + "world-display".equals(change) ? "Changed Forest" : "Forest", + second || "realm".equals(change) ? OTHER : REALM, + "realm-slug".equals(change) ? "changed-realm" : "public", + "realm-display".equals(change) ? "Changed Realm" : "Live Realm", + second || "tenant".equals(change) || "duplicate-pair".equals(change) ? 909L : 101L, + second + || "runtime".equals(change) + || "duplicate-pair".equals(change) + || "duplicate-world".equals(change) + ? 808L + : 202L, + second || "namespace".equals(change) ? OTHER : NAMESPACE, + "scope".equals(change) ? "ISOLATED" : "SHARED", + second || "canonical-instance".equals(change) ? OTHER : INSTANCE, + "canonical-version".equals(change) ? OTHER : VERSION, + "runtime-version".equals(change) ? 304L : 303L, + "revision".equals(change) ? 2L : 1L, + "pointer".equals(change) ? 8L : 7L, + ("pointer-digest".equals(change) ? "e" : "d").repeat(64), + "epoch".equals(change) ? 83L : 82L, + "request-id".equals(change) ? "another-open" : "original-open", + ("request-digest".equals(change) ? "b" : "a").repeat(64), + "origin".equals(change) ? OriginKind.EXPECT_CLOSED : OriginKind.NO_PRIOR_POINTER, + "origin".equals(change) ? Long.valueOf(6L) : null, + "hold".equals(change) ? OTHER : HOLD, + "fence".equals(change) ? OTHER : FENCE, + "sha256:" + ("hold-digest".equals(change) ? "b" : "c").repeat(64), + "audit".equals(change) ? 28L : 27L, + "sha256:" + ("proof-digest".equals(change) ? "e" : "f").repeat(64), + Outcome.COMMITTED, + false, + "terminal".equals(change) ? NOW.minusSeconds(2) : NOW.minusSeconds(1), + "policy".equals(change) ? "PRESEEDED_ONLY" : "ALLOW_NEW"); + } + + private static final class MutableClock extends Clock { + private Instant now = NOW; + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return Clock.fixed(now, zone); + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionSnapshotCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionSnapshotCodecTest.java new file mode 100644 index 0000000000..7e14fb9f81 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionSnapshotCodecTest.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.gamesession.command.text; + +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.ArrayList; +import java.util.Arrays; +import java.util.List; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.Choice; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.Snapshot; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class DirectTextWorldSelectionSnapshotCodecTest { + private static final Instant CREATED = Instant.parse("2026-10-31T12:00:00Z"); + + @Test + void roundTripsImmutableEvidenceWithoutCreatingAUsableHandle() { + ArrayList choices = new ArrayList<>(); + var original = new Snapshot(choices, "original-fingerprint", CREATED, CREATED.plusSeconds(300)); + byte[] encoded = DirectTextWorldSelectionSnapshotCodec.encode(original); + var decoded = DirectTextWorldSelectionSnapshotCodec.decode(encoded).orElseThrow(); + + assertThat(decoded).isEqualTo(original); + assertThat(decoded.choices()).isEmpty(); + assertThatThrownBy(() -> decoded.choices().clear()) + .isInstanceOf(UnsupportedOperationException.class); + Arrays.fill(encoded, (byte) 0); + assertThat(decoded).isEqualTo(original); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "null", + "{}", + "[]", + "{", + "{\"schema\":\"direct-text-world-selection/v2\",\"snapshot\":{}}", + "{\"schema\":\"direct-text-world-selection/v1\",\"snapshot\":null}" + }) + void rejectsUnsupportedAndMalformedPayloads(String payload) { + assertThat( + DirectTextWorldSelectionSnapshotCodec.decode(payload.getBytes(StandardCharsets.UTF_8))) + .isEmpty(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "version", + "unknown", + "nested-unknown", + "duplicate", + "nested-duplicate", + "trailing", + "missing", + "null", + "coercion", + "whitespace" + }) + void rejectsSchemaDriftDuplicatesTrailingTokensAndRepairs(String change) { + String encoded = + new String( + DirectTextWorldSelectionSnapshotCodec.encode(snapshot("evidence")), + StandardCharsets.UTF_8); + String altered = + switch (change) { + case "version" -> + encoded.replace("direct-text-world-selection/v1", "direct-text-world-selection/v2"); + case "unknown" -> encoded.replaceFirst("\\{", "{\"unexpected\":true,"); + case "nested-unknown" -> + encoded.replace("\"choices\":[]", "\"choices\":[],\"unexpected\":true"); + case "duplicate" -> + encoded.replace( + "\"schema\":", "\"schema\":\"direct-text-world-selection/v1\",\"schema\":"); + case "nested-duplicate" -> + encoded.replace("\"choices\":[]", "\"choices\":[],\"choices\":[]"); + case "trailing" -> encoded + "{}"; + case "missing" -> encoded.replace("\"choices\":[],", ""); + case "null" -> encoded.replace("\"choices\":[]", "\"choices\":null"); + case "coercion" -> encoded.replace("\"fingerprint\":\"evidence\"", "\"fingerprint\":42"); + case "whitespace" -> " " + encoded; + default -> throw new AssertionError(change); + }; + + assertThat(altered).isNotEqualTo(encoded); + assertThat( + DirectTextWorldSelectionSnapshotCodec.decode(altered.getBytes(StandardCharsets.UTF_8))) + .isEmpty(); + } + + @Test + void encodedAndDecodedTotalPayloadHaveAnInclusiveOneMiBBound() { + int overhead = DirectTextWorldSelectionSnapshotCodec.encode(snapshot("")).length; + String fingerprint = + "x".repeat(DirectTextWorldSelectionSnapshotCodec.MAX_PAYLOAD_BYTES - overhead); + byte[] atLimit = DirectTextWorldSelectionSnapshotCodec.encode(snapshot(fingerprint)); + + assertThat(atLimit).hasSize(1024 * 1024); + assertThat(DirectTextWorldSelectionSnapshotCodec.decode(atLimit)) + .contains(snapshot(fingerprint)); + assertThatThrownBy( + () -> DirectTextWorldSelectionSnapshotCodec.encode(snapshot(fingerprint + "x"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + DirectTextWorldSelectionSnapshotCodec.decode( + Arrays.copyOf(atLimit, atLimit.length + 1))) + .isEmpty(); + assertThat(DirectTextWorldSelectionSnapshotCodec.decode(new byte[0])).isEmpty(); + assertThat(DirectTextWorldSelectionSnapshotCodec.decode(null)).isEmpty(); + } + + @Test + void rejectsInvalidUtf8AndAlternateCharacterEncoding() { + byte[] invalid = DirectTextWorldSelectionSnapshotCodec.encode(snapshot("evidence")); + for (int index = 0; index < invalid.length; index++) { + if (invalid[index] == 'e') { + invalid[index] = (byte) 0xff; + break; + } + } + assertThat(DirectTextWorldSelectionSnapshotCodec.decode(invalid)).isEmpty(); + String encoded = + new String( + DirectTextWorldSelectionSnapshotCodec.encode(snapshot("evidence")), + StandardCharsets.UTF_8); + assertThat( + DirectTextWorldSelectionSnapshotCodec.decode(encoded.getBytes(StandardCharsets.UTF_16))) + .isEmpty(); + } + + private static Snapshot snapshot(String fingerprint) { + return new Snapshot(List.of(), fingerprint, CREATED, CREATED.plusSeconds(300)); + } +} 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 6c516a7094..fee5b895e7 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 @@ -11,6 +11,7 @@ import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -781,6 +782,324 @@ void browseViewUsesOneWorldSnapshotForDefaultRealmAndCardinalityChecks() { assertThat(supplierCalls).hasValue(1); } + @Test + void authoritySnapshotReadsOnceAndRetainsSuppressedPointerComparisonEvidence() { + GameplayAdmissionPointerSnapshot visible = publicPointer("demo", "Demo World", 1L, 11L); + GameplayAdmissionPointerSnapshot hidden = + new GameplayAdmissionPointerSnapshot( + "hidden", + "Hidden", + "production", + "Hidden Realm", + 2L, + 21L, + 1L, + false, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + stableId("hidden-realm"), + stableId("hidden-namespace")); + AtomicReference> source = + new AtomicReference<>(List.of(visible, hidden)); + AtomicInteger reads = new AtomicInteger(); + when(authorityService.listPointers()) + .thenAnswer( + invocation -> { + reads.incrementAndGet(); + return source.get(); + }); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + GameplayWorldCatalog.DiscoverySnapshot original = catalog.discoverySnapshot(); + assertThat(reads).hasValue(1); + assertThat(original.worlds()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("demo"); + source.set( + List.of( + visible, + new GameplayAdmissionPointerSnapshot( + hidden.worldSlug(), + hidden.worldDisplayName(), + hidden.realmSlug(), + hidden.realmDisplayName(), + hidden.tenantId(), + hidden.gameInstanceId(), + 2L, + hidden.visible(), + hidden.publicProductionRealm(), + hidden.requiresCharacterSelection(), + hidden.stateScope(), + hidden.characterCreationPolicy(), + hidden.catalogRevision(), + hidden.realmId(), + hidden.playableStateNamespaceId()))); + + GameplayWorldCatalog.DiscoverySnapshot changed = catalog.discoverySnapshot(); + assertThat(reads).hasValue(2); + assertThat(changed.worlds()).isEqualTo(original.worlds()); + assertThat(changed.fingerprint()).isNotEqualTo(original.fingerprint()); + } + + @Test + void discoverySnapshotReadsItsSourceOnce() { + AtomicInteger supplierCalls = new AtomicInteger(); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + supplierCalls.incrementAndGet(); + return List.of(worldWithRealm("demo", "production", 7L, true)); + }); + + GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.discoverySnapshot(); + + assertThat(supplierCalls).hasValue(1); + assertThat(snapshot.worlds()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("demo"); + } + + @Test + void realmDiscoverySnapshotReadsOneCurrentSourceForTheExactSelectedWorld() { + AtomicInteger supplierCalls = new AtomicInteger(); + GameplayWorldCatalog.WorldView selectedWorld = + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + realmView("live", "Live Realm", 7L, 11L, 1L, true, true, "ALLOW_NEW"), + realmView("preview", "Preview Realm", 7L, 12L, 2L, true, false, "ALLOW_NEW"), + realmView("hidden", "Hidden Realm", 7L, 13L, 3L, false, false, "ALLOW_NEW"))); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + supplierCalls.incrementAndGet(); + return List.of(selectedWorld); + }); + GameplayWorldCatalog.DiscoverySnapshot discovery = catalog.discoverySnapshot(); + assertThat(supplierCalls).hasValue(1); + + GameplayWorldCatalog.RealmDiscoverySnapshot realms = + catalog.realmDiscoverySnapshot(discovery.worlds().getFirst()).orElseThrow(); + + assertThat(supplierCalls).hasValue(2); + assertThat(realms.world().slug()).isEqualTo(discovery.worlds().getFirst().slug()); + assertThat(realms.realms()) + .extracting(GameplayWorldCatalog.RealmView::slug) + .containsExactly("live", "preview"); + assertThat(realms.world().realms()) + .extracting(GameplayWorldCatalog.RealmView::slug) + .containsExactly("live", "preview"); + assertThat(realms.realms().getFirst()) + .isEqualTo(discovery.worlds().getFirst().realms().getFirst()); + assertThat(realms.fingerprint()).isEqualTo(discovery.fingerprint()); + } + + @Test + void retainedDiscoverySnapshotOrderAndDataDoNotFollowLaterSupplierReordering() { + AtomicReference> source = + new AtomicReference<>( + List.of( + worldWithRealm("alpha", "production", 1L, true), + worldWithRealm("beta", "production", 2L, true))); + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(source::get); + + GameplayWorldCatalog.DiscoverySnapshot responseSnapshot = catalog.discoverySnapshot(); + source.set( + List.of( + worldWithRealm("beta", "production", 2L, true), + worldWithRealm("alpha", "production", 1L, true))); + + assertThat(catalog.discoverySnapshot().worlds()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("beta", "alpha"); + assertThat(responseSnapshot.worlds()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("alpha", "beta"); + assertThat(responseSnapshot.worlds().getFirst().displayName()).isEqualTo("alpha"); + assertThatThrownBy(() -> responseSnapshot.worlds().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> responseSnapshot.worlds().getFirst().realms().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void discoveryFingerprintChangesWithCurrentTenantRealmNamespaceRevisionPointerAndPolicyData() { + GameplayWorldCatalog.RealmView baselineRealm = + realmView("live", "Live Realm", 7L, 11L, 3L, true, true, "ALLOW_NEW"); + GameplayWorldCatalog.WorldView baselineWorld = + new GameplayWorldCatalog.WorldView("demo", "Demo World", List.of(baselineRealm)); + AtomicReference> source = + new AtomicReference<>(List.of(baselineWorld)); + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(source::get); + String baselineFingerprint = catalog.discoverySnapshot().fingerprint(); + + List changedRealms = + List.of( + copyRealm( + baselineRealm, + 8L, + "live", + 11L, + 3L, + "ALLOW_NEW", + baselineRealm.realmId(), + baselineRealm.playableStateNamespaceId()), + copyRealm( + baselineRealm, + 7L, + "changed-realm", + 11L, + 3L, + "ALLOW_NEW", + baselineRealm.realmId(), + baselineRealm.playableStateNamespaceId()), + copyRealm( + baselineRealm, + 7L, + "live", + 12L, + 3L, + "ALLOW_NEW", + baselineRealm.realmId(), + baselineRealm.playableStateNamespaceId()), + copyRealm( + baselineRealm, + 7L, + "live", + 11L, + 3L, + "ALLOW_NEW", + stableId("other-realm"), + baselineRealm.playableStateNamespaceId()), + copyRealm( + baselineRealm, + 7L, + "live", + 11L, + 3L, + "ALLOW_NEW", + baselineRealm.realmId(), + stableId("other-namespace")), + copyRealm( + baselineRealm, + 7L, + "live", + 11L, + 3L, + "ALLOW_NEW", + baselineRealm.realmId(), + baselineRealm.playableStateNamespaceId(), + 4L), + copyRealm( + baselineRealm, + 7L, + "live", + 11L, + 4L, + "ALLOW_NEW", + baselineRealm.realmId(), + baselineRealm.playableStateNamespaceId()), + copyRealm( + baselineRealm, + 7L, + "live", + 11L, + 3L, + "PRESEEDED_ONLY", + baselineRealm.realmId(), + baselineRealm.playableStateNamespaceId()), + copyRealmWithStateScope(baselineRealm, "ISOLATED")); + + for (GameplayWorldCatalog.RealmView changedRealm : changedRealms) { + source.set( + List.of(new GameplayWorldCatalog.WorldView("demo", "Demo World", List.of(changedRealm)))); + GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.discoverySnapshot(); + assertThat(snapshot.worlds()) + .as("changed realm must remain projected for %s", changedRealm) + .singleElement() + .satisfies(world -> assertThat(world.realms()).containsExactly(changedRealm)); + assertThat(snapshot.fingerprint()) + .as("changed catalog evidence for %s", changedRealm) + .isNotEqualTo(baselineFingerprint); + } + } + + @Test + void discoverySnapshotPreservesTenantCollisionAndUnavailableSourceRefusals() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + publicPointer("shared", "Shared World", 1L, 11L), + publicPointer("shared", "Shared World", 2L, 21L), + publicPointer("healthy", "Healthy World", 3L, 31L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.discoverySnapshot().worlds()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("healthy"); + + when(authorityService.listPointers()).thenReturn(null); + assertThatThrownBy(catalog::discoverySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasMessageContaining("pointer list is unavailable"); + } + + @Test + void discoveryFingerprintIncludesHiddenRowsWithoutExposingThemInTheWorldProjection() { + GameplayWorldCatalog.RealmView publicRealm = + realmView("live", "Live Realm", 7L, 11L, 1L, true, true, "ALLOW_NEW"); + GameplayWorldCatalog.RealmView hiddenRealm = + realmView("hidden", "Hidden Realm", 7L, 12L, 2L, false, false, "ALLOW_NEW"); + AtomicReference> source = + new AtomicReference<>( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(publicRealm, hiddenRealm)))); + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(source::get); + GameplayWorldCatalog.DiscoverySnapshot initial = catalog.discoverySnapshot(); + + source.set( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + publicRealm, + realmView( + "hidden", + "Changed Hidden Realm", + 7L, + 12L, + 2L, + false, + false, + "ALLOW_NEW"))))); + GameplayWorldCatalog.DiscoverySnapshot changed = catalog.discoverySnapshot(); + + assertThat(initial.worlds().getFirst().realms()) + .extracting(GameplayWorldCatalog.RealmView::slug) + .containsExactly("live"); + assertThat(changed.worlds().getFirst().realms()) + .extracting(GameplayWorldCatalog.RealmView::slug) + .containsExactly("live"); + assertThat(changed.fingerprint()).isNotEqualTo(initial.fingerprint()); + } + + @Test + void realmDiscoverySnapshotRefusesAWorldEntryThatIsNoLongerCurrent() { + AtomicReference> source = + new AtomicReference<>(List.of(worldWithRealm("demo", "production", 7L, true))); + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(source::get); + GameplayWorldCatalog.WorldView selectedWorld = catalog.discoverySnapshot().worlds().getFirst(); + source.set(List.of(worldWithRealm("other", "production", 7L, true))); + + assertThat(catalog.realmDiscoverySnapshot(selectedWorld)).isEmpty(); + } + @Test void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { GameplayWorldCatalog catalog = @@ -823,6 +1142,97 @@ void numericWorldSelectionUsesTheSameFilteredSetAsWorldBrowsePresentation() { assertThat(catalog.resolveWorld("invalid")).isPresent(); } + private static GameplayWorldCatalog.RealmView realmView( + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + String characterCreationPolicy) { + UUID realmId = stableId("realm/" + tenantId + "/demo/" + realmSlug); + return new GameplayWorldCatalog.RealmView( + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + false, + "SHARED", + characterCreationPolicy, + 1L, + realmId, + stableId("namespace/" + realmId)); + } + + private static GameplayWorldCatalog.RealmView copyRealm( + GameplayWorldCatalog.RealmView realm, + long tenantId, + String realmSlug, + long gameInstanceId, + long pointerVersion, + String characterCreationPolicy, + UUID realmId, + UUID playableStateNamespaceId) { + return copyRealm( + realm, + tenantId, + realmSlug, + gameInstanceId, + pointerVersion, + characterCreationPolicy, + realmId, + playableStateNamespaceId, + realm.catalogRevision()); + } + + private static GameplayWorldCatalog.RealmView copyRealm( + GameplayWorldCatalog.RealmView realm, + long tenantId, + String realmSlug, + long gameInstanceId, + long pointerVersion, + String characterCreationPolicy, + UUID realmId, + UUID playableStateNamespaceId, + long catalogRevision) { + return new GameplayWorldCatalog.RealmView( + realmSlug, + realm.displayName(), + tenantId, + gameInstanceId, + pointerVersion, + realm.visible(), + realm.publicProductionRealm(), + realm.requiresCharacterSelection(), + realm.stateScope(), + characterCreationPolicy, + catalogRevision, + realmId, + playableStateNamespaceId); + } + + private static GameplayWorldCatalog.RealmView copyRealmWithStateScope( + GameplayWorldCatalog.RealmView realm, String stateScope) { + return new GameplayWorldCatalog.RealmView( + realm.slug(), + realm.displayName(), + realm.tenantId(), + realm.gameInstanceId(), + realm.pointerVersion(), + realm.visible(), + realm.publicProductionRealm(), + realm.requiresCharacterSelection(), + stateScope, + realm.characterCreationPolicy(), + realm.catalogRevision(), + realm.realmId(), + realm.playableStateNamespaceId()); + } + 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/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 960328343f..27a57c951d 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 @@ -31,6 +31,17 @@ void helpWithoutTopicShowsTopicIndex() { assertTrue(result.outputs().get(0).text().contains("HELP EQUIPMENT")); } + @Test + void helpDoesNotAdvertiseOrDescribeTheUnregisteredJoinCommand() { + var index = handler.handle(new TextCommand(TextCommandType.HELP, List.of(), "HELP")); + assertTrue(index.commandResult().accepted()); + assertFalse(index.outputs().get(0).text().contains("HELP JOIN")); + + var topic = handler.handle(new TextCommand(TextCommandType.HELP, List.of("join"), "HELP join")); + assertFalse(topic.commandResult().accepted()); + assertEquals("HELP_UNKNOWN_TOPIC", topic.commandResult().errorCode()); + } + @Test void helpWhoTopicExplainsGameplayOnlyScope() { TextCommandInterpretationResult result = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java index d04e27eebb..d2f96625bc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java @@ -27,7 +27,8 @@ void publishesCommandEventForGameplayScopedHelp() { "session-1", new TextCommand(TextCommandType.HELP, List.of("who"), "HELP who"), false, - Optional.of(context))); + Optional.of(context), + Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); Mockito.verify(scriptEventPublisher) @@ -49,6 +50,7 @@ void skipsCommandEventWithoutGameplayContext() { "session-1", new TextCommand(TextCommandType.HELP, List.of(), "HELP"), false, + Optional.empty(), Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java index 90375533e2..ebdc42ccfd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java @@ -46,7 +46,8 @@ void dispatchesToHistoryHandler() { "HISTORY", new TextCommandPayload.HistoryRequest(2)), false, - Optional.of(context))); + Optional.of(context), + Optional.empty())); assertThat(handler.group()).isEqualTo(TextCommandDispatchGroup.HISTORY); assertThat(result.commandResult().accepted()).isTrue(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookTextCommandDispatchHandlerTest.java index 8a1138631d..0090092377 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookTextCommandDispatchHandlerTest.java @@ -40,6 +40,7 @@ void usesParsedViewPayloadForQuickLookShape() { LOOK_LINE, new TextCommandPayload.ViewRequest(LOOK_LINE, false)), false, + Optional.empty(), Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransportTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransportTest.java new file mode 100644 index 0000000000..10f4f08f03 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransportTest.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.gamesession.command.text; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class ObservedDirectTextTransportTest { + private static final String PROXY_CONNECTION_ID = "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"; + + @Test + void acceptsOnlyCanonicalNonNilUuidV4ObservedInTrustedProxyMode() { + assertThat( + ObservedDirectTextTransport.fromHandshake( + "trusted_tcp_proxy", "41", PROXY_CONNECTION_ID)) + .contains(new ObservedDirectTextTransport("41", UUID.fromString(PROXY_CONNECTION_ID))); + assertThat( + ObservedDirectTextTransport.fromHandshake( + "trusted_tcp_proxy", "41", "00000000-0000-0000-0000-000000000000")) + .isEmpty(); + assertThat( + ObservedDirectTextTransport.fromHandshake( + "trusted_tcp_proxy", "41", "9fb38c88-2f1d-12aa-8e0b-7eb69caf8814")) + .isEmpty(); + assertThat( + ObservedDirectTextTransport.fromHandshake("first_party_web", "41", PROXY_CONNECTION_ID)) + .isEmpty(); + } + + @Test + void constructorRejectsNonNumericTransportIdAndNonV4ProxyId() { + assertThatThrownBy( + () -> + new ObservedDirectTextTransport( + "transport-hash", UUID.fromString(PROXY_CONNECTION_ID))) + .isInstanceOf(IllegalArgumentException.class); + for (String invalidSession : List.of("0", "-1", "9223372036854775808")) { + assertThat( + ObservedDirectTextTransport.fromHandshake( + "trusted_tcp_proxy", invalidSession, PROXY_CONNECTION_ID)) + .isEmpty(); + } + assertThatThrownBy( + () -> + new ObservedDirectTextTransport( + "41", UUID.fromString("00000000-0000-0000-0000-000000000000"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void dispatchRequestRejectsObservationBoundToDifferentSessionId() { + ObservedDirectTextTransport observed = + new ObservedDirectTextTransport("41", UUID.fromString(PROXY_CONNECTION_ID)); + + assertThatThrownBy( + () -> + new TextCommandDispatchRequest( + "42", + new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), + false, + Optional.empty(), + Optional.of(observed))) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandDispatcherTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandDispatcherTest.java index 20d55fd7a6..3878852568 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandDispatcherTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandDispatcherTest.java @@ -31,6 +31,7 @@ void dispatchRoutesToRegisteredGroupHandler() { new TextCommand( TextCommandType.HELP, List.of(), "HELP", "HELP", new TextCommandPayload.None()), false, + Optional.empty(), Optional.empty())); assertEquals(expected.commandResult(), actual.commandResult()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java index ad8a6add09..0d3403d9ff 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java @@ -5,20 +5,23 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.presentation.PromptComposer; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; -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 TextCommandInterpreterDispatchSeamTest { - @Test - void interpretUsesRegistryAndDispatcherInsteadOfCommandTypeBranches() { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void interpretUsesRegistryAndDispatcherInsteadOfCommandTypeBranches(boolean observedTransport) { SessionAuthenticationService authenticationService = Mockito.mock(SessionAuthenticationService.class); SessionContext gameplayContext = @@ -30,6 +33,8 @@ void interpretUsesRegistryAndDispatcherInsteadOfCommandTypeBranches() { PromptComposer promptComposer = Mockito.mock(PromptComposer.class); AtomicReference dispatchedGroup = new AtomicReference<>(); AtomicReference dispatchedType = new AtomicReference<>(); + AtomicReference> dispatchedObservation = + new AtomicReference<>(); TextCommandInterpretationResult expectedDispatchResult = new TextCommandInterpretationResult( CommandEnqueueResult.success(), List.of(PlayerOutput.notice("handled-by-help-group"))); @@ -47,6 +52,7 @@ public TextCommandInterpretationResult handle( TextCommandDispatchRequest request) { dispatchedGroup.set(group()); dispatchedType.set(request.command().type()); + dispatchedObservation.set(request.observedDirectTextTransport()); return expectedDispatchResult; } })); @@ -81,10 +87,19 @@ public Optional findDefinitionByAlias(String alias) { dispatcher, commandHistoryRecorder); - TextCommandInterpretationResult actual = interpreter.interpret("1", "LOOK", false); + ObservedDirectTextTransport observed = + new ObservedDirectTextTransport( + "1", UUID.fromString("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814")); + TextCommandInterpretationResult actual = + observedTransport + ? interpreter.interpret( + "1", new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"), false, observed) + : interpreter.interpret("1", "LOOK", false); assertEquals(TextCommandDispatchGroup.HELP, dispatchedGroup.get()); assertEquals(TextCommandType.LOOK, dispatchedType.get()); + assertEquals( + observedTransport ? Optional.of(observed) : Optional.empty(), dispatchedObservation.get()); assertEquals(expectedDispatchResult.commandResult(), actual.commandResult()); assertEquals(expectedDispatchResult.outputs(), actual.outputs()); assertEquals( 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..119eca5a11 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,43 @@ void parsesOneArgumentLoginAsEmailChallengeRequest() { assertEquals("demo@example.com", payload.email()); } + @Test + void parsesJoinAsOneUnmodifiedWorldSelector() { + TextCommand command = parser.parse("JOIN Tenant-A/World-A"); + + assertEquals(TextCommandType.JOIN, command.type()); + assertEquals("join", command.commandId()); + assertEquals("JOIN", command.aliasUsed()); + assertEquals(List.of("Tenant-A/World-A"), command.args()); + assertEquals(new TextCommandPayload.JoinRequest("Tenant-A/World-A"), command.payload()); + } + + @Test + void requiresExactlyOneJoinWorldSelector() { + TextCommand missingSelector = parser.parse("JOIN"); + TextCommand extraArguments = parser.parse("JOIN tenant-a/world-a production"); + + assertEquals(TextCommandType.JOIN, missingSelector.type()); + assertTrue(missingSelector.payload() instanceof TextCommandPayload.Tokens); + assertEquals(TextCommandType.JOIN, extraArguments.type()); + assertEquals(List.of("tenant-a/world-a", "production"), extraArguments.args()); + assertTrue(extraArguments.payload() instanceof TextCommandPayload.Tokens); + } + + @Test + void registersJoinAsLoginStageNonpromptingMetaCommand() { + TextCommandDefinition definition = + new BuiltInTextCommandDefinitionProvider() + .definitions().stream() + .filter(candidate -> candidate.type() == TextCommandType.JOIN) + .findFirst() + .orElseThrow(); + + assertEquals(TextCommandStageRequirement.LOGIN, definition.stageRequirement()); + assertEquals(TextCommandPromptPolicy.NEVER, definition.promptPolicy()); + assertEquals(TextCommandActionCategory.META, definition.actionCategory()); + } + @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/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index a1b282b348..f8b0aea263 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 @@ -34,6 +34,30 @@ class WorldsTextCommandDispatchHandlerTest { entityManagementClient), scriptEventPublisher); + @Test + void preparedJoinExplicitlyRefusesWithoutDiscoveryOrGameplayEffects() { + var command = new TextCommandParser().parse("JOIN 1"); + assertThat(command.type()).isEqualTo(TextCommandType.JOIN); + var result = + handler.handle( + new TextCommandDispatchRequest( + "session-1", + command, + false, + Optional.of(GameplayCommandTestFixtures.authoredDispatchEmberline()), + Optional.empty())); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("FEATURE_UNAVAILABLE"); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> + assertThat(output.text()) + .isEqualTo("ERROR FEATURE_UNAVAILABLE JOIN is not available.")); + Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + } + @Test void publishesCommandEventForGameplayScopedWorldsBrowse() { SessionContext context = GameplayCommandTestFixtures.authoredDispatchEmberline(); @@ -44,7 +68,8 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { "session-1", new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), false, - Optional.of(context))); + Optional.of(context), + Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) @@ -73,7 +98,8 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { "session-1", new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo"), false, - Optional.of(context))); + Optional.of(context), + Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) @@ -117,7 +143,8 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { "session-1", new TextCommand(TextCommandType.CHARS, List.of("demo"), "CHARS demo"), false, - Optional.of(context))); + Optional.of(context), + Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) @@ -147,6 +174,7 @@ void skipsCommandEventWithoutGameplayContext() { "session-1", new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), false, + Optional.empty(), Optional.empty())); assertThat(result.commandResult().accepted()).isTrue(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java new file mode 100644 index 0000000000..f63063eb72 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -0,0 +1,683 @@ +package unit.net.firedevops.firemud.gamesession.service.directtext; + +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.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin.State; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +/** + * Controlled Account-result/custody/repository fixtures, NOT authenticated ingress or SQL proof. + */ +class DirectTextAuthenticatedLobbyTest { + private static final Instant NOW = Instant.parse("2026-11-01T12:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void codecPreservesWholeIdentityTargetAndOriginalAccountTimesWithoutPrivateBytes() { + var f = new Fixture(); + byte[] bytes = f.scope.encode(); + var restored = DirectTextAuthenticatedLobbyScope.decode(bytes); + assertThat(restored.encode()).containsExactly(bytes); + assertThat(restored.evidence()).isEqualTo(f.result.evidence()); + assertThat(restored.publicTarget()).isEqualTo(f.scope.publicTarget()); + assertThat(restored.transport()).isEqualTo(f.transport); + assertThat(restored.issued().evaluatedAt()).isEqualTo(NOW.minusSeconds(1).toString()); + assertThat(restored.issued().connectScopeExpiresAt()).isEqualTo(NOW.plusSeconds(60).toString()); + assertThat(new String(bytes, StandardCharsets.UTF_8)) + .doesNotContain("fixture-private-token", "password", "authToken", "compactJwt"); + // Historical decode after expiry is still possible, but use cannot renew its deadline. + assertThatThrownBy( + () -> + restored.requireCurrent( + f.original, + f.result, + f.transport, + Clock.fixed(NOW.plusSeconds(60), ZoneOffset.UTC))) + .isInstanceOf(IllegalArgumentException.class); + verify(f.result, never()).close(); + } + + @ParameterizedTest + @ValueSource( + strings = {"duplicate", "unknown", "trailing", "coerced", "missing", "malformed", "oversize"}) + void codecRefusesNoncanonicalOrUnboundedState(String change) { + var f = new Fixture(); + String text = new String(f.scope.encode(), StandardCharsets.UTF_8); + byte[] bytes = + switch (change) { + case "duplicate" -> + text.replace("\"schema\":", "\"schema\":\"duplicate\",\"schema\":") + .getBytes(StandardCharsets.UTF_8); + case "unknown" -> + text.replaceFirst("\\{", "{\"credential\":\"untrusted\",") + .getBytes(StandardCharsets.UTF_8); + case "trailing" -> (text + "{}").getBytes(StandardCharsets.UTF_8); + case "coerced" -> + text.replace("\"gameInstanceId\":202", "\"gameInstanceId\":\"202\"") + .getBytes(StandardCharsets.UTF_8); + case "missing" -> + text.replace("\"expectedPriorPointerVersion\":null,", "") + .getBytes(StandardCharsets.UTF_8); + case "oversize" -> new byte[DirectTextAuthenticatedLobbyScope.MAX_BYTES + 1]; + default -> new byte[] {(byte) 0xc3, (byte) 0x28}; + }; + assertThatThrownBy(() -> DirectTextAuthenticatedLobbyScope.decode(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"0", "-1", "01", "+1", "9223372036854775808"}) + void positiveReplyRejectsNoncanonicalOrOverflowingAccountMembershipIds(String membershipId) { + var f = new Fixture(); + var response = positive().toBuilder().setMembershipId(membershipId).build(); + assertThatThrownBy( + () -> DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void positiveReplyPreservesTheFullPositiveAccountBigintBoundary() { + var f = new Fixture(); + var response = positive().toBuilder().setMembershipId(Long.toString(Long.MAX_VALUE)).build(); + assertThat(DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) + .isEqualTo(response); + } + + @Test + void frozenRequestKeepsTransportCorrelationSeparateFromProxyOriginalContextAndJoinIds() { + var f = new Fixture(); + var context = f.frozen.request().getPlayerContext(); + assertThat(context.getSessionId()) + .isEqualTo(f.transport.transportSessionId()) + .isEqualTo("00042"); + assertThat(context.getRequestId()).isEqualTo(f.frozen.request().getRequestId()); + assertThat( + List.of( + context.getSessionId(), + f.original.callerContextId().toString(), + f.transport.proxyConnectionId().toString(), + f.original.requestId().toString(), + f.scope.recordId().toString(), + context.getRequestId())) + .doesNotHaveDuplicates(); + } + + @Test + void maximumNonAsciiOpaqueScopeIdRoundTripsExactlyInFrozenRequest() { + var f = new Fixture(); + String opaqueId = "\u4e16".repeat(2048); + assertThat(opaqueId).hasSize(2048); + assertThat(opaqueId.getBytes(StandardCharsets.UTF_8)).hasSize(6144); + var response = scopeResponse().toBuilder().setConnectScopeId(opaqueId).build(); + var scope = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + InitialGameplayLoginContextState.installed(f.original, f.result), + f.transport, + f.scope.publicTarget(), + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT.toString(), f.scope.issued().target(), response, CLOCK)); + var retainedScope = DirectTextAuthenticatedLobbyScope.decode(scope.encode()); + var frozen = + new DirectTextAuthenticatedLobbyJoin( + retainedScope, + DirectTextAuthenticatedLobbyJoin.requestFor(retainedScope, UUID.randomUUID()), + State.NEVER_DISPATCHED, + Optional.empty()); + byte[] bytes = frozen.request().toByteArray(); + assertThat(bytes.length) + .isGreaterThan(4096) + .isLessThanOrEqualTo(DirectTextAuthenticatedLobbyJoin.MAX_REQUEST_BYTES); + var restoredRequest = DirectTextAuthenticatedLobbyJoin.decodeRequest(bytes); + var restored = + new DirectTextAuthenticatedLobbyJoin( + retainedScope, restoredRequest, State.NEVER_DISPATCHED, Optional.empty()); + assertThat(restored.request()).isEqualTo(frozen.request()); + assertThat(restored.request().toByteArray()).containsExactly(bytes); + assertThat(retainedScope.issued().connectScopeId()).isEqualTo(opaqueId); + assertThat(restored.request().getConnectScopeId().getBytes(StandardCharsets.UTF_8)) + .containsExactly(opaqueId.getBytes(StandardCharsets.UTF_8)); + } + + @Test + void scopeEncodingRefusesOverBoundEnvelopeAfterSuccessfulConstruction() { + var f = new Fixture(); + // Only display text grows; routing selectors and every constructor-validated identity stay + // valid. + // The display has fewer UTF16 code units than MAX_BYTES but exceeds it as UTF8 before headers. + String display = "\u4e16".repeat(DirectTextAuthenticatedLobbyScope.MAX_BYTES / 3 + 1); + var target = target(display); + var oversized = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + InitialGameplayLoginContextState.installed(f.original, f.result), + f.transport, + target, + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT.toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + scopeResponse(), + CLOCK)); + assertThat(oversized.publicTarget().worldDisplayName()).isEqualTo(display); + assertThatThrownBy(oversized::encode).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnknownHiddenAndDuplicateProtobufData() { + var f = new Fixture(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var request = f.frozen.request(); + assertThatThrownBy( + () -> + DirectTextAuthenticatedLobbyJoin.decodeRequest( + request.toBuilder().setUnknownFields(unknown).build().toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var hidden = + request.toBuilder() + .setPlayerContext( + request.getPlayerContext().toBuilder().setCharacterId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> + new DirectTextAuthenticatedLobbyJoin( + f.scope, hidden, State.NEVER_DISPATCHED, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + byte[] duplicate = new byte[request.getSerializedSize() * 2]; + System.arraycopy(request.toByteArray(), 0, duplicate, 0, request.getSerializedSize()); + System.arraycopy( + request.toByteArray(), + 0, + duplicate, + request.getSerializedSize(), + request.getSerializedSize()); + assertThatThrownBy(() -> DirectTextAuthenticatedLobbyJoin.decodeRequest(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + for (UUID reused : + List.of( + f.original.requestId(), + f.original.callerContextId(), + f.scope.recordId(), + f.transport.proxyConnectionId(), + f.result.evidence().tokenJti())) { + assertThatThrownBy( + () -> + new DirectTextAuthenticatedLobbyJoin( + f.scope, + DirectTextAuthenticatedLobbyJoin.requestFor(f.scope, reused), + State.NEVER_DISPATCHED, + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void onlyGenuineSelectionCanIssueScopeAndAnUnknownIssuanceIsNeverRetried() { + var f = new Fixture(); + when(f.selection.resolve(null, "private")).thenReturn(Optional.empty()); + assertThatThrownBy(() -> f.owner.realms(f.original, f.result, f.custody, null, "private")) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(f.account); + when(f.selection.resolve(null, "public")).thenReturn(Optional.of(f.scope.publicTarget())); + when(f.account.issueDirectTextConnectScope(any(), any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE")) + .build()); + assertThatThrownBy(() -> f.owner.realms(f.original, f.result, f.custody, null, "public")) + .isInstanceOf(IllegalArgumentException.class); + verify(f.account, times(1)).issueDirectTextConnectScope(any(), any()); + verify(f.repository, never()).retainScope(any(), any(), any()); + } + + @Test + void freshScopeIsRetainedAndIndependentlyReadAfterCommit() { + var f = new Fixture(); + when(f.selection.resolve(null, "public")).thenReturn(Optional.of(f.scope.publicTarget())); + when(f.account.issueDirectTextConnectScope(any(), any())).thenReturn(scopeResponse()); + when(f.repository.readCommittedScope(any())) + .thenAnswer( + call -> { + assertThat(f.events.getLast()).isEqualTo("COMMIT"); + return call.getArgument(0); + }); + var retained = f.owner.realms(f.original, f.result, f.custody, null, "public"); + assertThat(retained.issued().evaluatedAt()).isEqualTo(scopeResponse().getEvaluatedAt()); + assertThat(retained.issued().connectScopeExpiresAt()) + .isEqualTo(scopeResponse().getConnectScopeExpiresAt()); + verify(f.repository).retainScope(retained, f.result, CLOCK); + } + + @Test + void accountEvaluationAheadOfGameSessionClockIsRetainedExactlyWhileLoginRemainsLive() { + Clock gameSessionClock = Clock.fixed(NOW.minusMillis(30), ZoneOffset.UTC); + var f = new Fixture(gameSessionClock); + var accountScope = scopeResponse().toBuilder().setEvaluatedAt(NOW.toString()).build(); + when(f.selection.resolve(null, "public")).thenReturn(Optional.of(f.scope.publicTarget())); + when(f.account.issueDirectTextConnectScope(any(), any())).thenReturn(accountScope); + when(f.repository.readCommittedScope(any())).thenAnswer(call -> call.getArgument(0)); + + var retained = f.owner.realms(f.original, f.result, f.custody, null, "public"); + + assertThat(retained.issued().evaluatedAt()).isEqualTo(accountScope.getEvaluatedAt()); + assertThat(retained.issued().connectScopeExpiresAt()) + .isEqualTo(accountScope.getConnectScopeExpiresAt()); + verify(f.repository).retainScope(retained, f.result, gameSessionClock); + } + + @ParameterizedTest + @ValueSource(strings = {"issuedAt", "notBefore"}) + void futureLoginTimestampDeniesRealmPreparationBeforeEffects(String futureClaim) { + var f = new Fixture(); + long future = NOW.plusSeconds(1).getEpochSecond(); + long issuedAt = futureClaim.equals("issuedAt") ? future : NOW.minusSeconds(2).getEpochSecond(); + long notBefore = + futureClaim.equals("notBefore") ? future : NOW.minusSeconds(2).getEpochSecond(); + when(f.result.evidence()).thenReturn(evidence(f.original, issuedAt, notBefore)); + + assertThatThrownBy(() -> f.owner.realms(f.original, f.result, f.custody, null, "public")) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(f.repository, f.account, f.selection); + } + + @Test + void committedExactRequestAndPossibleStatePrecedeAccountAndReplyPersistence() { + var f = new Fixture(); + when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + assertThat(f.events) + .containsSubsequence("FREEZE", "COMMIT", "READ", "CLAIM", "COMMIT", "READ"); + assertThat( + call.getArgument( + 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)) + .isEqualTo(f.frozen.request().getPlayerContext()); + var context = + call.getArgument( + 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + assertThat(context.getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(context.getSessionId()).isEqualTo(f.transport.transportSessionId()); + assertThat(call.getArgument(1, String.class)) + .isEqualTo(f.scope.issued().connectScopeId()); + assertThat(call.getArgument(2, String.class)) + .isEqualTo(f.frozen.request().getRequestId()); + return positive(); + }); + var observation = f.owner.join(f.original, f.result, f.custody); + assertThat(observation.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); + assertThat(observation.currentReply()).contains(positive()); + verify(f.account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + verify(f.result, never()).close(); + verify(f.account, never()).authenticate(any(), any()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "AUTH_UNAVAILABLE", + "CONNECT_SCOPE_INVALID", + "JOIN_FAILED", + "INVALID_ARGUMENT", + "IDEMPOTENCY_CONFLICT" + }) + void genericErrorsNeverFabricateTerminalCompletionOrRearm(String code) { + var f = new Fixture(); + when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode(code) + .setError(ErrorDetail.newBuilder().setCode(code)) + .build()); + var first = f.owner.join(f.original, f.result, f.custody); + var continuation = f.owner.join(f.original, f.result, f.custody); + assertThat(first.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + assertThat(continuation.requestId()).isEqualTo(first.requestId()); + verify(f.repository, never()).recordPositiveReply(any(), any(), any()); + verify(f.account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + + @Test + void positiveReplyAfterCustodyLossIsRetainedButNeverAppliedToReplacementTransport() { + var f = new Fixture(); + when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + f.resetAfterCallback.set( + true); // Controlled reset at callback exit, not real receiving proof. + return positive(); + }); + var observation = f.owner.join(f.original, f.result, f.custody); + assertThat(observation.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); + assertThat(observation.currentReply()).isEmpty(); + assertThat(f.retained.get().reply()).contains(positive()); + } + + @Test + void lostClaimCommitCannotDispatchOrAllocateACompetitor() { + var f = new Fixture(); + f.failClaimCommit.set(true); + assertThatThrownBy(() -> f.owner.join(f.original, f.result, f.custody)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(f.account); + assertThat(f.retained.get().state()).isEqualTo(State.DISPATCH_POSSIBLE); + f.failClaimCommit.set(false); + var continuation = f.owner.join(f.original, f.result, f.custody); + assertThat(continuation.requestId()).isEqualTo(f.frozen.requestId()); + verifyNoInteractions(f.account); + } + + @Test + void resetExpiredPrivateResultAndChangedTransportDenyBeforeEffects() { + var f = new Fixture(); + f.live.set(false); + assertThatThrownBy(() -> f.owner.join(f.original, f.result, f.custody)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(f.repository, f.account); + f.live.set(true); + assertThatThrownBy( + () -> + f.scope.requireCurrent( + f.original, + f.result, + new ObservedDirectTextTransport("42", f.transport.proxyConnectionId()), + CLOCK)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + f.scope.requireCurrent( + f.original, + f.result, + new ObservedDirectTextTransport("00042", UUID.randomUUID()), + CLOCK)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + f.scope.requireCurrent( + f.original, + f.result, + f.transport, + Clock.fixed(NOW.plusSeconds(120), ZoneOffset.UTC))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static final class Fixture { + final InitialGameplayLoginAttemptCoordinates original = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); + final ObservedDirectTextTransport transport = + new ObservedDirectTextTransport("00042", UUID.randomUUID()); + final CanonicalGameplayLoginResult result = mock(CanonicalGameplayLoginResult.class); + final DirectTextAuthenticatedLobbyRepository repository = + mock(DirectTextAuthenticatedLobbyRepository.class); + final DirectTextWorldSelectionService selection = mock(DirectTextWorldSelectionService.class); + final AccountClient account = mock(AccountClient.class); + final AtomicBoolean live = new AtomicBoolean(true); + final AtomicBoolean resetAfterCallback = new AtomicBoolean(); + final AtomicBoolean failClaimCommit = new AtomicBoolean(); + final List events = new ArrayList<>(); + final DirectTextAuthenticatedLobbyScope scope; + final DirectTextAuthenticatedLobbyJoin frozen; + final AtomicReference retained = new AtomicReference<>(); + final DirectTextAuthenticatedLobbyOwner owner; + final DirectTextAuthenticatedLobbyCustody custody = + new DirectTextAuthenticatedLobbyCustody() { + @Override + public T withCurrent( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult borrowed, + Function action) { + if (!live.get() || !original.equals(coordinates) || borrowed != result) + throw new IllegalStateException("Controlled custody unavailable"); + try { + return action.apply(transport); + } finally { + if (resetAfterCallback.get()) live.set(false); + } + } + }; + + Fixture() { + this(CLOCK); + } + + Fixture(Clock ownerClock) { + when(result.evidence()).thenReturn(evidence(original)); + when(result.compactJwtBytes()) + .thenAnswer(call -> "fixture-private-token".getBytes(StandardCharsets.US_ASCII)); + var target = target("Forest"); + scope = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + InitialGameplayLoginContextState.installed(original, result), + transport, + target, + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT.toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + scopeResponse(), + CLOCK)); + frozen = + new DirectTextAuthenticatedLobbyJoin( + scope, + DirectTextAuthenticatedLobbyJoin.requestFor(scope, UUID.randomUUID()), + State.NEVER_DISPATCHED, + Optional.empty()); + retained.set(frozen); + when(repository.current(any(), any(), any(), any())).thenReturn(scope); + when(repository.freezeCurrentJoin(any(), any(), any(), any())) + .thenAnswer( + call -> { + events.add("FREEZE"); + return retained.get(); + }); + when(repository.readCommittedJoin(any())) + .thenAnswer( + call -> { + events.add("READ"); + return retained.get(); + }); + when(repository.claimDispatch(any(), any(), any(), any())) + .thenAnswer( + call -> { + events.add("CLAIM"); + if (retained.get().state() != State.NEVER_DISPATCHED) return false; + retained.set( + new DirectTextAuthenticatedLobbyJoin( + scope, frozen.request(), State.DISPATCH_POSSIBLE, Optional.empty())); + return true; + }); + doAnswer( + call -> { + retained.set( + new DirectTextAuthenticatedLobbyJoin( + scope, + frozen.request(), + State.COMPLETED, + Optional.of(call.getArgument(2)))); + return null; + }) + .when(repository) + .recordPositiveReply(any(), any(), any()); + var transactions = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("COMMIT"); + if (failClaimCommit.get() && retained.get().state() == State.DISPATCH_POSSIBLE) + throw new IllegalStateException("Lost commit reply"); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("ROLLBACK"); + } + }; + owner = + new DirectTextAuthenticatedLobbyOwner( + repository, selection, account, transactions, ownerClock); + } + } + + private static CanonicalGameplayLoginResult.NonSecretEvidence evidence( + InitialGameplayLoginAttemptCoordinates original) { + return evidence( + original, NOW.minusSeconds(2).getEpochSecond(), NOW.minusSeconds(2).getEpochSecond()); + } + + private static CanonicalGameplayLoginResult.NonSecretEvidence evidence( + InitialGameplayLoginAttemptCoordinates original, long issuedAt, long notBefore) { + try { + return new CanonicalGameplayLoginResult.NonSecretEvidence( + ACCOUNT, + original.requestId(), + original.callerContextId(), + UUID.randomUUID(), + "a".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + issuedAt, + notBefore, + NOW.plusSeconds(120).getEpochSecond(), + "1", + "5", + canonical(GameSessionAccountDelegationProfile.authorityTuple(1, 1)), + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/firemud-account-service", + "outboxSequence", + "0"))), + canonical(List.of())); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } + + private static IssueDirectTextConnectScopeResponse scopeResponse() { + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-account-scope") + .setEvaluatedAt(NOW.minusSeconds(1).toString()) + .setConnectScopeExpiresAt(NOW.plusSeconds(60).toString()) + .build(); + } + + private static JoinPublicProductionMembershipResponse positive() { + return JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(ACCOUNT.toString()) + .setTenantId("101") + .setMembershipId("90") + .setMembershipVersion(3) + .setMembershipAuthorityGeneration(1) + .build(); + } + + private static CanonicalPlayableTarget target(String display) { + return new CanonicalPlayableTarget( + "gameplay", + "studio", + UUID.randomUUID(), + "forest", + display, + UUID.randomUUID(), + "public", + "Live", + 101, + 202, + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + UUID.randomUUID(), + 303, + 1, + 7, + "d".repeat(64), + 82, + "original-open", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "c".repeat(64), + 27, + "sha256:" + "f".repeat(64), + Outcome.COMMITTED, + false, + NOW.minusSeconds(1), + "ALLOW_NEW"); + } +} 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 98ef32ffcd..355b80bda2 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 @@ -1,7 +1,9 @@ package net.firedevops.firemud.gamesession.websocket; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; @@ -17,6 +19,7 @@ import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.gamesession.command.text.LookCommandHandler; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpreter; @@ -152,6 +155,68 @@ void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected( verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void carriesObservedTrustedProxyTransportThroughTextInterpretation() throws Exception { + var observed = + new ObservedDirectTextTransport( + "41", UUID.fromString("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814")); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + GameSessionWebSocketHandshakeInterceptor.OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR, + observed)); + TextCommand command = new TextCommand(TextCommandType.HELP, List.of(), "HELP"); + when(parser.parse("HELP")).thenReturn(command); + when(interpreter.interpret("41", command, false, observed)) + .thenReturn(new TextCommandInterpretationResult(CommandEnqueueResult.success())); + SessionContext context = GameplayCommandTestFixtures.bootstrapDemo(); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(context)); + when(promptBurstCoordinator.applyPromptWindow(any(), any(), any(), anyBoolean())) + .thenAnswer(invocation -> invocation.getArgument(2)); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + Mockito.nullable(String.class), + any(PresentationProperties.class), + any())) + .thenReturn("OK HELP"); + + handler.handleMessage(session, new TextMessage("HELP")); + + verify(interpreter).interpret("41", command, false, observed); + verify(interpreter, never()).interpret("41", command, false); + } + + @Test + void nullObservedDispatchResultNeverFallsBackToASecondDispatch() throws Exception { + var observed = + new ObservedDirectTextTransport( + "41", UUID.fromString("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814")); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + GameSessionWebSocketHandshakeInterceptor.OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR, + observed)); + TextCommand command = new TextCommand(TextCommandType.HELP, List.of(), "HELP"); + when(parser.parse("HELP")).thenReturn(command); + when(interpreter.interpret("41", command, false, observed)).thenReturn(null); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(GameplayCommandTestFixtures.bootstrapDemo())); + + assertThatThrownBy(() -> handler.handleMessage(session, new TextMessage("HELP"))) + .isInstanceOf(NullPointerException.class); + + verify(interpreter).interpret("41", command, false, observed); + verify(interpreter, never()).interpret("41", command, false); + } + @Test void messageStopsWhenFirstPartyBootstrapContextCannotBeRestored() throws Exception { var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); 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 b321bf58ef..2b71cd2638 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 @@ -4,6 +4,8 @@ import java.util.HashMap; import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import org.junit.jupiter.api.Test; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; @@ -78,4 +80,65 @@ void firstPartyHandoffDoesNotTreatRawRoutingHeadersAsLogicalAuthority() { GameSessionWebSocketHandshakeInterceptor.REALM_SLUG_ATTR, GameSessionWebSocketHandshakeInterceptor.POINTER_VERSION_ATTR); } + + @Test + void preservesCanonicalProxyConnectionIdOnlyForTrustedProxyMode() { + String proxyConnectionId = "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"; + MockHttpServletRequest servlet = new MockHttpServletRequest("GET", "/ws/game"); + servlet.addHeader( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_HEADER, "trusted_tcp_proxy"); + servlet.addHeader( + GameSessionWebSocketHandshakeInterceptor.PROXY_CONNECTION_HEADER, proxyConnectionId); + Map attributes = new HashMap<>(); + + interceptor.beforeHandshake( + new ServletServerHttpRequest(servlet), + new ServletServerHttpResponse(new MockHttpServletResponse()), + null, + attributes); + + ObservedDirectTextTransport observed = + (ObservedDirectTextTransport) + attributes.get( + GameSessionWebSocketHandshakeInterceptor.OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); + assertThat(observed.proxyConnectionId()).isEqualTo(UUID.fromString(proxyConnectionId)); + assertThat(observed.transportSessionId()) + .isEqualTo(attributes.get(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR)); + assertThat(observed.transportSessionId()).isNotEqualTo(proxyConnectionId); + } + + @Test + void omitsObservationForMalformedProxyIdOrNonProxyMode() { + assertNoObservation("trusted_tcp_proxy", "not-a-uuid"); + assertNoObservation("first_party_web", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); + assertNoObservation("trusted_tcp_proxy", "9FB38C88-2F1D-42AA-8E0B-7EB69CAF8814"); + assertNoObservation("trusted_tcp_proxy", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814", true); + } + + private void assertNoObservation(String mode, String proxyConnectionId) { + assertNoObservation(mode, proxyConnectionId, false); + } + + private void assertNoObservation( + String mode, String proxyConnectionId, boolean includeConnectContext) { + MockHttpServletRequest servlet = new MockHttpServletRequest("GET", "/ws/game"); + servlet.addHeader(GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_HEADER, mode); + servlet.addHeader( + GameSessionWebSocketHandshakeInterceptor.PROXY_CONNECTION_HEADER, proxyConnectionId); + if (includeConnectContext) { + servlet.addHeader( + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_HEADER, "untrusted-context"); + } + Map attributes = new HashMap<>(); + + interceptor.beforeHandshake( + new ServletServerHttpRequest(servlet), + new ServletServerHttpResponse(new MockHttpServletResponse()), + null, + attributes); + + assertThat(attributes) + .doesNotContainKey( + GameSessionWebSocketHandshakeInterceptor.OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); + } }