diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a9f2ecd4a..9d69e3b49f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -1012,7 +1011,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md index a47bd619b2..065cc8747b 100644 --- a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md +++ b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. The obsolete differently named writer RPC and service implementation remain removed. Game Session locally validates supplied lifecycle, authority-generation, membership-version, and evaluation-time fields; its response-classification branch returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so this local classification does not establish live `JOIN_REQUIRED` or successful composed public `PLAY`; the live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but live membership reads and its independent membership-version/authority-generation issuance rereads remain unavailable or unproved. A bounded Account-owned worker revisits `PENDING` intents for exact positive operation and membership/audit readback. PostgreSQL execution is unavailable locally, unknown-commit-outcome reconciliation and direct text-to-Logging end-to-end proof remain open. ADR 0025 does not claim complete runtime or production proof; see [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for owning detail. +The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. The obsolete differently named writer RPC and service implementation remain removed. Game Session locally validates supplied lifecycle, authority-generation, membership-version, and evaluation-time fields; its response-classification branch returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so this local classification does not establish live `JOIN_REQUIRED` or successful composed public `PLAY`; the live in-band membership failure maps to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the prior gameplay binding. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but live membership reads and its independent membership-version/authority-generation issuance rereads remain unavailable or unproved. A bounded Account-owned worker revisits `PENDING` intents for exact positive operation and membership/audit readback. PostgreSQL execution is unavailable locally, unknown-commit-outcome reconciliation and direct text-to-Logging end-to-end proof remain open. ADR 0025 does not claim complete runtime or production proof; see [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for owning detail. ## Decision Record diff --git a/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md b/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md index 835e1d2c3a..ca98c940ed 100644 --- a/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md +++ b/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted separation of global control-plane roles from gameplay authority is target state. Current global-role presence classification still has drift, and the regression test proving a normally joined global-role account remains an ordinary player is missing. No runtime completion is claimed by this ADR. +The accepted separation of global control-plane roles from gameplay authority is target state. Game Session's current presence classifier and the shared gameplay-specific claim helpers now ignore global roles, with focused ordinary-player regression proof; this does not establish completed Account-backed gameplay admission, which remains fail-closed pending typed runtime reads and tenant-scoped grant proof. No end-to-end runtime completion is claimed by this ADR. ## Decision Record @@ -22,7 +22,7 @@ The accepted separation of global control-plane roles from gameplay authority is ## Context -FireMUD has global `platformAdmin`, `support`, and `billingAdmin` roles for cross-tenant control-plane work. Those roles express platform operating responsibility, not tenant consent, player identity, or in-world authority. Existing target-state admission rules already prevent global roles from bypassing caller-bound gameplay membership, but current runtime presence classification can still translate a global `platformAdmin` role into an in-game `ADMIN` actor after the account joins normally. That leaks control-plane privilege into gameplay and weakens tenant autonomy. +FireMUD has global `platformAdmin`, `support`, and `billingAdmin` roles for cross-tenant control-plane work. Those roles express platform operating responsibility, not tenant consent, player identity, or in-world authority. Existing target-state admission rules prevent global roles from bypassing caller-bound gameplay membership. A past Game Session presence classifier could translate a global `platformAdmin` role into an in-game `ADMIN` actor after the account joined normally; the current classifier ignores global roles. Account-backed admission remains fail-closed while typed runtime reads and tenant-scoped grant evidence are unavailable, so this correction does not establish completed gameplay admission. The former behavior leaked control-plane privilege into gameplay and weakened tenant autonomy. Support impersonation or hidden live observation could make some investigations more convenient, but neither has a current product requirement. Both would create a privileged path into private player state, conversations, and tenant experiences that would require substantial privacy, audit, notification, and abuse controls. @@ -47,7 +47,7 @@ Support impersonation or hidden live observation could make some investigations - Tenant gameplay authority remains explicit and cannot be inherited accidentally from platform employment or operating access. - Global staff can reproduce ordinary player behavior by joining a public game normally, but they receive no special in-world access unless the tenant explicitly grants it. - Support investigations cannot inspect private live gameplay by impersonating a player or attaching invisibly. They depend on purpose-built diagnostics and control-plane evidence. -- Current global-role-to-presence elevation and its tests are implementation drift that must be removed. +- Past global-role-to-presence elevation and its tests were implementation drift. The current classifier ignores global roles; Account-backed admission remains fail-closed pending typed runtime reads and tenant-scoped grant evidence. - Operational emergency actions remain possible, but their APIs and audit records remain visibly separate from player action processing. ## Alternatives Considered diff --git a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md index 9888dd5240..f45b786822 100644 --- a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md +++ b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding, lacks the target namespace key and durable binding-generation contract end to end, and may emit region-exit lifecycle behavior even though takeover leaves the character in place. These are implementation gaps, not evidence for the old target. +Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding and lacks the target namespace key and durable binding-generation contract end to end. Game Session now suppresses a false region-exit event when takeover displaces the old session, but the complete atomic transfer and cross-service proof remain gaps, not evidence for the old target. ## Decision Record diff --git a/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md b/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md index 1cf6676e44..9f151d5191 100644 --- a/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md +++ b/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The repository implements substantial `LOGIN`/`PLAY`, Redis rebinding, bounded semantic recent context, durable command, TCP Proxy advisory-disconnect, and Gateway rebind seams. It does not yet prove the complete authenticated real-service replacement sequence, configured elapsed recovery bounds, lifecycle classification, presence convergence, or all stalled-input outcomes. The effective disconnected-resume window is resolved but not fully enforced, and explicit first-party logout can currently present retained context contrary to ADR 0019 and CMD-04. +The repository implements substantial `LOGIN`/`PLAY`, Redis rebinding, bounded semantic recent context, durable command, TCP Proxy advisory-disconnect, and Gateway rebind seams. Focused local proof shows that a fresh first-party `PLAY` after explicit logout does not replay retained context. It does not yet prove the complete authenticated real-service replacement sequence, configured elapsed recovery bounds, lifecycle classification, presence convergence, all stalled-input outcomes, or a durable terminal episode fence against concurrent and delayed replay. The effective disconnected-resume window is resolved but not fully enforced. ## Decision Record diff --git a/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md b/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md index 215b0fa52f..cf4c4ae14a 100644 --- a/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md +++ b/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The current implementation substantially persists replay-eligible structured entries in ordered `resume_transcript_entry` rows and uses Redis only as a best-effort cache. Existing proof covers significant durable retention and replay behavior, but it does not prove oversized-entry omission or omission-marker behavior; the current runtime may retain an oversized entry. It does not yet implement this decision completely: durable context is keyed by `gameInstanceId` rather than `playableStateNamespaceId`, the distinct durable `resumeContextGeneration` episode fence is not persisted or enforced, and a first-party explicit logout path can leave private context replayable. Previous documentation contradicted the implemented oversized-entry behavior; this decision resolves the target in favor of a strict ceiling without claiming complete envelope-accounting and marker proof. +The current implementation substantially persists replay-eligible structured entries in ordered `resume_transcript_entry` rows and uses Redis only as a best-effort cache. Existing proof covers significant durable retention and replay behavior, including focused local proof that fresh first-party `PLAY` after explicit logout does not replay retained entries, but it does not prove oversized-entry omission or omission-marker behavior; the current runtime may retain an oversized entry. It does not yet implement this decision completely: durable context is keyed by `gameInstanceId` rather than `playableStateNamespaceId`, and the distinct durable `resumeContextGeneration` episode fence is not persisted or enforced, leaving concurrent and delayed replay unproved. Previous documentation contradicted the implemented oversized-entry behavior; this decision resolves the target in favor of a strict ceiling without claiming complete envelope-accounting and marker proof. ## Decision Record diff --git a/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md b/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md index a1a331b3ef..d3c1ed03b9 100644 --- a/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md +++ b/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is not implemented. Persisted character rows and realm-aware listing are partial, but synthetic-ID fallbacks, fixed RPG-oriented fields, published entry-policy resolution, versioned descriptors/templates, policy-specific zero/one/many handling, and fork-local identity proof remain gaps. +This decision is not implemented. Game Session `PLAY` no longer synthesizes an actor ID or trusts a name-only lookup, and its local handler contains persisted account-roster selection code. The shared `EntityManagementClient.listCharactersByAccount` currently returns `CHARACTER_LIST_UNAVAILABLE` without issuing an Entity RPC, so runtime actor selection is unavailable. Namespace-qualified roster access and Account runtime admission reads remain unavailable pending typed caller/target authority; this is containment rather than a working actor-entry path. Direct-text `CHARS` is unavailable before the unsafe unqualified roster read. Fixed RPG-oriented fields, published entry-policy resolution, versioned descriptors/templates, policy-specific zero/one/many handling, and fork-local identity proof remain gaps. ## Decision Record @@ -98,9 +98,9 @@ Generalize the session to zero or many primary subjects immediately. This could ## Implementation and Proof Obligations -Current implementation is materially partial and drifted. Entity Management has persisted character rows and realm-aware listing, but the schema and creation surface still expose fixed RPG-oriented fields. Game Session's unresolved-character path may use `accountId` when no selector exists or derive an ID from a hash of tenant, runtime instance, and name. The richer versioned creation descriptor is absent, policy-specific pre-seeded and auto-provision flows are incomplete, and documentation has assigned character ownership inconsistently between Account and Entity. +Current implementation is materially partial and drifted. Entity Management has persisted character rows and a narrower account/runtime-scope list, but the schema and creation surface still expose fixed RPG-oriented fields. Game Session now rejects unresolved actors rather than deriving an ID from the account or a name hash, yet Entity's list request cannot bind the stable playable-state namespace or published policy snapshot. Account's current runtime reads deny admission before data access, and direct-text `CHARS` is unavailable until the owner-bound discovery contract exists. The richer versioned creation descriptor, policy-specific pre-seeded and auto-provision flows, and fork-local identity proof remain absent. -Implementation must remove synthetic ID fallbacks, make Entity allocation and account association mandatory, add explicit published entry-policy resolution, idempotent auto-provisioning, versioned descriptor validation, policy-specific zero/one/many roster handling, and distinct fork-local copy identity with optional provenance. Fixed legacy RPG columns must not remain mandatory platform semantics; implementation may migrate them into authored component state as the actor model converges. +Implementation must preserve the synthetic-ID rejection, make Entity allocation and exact namespace-qualified account association mandatory, add explicit published entry-policy resolution, idempotent auto-provisioning, versioned descriptor validation, policy-specific zero/one/many roster handling, and distinct fork-local copy identity with optional provenance. Fixed legacy RPG columns must not remain mandatory platform semantics; implementation may migrate them into authored component state as the actor model converges. Proof must cover all three policies; missing, stale, wrong-version, and malformed descriptors/templates; exact account, tenant, realm, and namespace association; zero, one, and multiple actor rosters; duplicate auto-provision, same-request replay/digest conflict, and distinct-request races with a deterministic persisted loser outcome and no second allocation; repeated creation and concurrent distinct-request `PLAYER_CREATED` attempts against the same zero roster; actor selection by another account; synthetic-ID rejection; non-RPG components; shared versus isolated realms; fork-copy identity and source-provenance non-authority; reconnect and takeover using persisted identity; and absence of cross-namespace mutation or merge-back. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 8c7bcb4dc2..e055af90f8 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -32,9 +32,11 @@ Hosted Creator Party/operator identity, terms catalog, acceptance/currentness ev The Account proto and producer response model declares `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; this is not a live runtime snapshot because current Account membership, entitlement, and grant gRPC handlers fail closed before reads when caller/target binding is unavailable. Game Session text `PLAY` validates exact account/tenant identity plus freshness, lifecycle, admission, membership version, authority generation, and evaluation time on supplied-authority branches. `ACTIVE` is required for admission; only fresh `MISSING` or `INACTIVE` membership can produce public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. Canonical eligibility and outcome mapping belong to [Authentication](../../system-architecture-authentication.md). The complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` remain absent. -Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist, but current connect-token issuance uses membership existence, admission, version, and evaluation-time evidence without enforcing the emitted lifecycle or authority-generation fields. It does not yet validate the full private/playtest target or perform the required membership-version/generation baseline reread at issuance; a replay-cache hit also returns before fresh authority reads. Character discovery applies its local membership/admission checks after entitlement and target checks. These paths do not create or restore membership. +Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist. Fresh connect-token issuance and successful cached-result replay now share checks for the exact current target/pointer, gameplay entitlement, and membership lifecycle/admission; a valid replay returns the stored token and immutable result without minting or updating cache/session state. The local issuance path still reads membership through the Account repository; that check is separate from the live `GetTenantMembershipForRuntime` gRPC reader, which currently rejects before data access. The implementation does not yet validate the full private/playtest target or enforce the required membership-version/authority-generation baseline reread. Character discovery applies its local membership/admission checks after entitlement and target checks. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity. These paths do not create or restore membership. -Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct text `JOIN` dispatcher is implemented locally; the Gateway guard blocks external exposure of the Account HTTP route and first-party `Join & Play` remains unavailable. A `PENDING` intent persists before entitlement work; unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` with no fabricated policy evidence. The bounded Account worker is readback-only and terminalizes only exact positive operation, scope, membership, and audit evidence; absent or uncertain evidence remains nonterminal with capped diagnostics and backoff, never terminalized by expiry or attempt limit. Registration/JOIN audit outbox records retain one identity through receiver retries, and Account's producer-side receipt validation and verified-projection marker handling are local code; the separate Logging & Admin receiver/readback is implemented locally in the composed child; PostgreSQL, end-to-end and finite-retention activation proof remain open; no exact PostgreSQL lost-acknowledgement/concurrency or direct text-to-Logging end-to-end proof is claimed. The target membership-generation snapshot at connect-token issuance remains unproved. Runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), with owner contracts in [Authentication](../../system-architecture-authentication.md) and [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). +Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct-text `JOIN` dispatcher is implemented locally; the Gateway blocks external exposure of the Account route and first-party `Join & Play` remains unavailable. Terminal replay requires the current authenticated caller, exact target, and matching immutable intent digest; a retained policy digest must also match only when Account bound one after entitlement evaluation. Terminal storage alone is not replay authority. A policy-independent `PENDING` intent persists before entitlement work. Unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` without fabricated policy evidence. The bounded Account worker is readback-only: it can terminalize only exact positive operation, scope, membership, and audit evidence; expiry, attempt limits, absent evidence, and uncertainty never terminalize or cause the worker to resubmit the expired bearer-bound request. Incomplete evidence remains pending with capped diagnostics and backoff. + +Producer-side receipt validation, verified-projection marker handling, and the composed Logging & Admin receiver/readback exist locally, but live `CreateLogEvent` returns `UNAVAILABLE` and Account audit delivery is unscheduled. New and outstanding audit rows therefore remain `PENDING`; receipt reads remain available, and readback does not upgrade historical rows with unknown projection provenance. Direct service/repository/job calls are offline fixture proof only. PostgreSQL lost-acknowledgement/concurrency, direct text-to-Logging end-to-end, and finite-retention activation proof remain open. The target membership-generation snapshot at connect-token issuance also remains unproved. Runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), with owner contracts in [Authentication](../../system-architecture-authentication.md) and [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). `GetAdmissionPointer` is a live Game Session RPC consumed by Account through `GameSessionClient`; broader reconnect/cutover consumption and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` when the tenant has zero or multiple subscription rows; focused cardinality/retry proof does not establish the full entitlement snapshot/freshness contract, including explicit free/trial rows, authoritative current-row selection, `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and delivery. `CommitTenantCapacityAdmission` has a synchronized target request/replay contract including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. @@ -60,7 +62,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. - **Target state:** global Account registration creates only global account/security state and a platform-scoped audit outbox entry in the same transaction; successful JOIN records a separate tenant-scoped event using its exact committed `tenantId`. Account preserves one stable event identity and envelope across retries. Logging & Admin owns the typed receipt, exact-payload digest, readback, minimized-evidence, and retention contract; see [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Logging & Admin is not a second authority for Account state. -- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; unavailable, timeout, mismatched, and ambiguous responses leave that identity `PENDING` and never mint a replacement. The composed Logging & Admin child implements exact payload-byte digest validation and durable readback locally; producer request/response validation alone remains insufficient runtime proof. PostgreSQL, end-to-end and finite-retention activation gates remain open under the [Logging owner contract](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). After a matching receipt supplies both terminal status and minimized evidence, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. +- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; offline fixture calls exercise retrying the same envelope and marking it delivered only after matching terminal status and minimized receipt evidence. Unavailable, timeout, mismatched, and ambiguous responses leave the identity `PENDING` and never mint a replacement. In production, Account audit delivery is unscheduled and Logging & Admin's `CreateLogEvent` returns `UNAVAILABLE`, so new and outstanding records remain `PENDING`; the composed child implements exact payload-byte digest validation and durable readback locally, but that fixture and producer request/response validation do not establish live delivery. PostgreSQL, end-to-end, and finite-retention activation gates remain open under the [Logging owner contract](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). After a matching terminal-status receipt with minimized evidence in the exercised path, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. - JOIN first commits a policy-independent `PENDING` intent; only an available entitlement result binds the policy digest, `allowPublicJoin`, and entitlement version for the membership/outbox/outcome transaction. An expired scope on a retained `PENDING` request returns retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation. The bounded Account reconciler is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence, while absent or uncertain evidence remains pending with capped diagnostics and backoff. It never reissues an expired scope or terminalizes by expiry or attempt limit. PostgreSQL unknown-outcome/concurrency proof remains open. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN append to the durable outbox and validate matching receipt responses as described above; the composed child supplies local receiver/readback implementation, while actual delivery/recovery activation still requires its versioned capability and outstanding runtime/retention proof. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). @@ -284,13 +286,13 @@ Account evaluates effective access as `min(grantExpiresAt, forkExpiresAt)` and e Grant `scopeId`, `outboxStreamKey`, and event `sourceScope` are produced and parsed through the [canonical grant authority-stream scope codec](../../system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). This document owns only the persistence and projection consequences; it does not define another stream grammar or fallback identity. -Current `AccountRealmAccessGrant` persistence and internal grant reads are limited to the legacy four-field identity, with only limited text `PLAY` denial; no lifecycle-bound read, expiry, fork-expiry evaluation, tenant-admin mutation surface, expected-revision CAS, request-replay record, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, or complete grant event proof exists. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). +Current `AccountRealmAccessGrant` persistence is limited to the legacy four-field identity; current Game Session grant gRPC reads fail with `FAILED_PRECONDITION` before data access, so downstream text `PLAY` does not reach grant evaluation. No lifecycle-bound read, expiry, fork-expiry evaluation, tenant-admin mutation surface, expected-revision CAS, request-replay record, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, or complete grant event proof exists. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). ### Runtime Implementation Status and Drift -Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance uses membership-existence, admission, version, and evaluation-time evidence; only missing membership on an eligible public-production target may produce `JOIN_REQUIRED`, while an existing non-admitting membership is denied. It does not yet enforce the emitted lifecycle/authority-generation baseline or the full private/playtest target, and a replay-cache hit returns before fresh authority reads. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. +Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Fresh connect-token issuance and successful cached-result replay share the current target/pointer, gameplay-entitlement, and membership lifecycle/admission checks; missing or `INACTIVE` membership on an eligible public-production target may produce `JOIN_REQUIRED`, while `ACTIVE` non-admitting membership is denied. The current path still does not validate the full private/playtest target or enforce the membership-version/authority-generation baseline reread. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. -Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers still fail closed before reads because their requests cannot prove caller/target binding, so those local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. AccountClient separately normalizes a transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`; that transport outcome does not describe the in-band denial. These local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Account-side Logging receipt validation is implemented; the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Reconnect flow consumption of admission-pointer truth remains incomplete; replacement cutover flow consumption remains incomplete, and operator pointer tooling is incomplete. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index abcc974307..05e2318f17 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -20,7 +20,11 @@ For logout and retained private semantic context, [ADR 0019](../../decisions/adr Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). -Current production `CHARS` and `PLAY` roster access is contained at the shared Entity client because the live `ListCharactersByAccount` request and `Character` response do not establish the stable playable-state namespace. A positive `gameInstanceId` is only a replaceable runtime fence and cannot stand in for durable actor identity. The client preserves the existing `CHARACTER_LIST_UNAVAILABLE` failure without dispatching the legacy RPC; `CHARS` remains unavailable and `PLAY` retains its existing identity-unavailable outcome. Positive handler fixtures are offline-only evidence for mapping and error behavior, not runtime namespace proof. This containment follows [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity API contract](../entity-management-service/api-contracts.md); it does not alter separate `WORLDS` or `REALMS` discovery. +The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. The live Account membership, entitlement, and grant gRPC readers return in-band `FAILED_PRECONDITION` before data access even for Game Session; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. These outcomes do not establish whether a membership, grant, or character exists. Supplied-authority handler fixtures are offline evidence only, not composed admission proof. + +The shared Entity roster request and `Character` response still do not establish the stable playable-state namespace or policy-qualified actor identity; a positive `gameInstanceId` is only a replaceable runtime fence. Account-scoped roster selection therefore cannot authorize production `PLAY`, and the legacy roster RPC is not dispatched from `CHARS`. This hardgate follows [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity API contract](../entity-management-service/api-contracts.md); it does not change `WORLDS` or `REALMS` discovery. + +Current text `WORLDS` and `REALMS` expose only visible public-production realms. A visible pointer alone does not prove private access; caller-bound current Account membership and grant authority are required, but those readers remain disabled, so private discovery and `PLAY` are not live. First-party `PLAY` does not treat a connect-context token or JWT role as gameplay or retained-context replay authority. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects because durable termination evidence is unavailable; separately, first-party private transcript replay is suppressed when durable termination evidence is unavailable and a fresh authoritative `LOOK` remains the current redraw. Durable logout episode/generation fencing, delayed-race proof, effective resume-window enforcement, and namespace-scoped takeover remain open. Current direct-text `REALMS` deliberately omits non-public entries because Account's runtime grant reader is slug-only and cannot prove the lifecycle-qualified target. Game Session skips those entries before membership, grant, entitlement, or scope dispatch and preserves public-production discovery and scope issuance. Guessed or unbound private character selectors retain the existing unknown-target projection; only a fresh caller-bound prior REALMS snapshot that resolves to the exact current private target reaches retryable `AUTH_UNAVAILABLE`, without Account or Entity dispatch. This containment does not change public `WORLDS`/`REALMS` or public character admission. The lifecycle-qualified grant contract remains owned by [Authentication](../../system-architecture-authentication.md#playtest-grant-admission-consequence). @@ -47,7 +51,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – Existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY`; first public-production entry requires explicit `JOIN`. Game Session direct-text `JOIN` dispatch and Account's explicit writer exist locally, but first-party `Join & Play` remains unavailable and the Gateway blocks the external Account route. Current `PLAY` requires fresh identity-matched lifecycle/version/generation evidence and validates positive grant/entitlement scope and freshness; only eligible public `MISSING` or `INACTIVE` membership may reach `JOIN_REQUIRED` after entitlement and public-policy checks. Account's live runtime readers fail closed before reads, so no composed live admission is established. Non-public denial is not converted to public JOIN advice; see [Implementation Status](#implementation-status) and [Authentication](../../system-architecture-authentication.md). Players may use lobby helpers such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – target behavior permits direct `PLAY` only for existing `ACTIVE` members and requires first-time public-production players to complete `JOIN`. The Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path exist locally, but Account runtime membership, entitlement, and grant reads return in-band `FAILED_PRECONDITION` before data access until typed caller/target binding is available. Text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; transport-level `StatusRuntimeException` is separately normalized by AccountClient to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED` and other membership classifications use supplied authority in focused tests. First-party browser `JOIN` remains unavailable because Gateway denies the target-only route. Direct-text end-to-end/PostgreSQL proof, pending-operation readback, and the independent connect-token issuance reread remain open. Current `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; players may use `REALMS` and `CHARS` to disambiguate selection only in the target flow. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -68,13 +72,13 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | ------- | ------- | ------- | | `LOGIN [secret]` | With one argument, requests a verified-email login code without authenticating the session. With a password or active email code as the second argument, authenticates immediately. The Gateway-routed first-party WebSocket route at `/ws/game/**` uses bare `LOGIN` after bootstrap/connect-token validation instead. | `LOGIN demo@example.com swordfish` | | `LOGON [secret]` | Exact alias for `LOGIN`. | `LOGON demo@example.com swordfish` | -| `LOGOUT` / `LOGOFF` / `QUIT` | Ends the current session and closes the transport. `LOGOFF` and `QUIT` are exact aliases for canonical `LOGOUT`. | `LOGOUT` | +| `LOGOUT` / `LOGOFF` / `QUIT` | Currently returns `LOGOUT_UNAVAILABLE` before side effects because durable termination evidence is unavailable. Target behavior ends the current session and closes the transport; `LOGOFF` and `QUIT` are exact aliases for canonical `LOGOUT`. | `LOGOUT` | | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | -| `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where target `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; target behavior never resolves a bare `worldSlug` globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Direct-text command implemented locally; target selector form and end-to-end/runtime proof remain incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. Current local input accepts a snapshot-bound `WORLDS` ordinal or a uniquely resolving bare world slug against the current catalog; the latter is implementation drift. The pointer projection lacks `tenantSlug`, so the target stable `tenantSlug/worldSlug` selector is unavailable. PostgreSQL/recovery and full direct-text/Telnet and first-party path proof remain open. | `JOIN 1` (from the current `WORLDS` response) | -| `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | -| `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | +| `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world. Target `` is the stable `tenantSlug/worldSlug` selector or a response-local menu index; a bare `tenantSlug` is accepted only when it exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. Current direct-text world and realm menu ordinals are bound to their exact response snapshots. | `REALMS demo/demo` | +| `JOIN ` | **Direct-text command implemented locally; end-to-end/runtime proof remains incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. Current input accepts the exact snapshot-bound `WORLDS` response ordinal or a uniquely resolving bare world slug; the latter is implementation drift. The pointer projection lacks `tenantSlug`, so the target stable `tenantSlug/worldSlug` selector is unavailable. PostgreSQL execution, pending-operation recovery, and full direct-text/Telnet and first-party path proof remain open. | `JOIN 1` (from the current `WORLDS` response) | +| `CHARS [realm]` | Target behavior requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. Current direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. | `CHARS demo/demo production` | +| `PLAY [realm] [character]` | Target behavior binds the authenticated connection after fresh discovery, `LOGIN`, and conditional membership/character gates. Players may omit `[realm]` or `[character]` only when fresh resolution is unambiguous; direct text never reuses a first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN`; a non-public path requires existing durable `membershipLifecycleState=ACTIVE` membership and the applicable grant. Supplied-authority tests cover conditional `JOIN_REQUIRED`, but Account membership, entitlement, and grant readers fail closed before data access, so no composed live admission or actionable `JOIN_REQUIRED` is established; current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | | `INVENTORY` / `INV HERE` | Lists carried items or the current room-ground item holder. The command is rendered by Game Session, but item state is read through Game Logic and Entity Management. | `INV HERE` | | `GET ` / `DROP ` | Moves a visible room-ground item into carried inventory, or a carried item into the current room. Game Session forwards the raw selector and quantity to Game Logic; Game Logic resolves names, visible refs, container refs, and stack refs before Entity Management mutates state. | `GET torch1` | @@ -172,8 +176,8 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – **Target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. -- `JOIN_REQUIRED` – canonical actionable advice only for an eligible public-production target after current routing and authority checks, when a fresh Account membership response matches the exact account/tenant, passes lifecycle/version/generation/evaluation-time validation, and reports missing (`membershipExists=false`/`membershipLifecycleState=MISSING`) or existing `INACTIVE` membership (`gameplayAdmissionAllowed=false`). Fresh entitlement must confirm gameplay availability and `allowPublicJoin=true`. `ACTIVE` but non-admitting membership gets no JOIN advice. The implemented direct-text `JOIN` is local; first-party `Join & Play` remains unavailable and direct-text/Telnet proof remains open. A grant or cached discovery result is not a substitute. Account runtime readers currently fail closed before data access, so no composed live `JOIN_REQUIRED` is established; the live membership failure maps to `WORLD_ACCESS_DENIED`. Canonical eligibility and ordering are owned by [Authentication](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). -- `WORLD_ACCESS_DENIED` – current denial for private, playtest, or other non-public targets whose membership/admission or existing grant check denies access; it offers no public join action. If the selected world is absent from public `WORLDS` discovery, current `PLAY` projects the definitive denial as generic `PLAY_SELECTION_REQUIRED` without target metadata; publicly discoverable worlds retain `WORLD_ACCESS_DENIED` (see [Implementation Status](#implementation-status)). +- `JOIN_REQUIRED` – canonical public-production advice only after the Authentication-owned routing, fresh authority, entitlement, and `allowPublicJoin` gates confirm missing or non-admitting `INACTIVE` membership. `ACTIVE` but non-admitting membership receives no JOIN advice. The local Account writer and Game Session dispatch exist, but Account runtime readers fail closed before data access, so supplied-authority classifications do not establish a composed live result; current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. +- `WORLD_ACCESS_DENIED` – current denial when the reachable admission path denies access, including private/playtest membership or grant denial. If the selected world is absent from public `WORLDS` discovery, the definitive denial is projected as generic `PLAY_SELECTION_REQUIRED` without target metadata; publicly discoverable worlds retain `WORLD_ACCESS_DENIED`. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. - `INVALID_ARGUMENT` – session ID parsing or other validation failed before the handler reached gameplay state. 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 739a60f36d..2679fe4c6d 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -32,11 +32,25 @@ The sections below define the target-state runtime contract. Current implementat - Current hosted wiring still exposes one generic `firemud.redis` connection to Game Session while the shared Helm profile sets `FIREMUD_REDIS_HOST=redis-cache`; the role-specific `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*` variables are not consumed by the common Redis auto-configuration. Consequently, the live Game Session tick/session coordination path is not proven to reach Coordination Redis in that profile and may share the Cache/Rate-Limit endpoint. This is implementation drift against ADR 0171, not a target-state role assignment; named role clients, endpoint-collision failure, and role-specific health/eviction proof remain required. - Current tick/session coordination also bypasses the target key/script boundary: `TickQueueControlService`/`TickServiceImpl` build untagged `gamesession:tick:*` keys and pass queue, pending, and lock keys together to Lua, while `RedisSessionContextService` performs watched multi-key writes across untagged `sessionctx:*` families. Those calls are not proven same-slot and can fail with `CROSSSLOT` on a supported Redis Cluster profile; the live families are not represented by the canonical builder/registry contract. This records current implementation/proof drift only; migration must use the canonical tagged builders, registered scripts, reset inventory, and fenced readback before claiming cluster support. - The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. -- The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and places it in the persisted `SessionContext.jwt` value, which is serialized into Redis by `RedisSessionContextService`. This contradicts the process-local/no-raw-delegation-JWT boundary in ADR 0031. The target binding must persist only bounded non-secret evidence such as the token hash or opaque rebind handle; stripping the token, fenced cleanup of existing values, and focused no-secret serialization proof remain implementation work. -- Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. Current player text handling rejects `LOGOUT` before side effects and gates private semantic transcript replay when durable termination proof is unavailable; fresh `LOOK` remains. This is fail-closed child behavior, not completion of the durable successor or either [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) or [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). +- The current `LOGIN` path receives Account's `game-session-account-delegation` JWT in process-local `SessionContext`, but `RedisSessionContextService` and `RedisMovementEffectIdempotencyService` strip it before new Redis writes and their readers do not return legacy raw values. This is new-write containment, not the ADR 0031 binding or complete at-rest correction: untouched Redis aliases and movement-effect replay values may still contain an earlier raw JWT until fenced cleanup or expiry, so inventory/readback and live serialization proof remain deployment prerequisites. The target binding persists only bounded non-secret evidence and an Account-issued opaque rebind handle. Gameplay presence remains `PLAYER`: JWT role claims never confer gameplay privilege, and cached elevated Redis roles project as `PLAYER` on reads and are demoted on activity/AFK writes. The positive Account-authenticated grant carrier and revocation proof remain unimplemented. +- Bounded reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, but private retained-context replay is currently suppressed when durable termination evidence is unavailable, and accepted `PLAY` renders a fresh `LOOK`. Text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; neither that rejection nor retaining transcript rows proves durable logout. Safe replay eligibility remains closed until exact current `resumeContextGeneration` and durable non-terminated episode/binding evidence are established, while the target logout path requires a durable episode fence and binding-termination compare-and-set before acknowledgement. Namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, exact append/restore checks, complete-envelope bounds and omission-marker convergence, cross-transport race proof, Redis/cache fencing, and PostgreSQL concurrency proof remain gaps under [ADR 0019](../../decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md) and [ADR 0134](../../decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). -- The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. +- The former Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration has been removed from the source chain. Its remote-followup target-instance/effect identity and gameplay-command recovery-index DDL are now direct SQL in Game Session's `V1__baseline.sql`, matching the canonical SQL-only migration input for shared jOOQ generation. This source convergence does not establish retained database history or data state; databases that may retain the former Java V8 application or pre-convergence child cardinality/index versions require exact deployed Flyway-history and data readback plus owner disposition before activation. +- Before activating against retained `gameplay_admission_pointer` data, run this read-only cardinality check for visible public-production realms: + + ```sql + SELECT tenant_id, COUNT(*) AS visible_public_production_realm_count + FROM gameplay_admission_pointer + WHERE visible AND public_production_realm + GROUP BY tenant_id + HAVING COUNT(*) > 1 + ORDER BY tenant_id; + ``` + + Any returned tenant blocks activation until an operator completes exact data readback and owner disposition. Do not automatically update or delete rows; the V12 constraint fails closed on duplicates. + +The child migration sequence is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index; V12/V13 preserve the child SQL bytes. Retained databases whose Flyway history records former child assignments (V7/V8/V9 cardinality or V9/V10 tenant lookup), including conflicting former child V11 cardinality/V12 lookup assignments, remain activation-blocked pending exact Flyway-history and data readback plus owner disposition. Do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail V12 rather than selecting or deleting a survivor. Before activation, require evidence of an acceptable V12 lock budget or quiescence and an actual V13 event-index build/write-lock budget measurement or quiescence; do not infer online write availability from a small table. ## Runtime Details @@ -198,7 +212,7 @@ Session shutdown therefore cleans up session keys but does not implicitly delete Game Session restores player sessions after disconnects and enforces single-session control as outlined in the [Reconnection Strategy](../../system-architecture-reconnection.md). For Telnet clients, it also consumes best-effort, at-least-once `NotifyDisconnect` events emitted by the TCP Proxy Service over an internal gRPC link and treats them as idempotent hints keyed by `` rather than a guaranteed source of truth. -Game Session persists the latest processed `disconnectSequence` per `` and ignores older or duplicate events so retry behavior at the proxy can remain simple while consumption stays idempotent. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory context that may be used for logging and audit, but they are not trusted as authorization claims or binding directives. Game Session still validates any game-instance ownership claims against Redis and its authenticated session state before rebinding the transport. **Current implementation gap:** the live `gamesession:notifydisconnect:dedup:` path fails open on Redis errors and is reset-loss-vulnerable; no current connection/generation binding guard runs before `NotifyDisconnect` presence or region-exit effects or `GameInstance` suspension. The live path therefore does not yet satisfy the target advisory safety contract. Until exact connection/generation binding and durable sequencing are proven, Redis loss/error must not authorize stale effects; see the [Redis reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). +Game Session currently records the latest processed `disconnectSequence` per `` and ignores older or duplicate hints, but the live `gamesession:notifydisconnect:dedup:` path fails open on Redis errors and is reset-loss-vulnerable. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory logging/audit context, not authorization or binding directives. The current `NotifyDisconnect` handler validates a supplied game-instance owner but does not mutate presence, region exit, relational lifecycle, or the shared Redis `GameInstance` snapshot: without a current connection/generation binding proof, even a validated target cannot authorize suspension. Exact connection/generation comparison, durable sequencing where required, and stale/duplicate/Redis-loss negative proof remain the ordered target before lifecycle effects can be enabled; see the [Redis reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Recent/offline account-presence state should preserve the last admitted routing bundle too. In target state, when live presence drops to recent presence after transport loss, takeover, or logout, the bounded recent-presence record keeps the last admitted `tenantId`, `gameInstanceId`, `realmId`, `worldSlug`, `realmSlug`, and `pointerVersion` so account-presence and friend-presence reads can continue to describe the last resolved durable realm target directly instead of collapsing immediately to a routing-less timestamp. The current selector-based record does not yet prove durable `{tenantId, realmId}` propagation. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 420ef18c3a..0acf91eaa5 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -6,31 +6,25 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory ## Implementation Status -The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache. Its handler requests a fresh Account membership read, but Account's live runtime handler returns `FAILED_PRECONDITION` before reading data; Game Session maps that response to `WORLD_ACCESS_DENIED`, so the entitlement and realm-grant reads do not establish a composed live admission path. - -The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). On connect-token replay-cache misses, issuance reads fresh Account authority; a cached `session:connect-token:*` success can bypass fresh entitlement, membership, and pointer rereads. That cache-hit bypass is implementation drift, not fail-closed admission proof. The target requires an independent issuance-time reread of `membershipVersion` and `membershipAuthorityGeneration`; baseline and replay-revalidation proof remains incomplete under [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Private/playtest connect-token grant validation is also incomplete. - -Text `PLAY` does not consult connect-token replay-cache state and requests fresh Account membership evidence (and the applicable grant for non-public targets). The live Account runtime handler currently returns `FAILED_PRECONDITION` before data access; Game Session maps that to `WORLD_ACCESS_DENIED`, so a live snapshot, subsequent entitlement/grant evaluation, or successful composed public `PLAY` is not established. Supplied-authority local branches classify otherwise-eligible public-production missing or `INACTIVE` membership as `JOIN_REQUIRED` after fresh entitlement and public-policy checks; active-but-non-admitting membership remains denied. Direct-text `JOIN` dispatch and the Account writer exist locally, but Gateway blocks first-party browser `Join & Play`; PostgreSQL/recovery and complete Telnet discovery/bridge proof remain open. - -Target direct-text flow is fresh `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/creation -> `PLAY` -> first `LOOK`. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. The target selector is a snapshot-bound ordinal or stable tenant-scoped slug pair; current local behavior supports bound ordinals and uniquely resolving bare world slugs, the latter being implementation drift. The pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` is unavailable. Direct-text/Telnet clients do not reuse first-party WebSocket discovery snapshots. `session_replaced`/`service_restart` preservation and bridge classification remain target-only. Current close recognition, fallback, and shutdown classification remain as recorded in [Operations Implementation Status](./operations.md#implementation-status). `LOGIN ` starts an email challenge; `LOGIN ` supplies the secret immediately. +The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. Its credential form is `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. Current `PLAY` does not consult the connect-token replay cache; live Account membership reads return in-band `FAILED_PRECONDITION` before data access, which Game Session maps from the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and handles without clearing the existing gameplay binding. AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`, so composed live text admission is not established. Connect-token cache behavior, issuance-time authority rereads, and text-admission rules remain owned by [Authentication](../../system-architecture-authentication.md#implementation-status) and the Account runtime contract. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status), with local capability and proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). ## Cross-Path Connectivity Contract The following are canonical contracts across Telnet and WebSocket paths: -- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped, and current `PLAY` does not create membership when it returns `JOIN_REQUIRED`. Direct text does not use a first-party WebSocket discovery snapshot. +- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped. The target `PLAY` path does not create membership; current live text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Direct text does not use a first-party WebSocket discovery snapshot. - Proxy -> Gateway WebSocket hop is mTLS-authenticated in player-facing environments under [Security](../../system-architecture-security.md#tls-termination--internal-encryption). - Proxy bridge-availability circuit breaker uses deterministic open/half-open/closed admission behavior during sustained upstream unreachability. ## Recommended Telnet Client Flows -These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. Direct-text `JOIN` is implemented and focused locally, but full Telnet discovery/bridge proof remains open. The `PLAY` handler's lifecycle/version/generation and entitlement classifications are conditional local branches; the live Account membership handler rejects before reading, and Game Session maps that to `WORLD_ACCESS_DENIED`. No live `JOIN_REQUIRED` or successful composed public `PLAY` is established through these handlers. The target connect-token membership-authority-generation/version baseline reread remains a separate gap. +These flows describe forwarding into the shared login/session pipeline. Command semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), and multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target requires fresh `WORLDS` before `LOGIN`; optional `HELP` does not replace it. Direct-text `JOIN` exists locally, but full discovery/bridge proof remains open. Live Account membership reads reject before data access, so current `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; conditional lifecycle and entitlement classifications use supplied authority in focused tests and do not prove live `JOIN_REQUIRED` or public admission. The connect-token reread of `membershipAuthorityGeneration` and `membershipVersion` remains open. - **Target canonical player flow** - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; its local Account route/RPC and Game Session text dispatch exist, while the full discovery-first sequence and end-to-end proof remain incomplete. The live Account membership handler currently rejects before reading, so text reconnect maps that response to `WORLD_ACCESS_DENIED`; local unit classification for supplied missing or `INACTIVE` membership does not establish a live `JOIN_REQUIRED`. Target behavior returns `JOIN_REQUIRED` for missing or `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for conditional `JOIN`; the local Account writer and Game Session dispatch exist, but full discovery-first and end-to-end proof remain open. The live Account membership handler returns in-band `FAILED_PRECONDITION` before reading and current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Supplied-authority unit classification does not establish live `JOIN_REQUIRED`. Target behavior requires `JOIN` for missing or `INACTIVE` public-production membership and permits skipping it only for existing `ACTIVE` membership. Private/playtest admission instead requires existing `ACTIVE` membership and the exact current grant; it does not use public `allowPublicJoin`. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -103,14 +97,14 @@ Typed `SESSION` gameplay lines are no longer part of the Telnet contract. TCP Pr Current rules: -- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Game Session's local `PLAY` branches classify supplied Account membership/lifecycle and entitlement responses, but the live Account membership handler rejects before reading and Game Session maps `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`; the live path does not reach `JOIN_REQUIRED` or the later realm-grant check. Direct-text `JOIN` dispatch and the Account writer exist locally, but successful composed public `PLAY` and the complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remain unproved; +- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Direct-text `JOIN` dispatch and the Account writer exist locally, but the live membership read returns in-band `FAILED_PRECONDITION` before data access and Game Session maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED`/grant classifications use supplied authority and are not live admission proof. `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Successful composed public `PLAY` and the complete target discovery-to-PLAY sequence remain unproved; - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; -- any future adapter-carried attach hint must remain advisory and must not bypass the current conditional `JOIN` path described above or the target discovery-first sequence owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); only existing `ACTIVE` public-production members skip target `JOIN`. +- any future adapter-carried attach hint must remain advisory and must not bypass the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` path or the target discovery-first flow owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); current text admission maps Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, and only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, but successful `LOGIN` -> `PLAY` -> `LOOK` admission is not established because the live Account membership handler rejects before reading and Game Session maps that failure to `WORLD_ACCESS_DENIED`. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist, but successful `LOGIN` -> `PLAY` -> `LOOK` admission is not established: the live Account membership handler rejects before reading, and valid-route text `PLAY` maps that in-band `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. A transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`; neither outcome proves admission. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 62740bc084..ca59a9f84c 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -29,8 +29,9 @@ For every private/playtest grant consequence, the exact Account target is `{acco - **Current fail-closed boundary:** Any route branch that requires the unavailable `privileged_control` window must reject that `platformAdmin` or cross-tenant `billingAdmin` authorization path. A separately declared tenant-role or unelevated `support` branch may remain available only when all of its own live checks pass. - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. -- The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` action exists locally, but the Gateway still blocks external `POST /auth/bootstrap/join`; first-party browser `Join & Play` is unexposed. Account runtime membership, entitlement, and grant gRPC handlers fail closed before data access until typed caller/target binding is available. Game Session `PLAY` validates exact identity, lifecycle, membership version, authority generation, admission, and evaluation time on supplied-authority branches. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, and only after fresh entitlement and `allowPublicJoin` checks; active-but-non-admitting membership receives no JOIN advice. Because live Account readers fail closed, these branches do not establish a composed live public `PLAY` or `JOIN_REQUIRED`. Current non-public text `PLAY` internally classifies denial as `WORLD_ACCESS_DENIED`. Definitive denial of an explicitly selected hidden or non-public-production realm projects the same selection-required response as an unresolved realm even within a publicly discoverable world; a non-discoverable world retains generic selection-required output without target metadata. Visible public-production denial and authority outages remain distinct; Account connect-token issuance retains its distinct rejection mapping and does not validate the applicable private/playtest grant. Account owns the independent issuance-time reread of membership version and authority generation; proof of this baseline, durable replay revalidation, and target connect-token grant validation remain incomplete. The Account JOIN worker uses versioned locked COMMITTED audit/receipt evidence for readback-only recovery: expired-scope retained `PENDING` intents remain retryable and only exact positive prior-commit evidence can terminalize; absent or uncertain evidence remains pending. PostgreSQL unknown-outcome/concurrency and direct-text end-to-end proof remain open. Canonical current and target outcomes remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). +- The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and performs a fresh membership check. For private/playtest targets, it reads the current realm grant only after the membership check succeeds with safe admitting membership. +- **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` operation exists locally, but Gateway blocks external `POST /auth/bootstrap/join` and first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data access because typed caller/target binding is not available. Game Session's local `PLAY` classifier validates identity, lifecycle, membership version, authority generation, admission, and evaluation time only on supplied-authority branches; this does not establish composed live admission. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership receives no JOIN advice. This supplied-authority `JOIN_REQUIRED` branch is not reached in the current live composition. Live text `PLAY` maps Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional membership/grant classification or Entity access because caller/target authority is unavailable; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so neither outcome proves member or actor visibility. Current non-public text `PLAY` denial is internally `WORLD_ACCESS_DENIED`; an explicitly selected hidden or non-public-production realm projects the selection-required outcome used for unresolved selection within a discoverable world, while a non-discoverable world stays generic and does not reveal target metadata. Visible public-production denial and authority outages remain distinct. Account connect-token issuance has its separate rejection mapping; cached-success replay requires exact cache-result binding and fresh current target/pointer, entitlement, and membership checks, but does not validate the applicable private/playtest grant. The independent Account issuance-time membership-version/authority-generation reread, durable replay revalidation, and target connect-token grant validation remain unproved. Canonical admission and outcome rules remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). +- **Public JOIN recovery status:** The Account JOIN worker reads exact locked, versioned COMMITTED audit/receipt evidence and cannot resubmit a bearer-bound request after its scope expires. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize it. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending. Terminal replay is bound to the authenticated caller, target, intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL unknown-outcome/concurrency and direct-text end-to-end proof remain open. Detailed local receiver and recovery status is tracked in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 79d693e202..1af30e73c6 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -Current implementation capability and proof status for player access, admission, and reconnect flows is tracked in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#current-status). The target protocol flow, carriage, ordering, admission, authentication, reconnect, and delivery requirements below remain normative; this bridge forwards the owned text sequence and does not independently claim successful live Account-backed `PLAY` or `JOIN`. +Current bridge capability and proof status for player access, admission, and reconnect are tracked in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#current-status). Existing smoke fixtures exercise only an abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path under stubbed admission; they do not prove `WORLDS`, `REALMS`, `JOIN`, or live Account-backed admission. The bridge forwards current `WORLD_ACCESS_DENIED` and `CHARACTER_LIST_UNAVAILABLE` consequences; [Authentication](./system-architecture-authentication.md#implementation-status) owns their precise admission/outcome meaning. The target protocol flow, carriage, ordering, reconnect, and delivery requirements below remain normative. --- @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Supplied-authority text `PLAY` must validate exact account/tenant identity, freshness, consistent `ACTIVE`/`INACTIVE` lifecycle, and positive membership-version and membership-authority-generation values; missing membership is exact `MISSING` evidence with zero versions and no admission. Public `JOIN_REQUIRED` follows only missing or `INACTIVE` membership after fresh entitlement and `allowPublicJoin` checks; an `ACTIVE` but non-admitting membership remains denied. Current implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers currently fail closed before data access, so supplied-authority classification is not proof of live admission; composed text/browser proof and connect-token issuance status remain with those owners. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication, and target `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Supplied-authority text `PLAY` validates exact account/tenant identity, freshness, consistent lifecycle, and positive membership-version and membership-authority-generation values; missing membership must be exact `MISSING` evidence with zero versions and no admission. Only fresh public-production `MISSING` or `INACTIVE` membership after entitlement and `allowPublicJoin` checks can yield `JOIN_REQUIRED`; an `ACTIVE` but non-admitting member is denied. Current text `PLAY` maps the live Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Current `PLAY` and `CHARS` outcomes are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers fail closed before data access, so supplied-authority classification is not live admission proof. This bridge preserves the transport consequence and does not claim current JOIN, roster access, successful PLAY, or composed text/browser proof. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Account runtime, supplied-authority `PLAY`, and connect-token issuance implementation and proof status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers currently fail closed before data access, so this target sequence is not live composed admission proof. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge preserves its owner-defined order, fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, exact current Account-owned realm-grant requirements, discovery snapshot, and valid-character prerequisites without treating discovery or token evidence as authorization proof. `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character; a character is mandatory before connect-token issuance and `PLAY`. Account runtime and connect-token issuance status remain with their owners. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current implementation and proof status is recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). In particular, `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. +The precedence and error rows below are the normative target inventory. The bridge maps live in-band Account membership `FAILED_PRECONDITION` and transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE` while preserving the existing gameplay binding. Account connect-token endpoint outcomes do not create bridge-level `JOIN_REQUIRED` advice. Current admission outcome and proof status are recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE`, and the earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates must pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime readers currently fail before data access, so this supplied-authority classification does not establish live admission; current implementation and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE` after the canonical earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime readers currently fail before data access, so this conditional classification is unit-only and does not establish live admission. Current text `PLAY` maps the live Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; the local Account route/RPC and Game Session dispatch do not establish an actionable current admission path. Current status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for explicit `JOIN` or `Join & Play`. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -82,7 +82,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu Direct text/Telnet clients must issue fresh anonymous `WORLDS` before credential-bearing `LOGIN`, then follow the authenticated `REALMS`-to-`JOIN` procedure in [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The bridge carries the resulting text flow and does not create or restore membership; Game Session retains pending JOIN transport state under the contract below. Reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`; a complete `CLOSED` realm remains `REALM_UNAVAILABLE`. Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist; lifecycle/generation reread and end-to-end runtime/deployment proof gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). -Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` retains `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on these non-public (private/playtest) targets; an eligible public-production request remains `JOIN_REQUIRED`. It also requires the current realm grant, while connect-token grant validation remains implementation drift. The separate current Account connect-token mappings are recorded in the implementation status above and are not text-protocol outcomes. +Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding before grant evaluation; supplied-authority classifications are unit-only. Current connect-token endpoint behavior is separate from text-protocol `PLAY` and remains recorded by its owning Account contract. A retained-edge upstream rebind is not a reconnect from the client's perspective. Gateway and the proxy may rebind the established edge to a replacement Game Session owner without repeating `LOGIN`, `JOIN`, or `PLAY`; unchanged public-production binding continuity may use bounded last-known-good entitlement only during an entitlement-only outage after current Account membership, routing, public policy, revocation, and resume-lease checks pass. This exception does not change the strict fresh-entitlement rules for a fresh gameplay binding/new admission, private/playtest admission, or a client-facing edge disconnect; an exact same-binding reconnect on a new transport does not receive this retained-edge exception and must use fresh admission rules. @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Current admission-reader containment and local classification status are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status): Account runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`. A supplied-authority `JOIN_REQUIRED` classification does not establish live admission. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. Target behavior permits Game Session to present bounded semantic recent context only after fresh admission and when exact binding and episode evidence permit, before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); current Game Session suppresses private retained-context reads on reconnect. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads remain suppressed on reconnect and after attempted `LOGOUT`, while fresh `LOOK` remains available after accepted `PLAY`. Strict generation-fence enforcement and live recovery proof remain incomplete, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor TCP Proxy replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After a client-facing edge disconnect, or after authentication invalidation terminates the active binding, direct text/Telnet follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) on a new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, then `PLAY`. Private/playtest reconnect never uses the public join fallback. Text clients obtain a new transport-local scope from authenticated `REALMS`; they do not reuse a browser/WebSocket snapshot, HTTP bootstrap, gameplay connect token, or first-party WebSocket bare `LOGIN`. Target entitlement, membership, and grant predicates remain owned by Authentication, and public `allowPublicJoin` never substitutes for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain distinct target error classes. A future semantic adapter starts fresh on the new connection while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. Target behavior permits bounded semantic recent context only after fresh admission and when exact binding and episode evidence allow it, before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Retained context is not authorization: target reads require the exact current `resumeContextGeneration` of an eligible, non-terminated binding, and durable `LOGOUT` must terminate that episode before acknowledgement and fence stale rows/cache state; a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Clients then rely on Game Session and Redis to resume or start fresh under [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage identities and a reused identity never implies automatic stale-intent replay. Implementation and proof status remain in [Reconnection Implementation Status](./system-architecture-reconnection.md#implementation-status), [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. Current admission-reader containment and local response-classification status are owned by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account runtime membership, entitlement, and grant readers fail closed before data access pending typed caller/target binding; a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`, while a supplied-authority `JOIN_REQUIRED` classification is not proof of live admission. Complete runtime/deployment and lifecycle-aware issuance-reread proof remain incomplete. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. Current admission-reader containment and local response-classification status are owned by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account runtime membership, entitlement, and grant readers fail closed before data access pending typed caller/target binding; a live Game Session membership-read `FAILED_PRECONDITION` maps to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while a supplied-authority `JOIN_REQUIRED` classification is not proof of live admission. Complete runtime/deployment and lifecycle-aware issuance-reread proof remain incomplete. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. @@ -277,7 +277,7 @@ Operators should interpret spikes in each layer’s metrics in this order when d - Buffers active input while the client remains connected and discards it if the TCP connection drops; the proxy never replays Telnet commands after a disconnect. - Telnet clients keep a sticky connection to the TCP Proxy Service; reconnection and session recovery are handled as described in [Reconnection Strategy](./system-architecture-reconnection.md). - Retained-edge upstream rebind is not an actual client-facing disconnect: Spring Cloud Gateway retains the client or proxy-facing gameplay WebSocket while performing ADR 0013's bounded rebind of a rebindable Game Session upstream, then closes with `1013/backend_unavailable` if recovery exhausts its window. Game Session revalidates the existing continuation binding, authorization, revocation, and target authority under the [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) contracts; it does not require fresh `LOGIN`, `JOIN`, or `PLAY`, and this hidden rebind does not trigger retained-context restoration or a fresh `LOOK`. -- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. Only after fresh admission completes, including current `LOGIN` identity checks and `PLAY` binding checks, may Game Session restore retained semantic context when its binding and episode evidence permit, followed by a mandatory fresh authoritative `LOOK`. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads remain suppressed on reconnect and after attempted `LOGOUT`, while fresh `LOOK` remains available after accepted `PLAY`. Strict generation-fence enforcement and live recovery proof remain incomplete. Target restoration is unavailable after durable termination of the private context episode, character ownership/control transfer, or a missing, ambiguous, non-positive, or not-exactly-current-and-non-terminated `resumeContextGeneration`; the target `LOGOUT` -> `LOGIN` -> `PLAY` path must durably fence the terminated binding before acknowledging `LOGOUT`, prove no private context replay, and then use the newer positive generation before any restoration. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical target contract, restoration status, and gaps. Structured status or optional semantic-extension state and any applicable prompt are additional projections, not alternatives to that `LOOK`. The Telnet path does not support hidden reattachment after its distinct Proxy -> Gateway gameplay WebSocket is lost: the proxy closes that Telnet connection rather than silently opening a fresh edge bridge behind the same client TCP socket. +- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. Only after fresh admission completes, including current `LOGIN` identity checks and `PLAY` binding checks, may Game Session restore retained semantic context when its binding and episode evidence permit, followed by a mandatory fresh authoritative `LOOK`. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before enqueue or lifecycle side effects. Private retained-context replay remains closed unless exact current `resumeContextGeneration` and durable non-terminated episode/binding evidence are established; private reads remain suppressed when that evidence is unavailable, including after attempted `LOGOUT`. A connect token alone is not replay authority, and accepted `PLAY` still requires a fresh authoritative `LOOK`. This fail-closed behavior does not prove the target terminal fence; strict generation-fence enforcement and live recovery proof remain incomplete. Target logout must durably terminate the episode and binding through the required compare-and-set before acknowledgement; restoration is unavailable after termination, character ownership/control transfer, or missing, ambiguous, non-positive, or not-exactly-current-and-non-terminated generation evidence, and a later authorized episode uses a newer positive generation. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical contract and gaps. Optional status or semantic-extension state and prompts are additional projections, not substitutes for `LOOK`. The Telnet path closes its client socket when its Proxy -> Gateway bridge is lost and does not hide reattachment behind it. - The proxy defines a `NotifyDisconnect` gRPC event so the Game Session Service can react quickly when Telnet clients drop. This stream is best-effort and **at-least-once**, and Game Session treats it as an idempotent, advisory hint rather than a source of truth for session liveness. Consumers key handling off `{proxyConnectionId, disconnectSequence}` so late or duplicate events are safe to ignore. The behaviour-level contract for this stream is summarised in the **NotifyDisconnect Behavioral Contract** section of [Reconnection Strategy](./system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary), while the TCP Proxy Service design’s **Service Interactions** section remains canonical for message fields, retry windows, and envelope context. - Metrics are exported at `/actuator/prometheus` and tracing data is sent to the collector configured by `OTEL_ENDPOINT`. See [Logging & Monitoring](./system-architecture-logging-monitoring.md). - Environment-specific tuning guidance for the TCP Proxy Service (connection caps, envelope budgets, and production hardening) is documented in the TCP Proxy Service design under **Tuning TCP Proxy for Different Environments**. @@ -287,7 +287,7 @@ Operators should interpret spikes in each layer’s metrics in this order when d Resume affects gameplay identity and session binding, not transport continuity: - Neither the TCP Proxy nor Gateway replays prior outbound text or optional semantic-extension traffic onto a newly reconnected client transport. -- After a successful reconnect and `PLAY`, current Game Session suppresses private retained-context replay on reconnect and after attempted `LOGOUT`, then renders a fresh authoritative `LOOK` derived from current state for the new transport. Strict generation-fence enforcement and live recovery proof remain incomplete. Target replay eligibility is restricted to the exact private semantic-context episode `{tenantId, playableStateNamespaceId, characterId, resumeContextGeneration}`. `bindingGeneration` remains the independent controller-ownership fence: an authorized reconnect, controller takeover, or runtime replacement carries the same `resumeContextGeneration` even when `bindingGeneration` advances. Durable termination for explicit logout, character ownership transfer, or lost replay authority occurs before any character-transfer acknowledgement and prevents restoration under that generation; a later authorized episode uses a newer generation. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the target contract, restoration status, and gaps. An applicable prompt, structured status, or newly generated optional extension state is an additional projection, not an alternative to `LOOK`; no transport backlog or exact-delivery replay is permitted. Empty or expired context produces no context output. +- After a successful reconnect and `PLAY`, current Game Session suppresses private retained-context replay when exact durable generation/termination evidence is unavailable, including on reconnect and after attempted `LOGOUT`, then renders a fresh authoritative `LOOK` derived from current state for the new transport. Durable generation-qualified replay proof remains incomplete. Target replay eligibility is restricted to the exact private semantic-context episode `{tenantId, playableStateNamespaceId, characterId, resumeContextGeneration}`. `bindingGeneration` remains the independent controller-ownership fence: an authorized reconnect, controller takeover, or runtime replacement carries the same `resumeContextGeneration` even when `bindingGeneration` advances. Durable termination for explicit logout, character ownership transfer, or lost replay authority occurs before any character-transfer acknowledgement and prevents restoration under that generation; a later authorized episode uses a newer generation. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the target contract, restoration status, and gaps. An applicable prompt, structured status, or newly generated optional extension state is an additional projection, not an alternative to `LOOK`; no transport backlog or exact-delivery replay is permitted. Empty or expired context produces no context output. - Allowed reconstruction output must be re-derived from current state at resume time; it must not be a byte-for-byte replay of previously queued outbound payloads from the old transport. - If previously delivered content and newly derived reconstruction happen to look similar to a human reader, that is acceptable only because the content was regenerated from current state, not because the transport backlog was replayed. - Prompt/status output remains a special output class rather than ordinary transcript text. Prompt lines should be coalesced after bursts of gameplay output and regenerated fresh for the new transport rather than copied into the reconnect transcript buffer. Current operator-default prompt behavior is surfaced in Game Session through `firemud.presentation.prompt.enabled`, `firemud.presentation.prompt.emit-after-reconnect-restore`, and `firemud.presentation.prompt.coalesce-window-ms`. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 93af0314a4..29ad398180 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,8 +10,8 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission, implementation, and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; token issuance persistence and retention status is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). -- **Runtime authority checks** – `PLAY` attempts membership and tenant-entitlement checks before fresh entry or resume/takeover, but its local classification uses supplied authority and does not prove positive live checks. Account's runtime readers fail closed before data reads until typed caller/target binding is available; see [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift). +- **Telnet and WebSocket parity** – The target shared gameplay flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet uses a fresh connection, `WORLDS`, credential-bearing `LOGIN`, and authenticated `REALMS`; first-party WebSocket reruns bootstrap and discovery, completes any required `Join & Play` and character step, obtains a fresh connect token, then opens `/ws/game/**`. Current implementation and proof status is recorded by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). +- **Runtime authority checks** – Target `PLAY`, reconnect, and takeover require current caller-bound membership, applicable entitlement and realm-grant authority, and exact routing and binding evidence before fresh admission, subject only to the owner-defined bounded continuity exceptions. Authentication owns the authority and outcome contract; current implementation and proof status is recorded by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -83,13 +83,13 @@ Reconnection uses two distinct client flows: Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. -Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Game Session's local non-public response and grant checks are exercised with supplied authority; they do not establish a live Account admission path. Account's membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live membership-read failure maps to `WORLD_ACCESS_DENIED`; composed live grant-backed admission is not proved. Connect-token grant validation also remains incomplete. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owner status. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. +Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Game Session's local non-public response and grant checks are exercised with supplied authority; they do not establish a live Account admission path. Account's membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and an in-band Account membership `FAILED_PRECONDITION` maps to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; composed live grant-backed admission is not proved. Connect-token grant validation also remains incomplete. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owner status. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. A client must not infer current membership or target identity from a stale Redis binding, cached tenant/realm fields, or an old `connectScopeId` after `CONNECT_SCOPE_MISMATCH`. For direct text, Game Session may use only the scope retained from the current authenticated `REALMS` exchange; it must not recreate that scope or authority from a stale selector after transport loss or scope failure. ### Public membership repair during reconnect (normative) -Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete. Current authority-reader containment and local response classification are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift): Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before reads pending typed caller/target binding, so the local `JOIN_REQUIRED` branch does not establish live `JOIN_REQUIRED`; Game Session maps the live membership-read failure to `WORLD_ACCESS_DENIED`. +Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete. Current authority-reader containment and local response classification are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift): Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before reads pending typed caller/target binding, so the local `JOIN_REQUIRED` branch does not establish live `JOIN_REQUIRED`; Game Session maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. Redis-backed session state allows resumable recovery when the gameplay binding is still logically valid, or a fresh login when it is not. The canonical continuity anchor, resume episode, physical TTL rules, token refresh, and transcript authority are defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Reconnection retains only this transport consequence: Redis key presence alone never authorizes resume, and a new transport never replays prior bytes. @@ -108,7 +108,7 @@ Successful reconnect after a normal disconnect: ```text OK LOGIN Logged in as demo@example.com OK PLAY Entered world: demo - + ``` Stale or expired resumable state where a fresh `PLAY` can still be admitted should not force the player to type the same command twice. The normal outcome is still a successful fresh entry: @@ -116,7 +116,7 @@ Stale or expired resumable state where a fresh `PLAY` can still be admitted shou ```text OK LOGIN Logged in as demo@example.com OK PLAY Entered world: demo - + ``` Only failures that genuinely require player or client action should surface as errors, for example access revocation, missing entitlements, or backend unavailability. @@ -211,20 +211,20 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). `PlayCommandHandler` has focused unit response-classification coverage using supplied Account authority, but live Account membership/entitlement/grant RPCs fail before data access and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`; no live `JOIN_REQUIRED` or successful composed public `PLAY` through these handlers is established. Local direct-text REALMS-scope/JOIN dispatch and the Account RPC exist, but the public Gateway JOIN route remains denied; PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. -- Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. A local browser bootstrap JOIN facade exists, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied; the full first-party browser/mobile flow and proof remain incomplete. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). +- Telnet clients reconnect on a new TCP connection and follow the Authentication-owned fresh-discovery and authenticated text procedure. Their new transport-local scope comes from authenticated `REALMS`; no first-party WebSocket connect-token snapshot or stale prior selector is reused. The live in-band Account membership `FAILED_PRECONDITION` currently maps text `PLAY` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; supplied-authority `JOIN_REQUIRED` coverage, the local REALMS-scope/JOIN dispatch, and Account JOIN RPC do not prove the complete flow. The public Gateway browser JOIN route remains denied. PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and end-to-end proof of the authenticated direct-text `REALMS` → `JOIN` → `PLAY` flow remain open. `CHARS` or allowed character creation is conditional on no valid selected character. If smart-client attach hints return later, they must be resent as hidden MCP metadata. +- Web clients reconnect by rerunning bootstrap discovery and, when required by the target, `Join & Play` plus realm-scoped `CHARS` or allowed character creation before fresh connect-token issuance. They then open `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. The local browser JOIN facade exists, but its public Gateway route and the full browser/mobile flow remain unimplemented or unproved. A short-lived discovery snapshot supplies only the selected edge target and is discarded on expiry or scope mismatch; it does not replace current `ACTIVE` membership or a valid character. Web clients must not assume previous MCP or hidden attach metadata survives; see [Mud Client Protocol](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification proof uses supplied Account authority and confirms lifecycle/generation/version/evaluation-time validation plus the local `JOIN_REQUIRED` classification for missing or `INACTIVE` eligible public membership. Live Account runtime readers still reject with `FAILED_PRECONDITION` before data access, and Game Session maps that live membership failure to `WORLD_ACCESS_DENIED`; live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN operation exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification proof uses supplied Account authority and confirms lifecycle/generation/version/evaluation-time validation plus the local `JOIN_REQUIRED` classification for missing or `INACTIVE` eligible public membership. Live Account runtime readers still reject with `FAILED_PRECONDITION` before data access, and Game Session maps that in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN operation exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: The close reason never establishes that command outcome. The current gameplay-command status surfaces are restricted to authorized operator or internal-service clients; an authorized client holding `{tenantId, gameInstanceId, commandId}` may reconcile that tuple, but ordinary players cannot use knowledge of `commandId` to query it. A future caller-bound first-party status route may expose the same authoritative record only after it binds the requested tuple to the immutable ingress account, character, or session identity required by the owning [command-outcome contract](./system-architecture-tick-execution-flows.md#command-outcome-status-surface-required). Until that route exists, ordinary browser and classic line clients receive later state reconstruction, must not treat any retryable close as proof that the last command failed, and must not recreate the input automatically. -- current implementation persists ordered `resume_transcript_entry` rows but suppresses private retained-context replay on reconnect and after attempted `LOGOUT`; it can render a fresh authoritative `LOOK` and prompt after successful `PLAY`. The current deliberate `LOGOUT` command returns `LOGOUT_UNAVAILABLE` without terminating the binding because the durable episode fence is absent. Target replay eligibility requires the exact current `resumeContextGeneration` and a non-terminated semantic-context episode; under that target, explicit gameplay `LOGOUT` durably terminates the episode before acknowledgement and prevents later replay of its private context. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) records the entry, cache, presentation, and current proof consequences; +- Current implementation persists ordered `resume_transcript_entry` rows but suppresses private retained-context replay when exact current `resumeContextGeneration` and durable non-terminated episode/binding evidence are unavailable; successful `PLAY` renders a fresh authoritative `LOOK`. Deliberate text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects because the durable episode fence is absent. Target replay eligibility requires the exact current generation, and target logout must commit episode termination with binding termination in one durable compare-and-set before acknowledgement. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) owns the context and presentation contract; the terminal fence, race/retry safety, and complete proof remain open. - the context may repeat output the client already displayed or omit output that was not retained or available. It is not a delivery acknowledgement, exact missed-message list, command history, or transcript archive; Redis may cache it but is not authoritative, and physical deletion may complete asynchronously; - then current reconnect flow obtains a fresh authoritative `LOOK` and applies the owner-defined prompt behavior. The local consequence is exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero when either is disabled; prompt restoration and duplicate-prevention proof remain current gaps recorded in [Input, Output and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status). This reconstruction defines current state; retained context is narrative orientation only. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8c0d6044d5..296893a2ca 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -217,3 +217,14 @@ Entry format: - Context: on 2026-10-03, a 0/0 public checkpoint was briefly posted before the complete CLI capture was inspected. The terminal capture showed 1 found / 1 accepted; source finalization first refused the undecided finding, and linked checkpoint `5969229965` was corrected. - Expected pattern: inspect the complete terminal raw capture, adjudicate every finding, and confirm successful source finalization before building public counts. If finalization refuses, resolve the disposition and correct the linked checkpoint before reporting the result. - Outcome: the source decision and finalization were recorded with no dry-review credit. + +- `2026-09-25`: Admission fixture actors must carry the complete typed scope + - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. + - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. + - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. + +- `2026-10-05`: Match review fixes to the exact production or test file + - Context: a reused #2857 helper put a requested `WorldsCommandHandler` comment in unassigned production `GameSessionGrpcService`, then returned passing tests while missing several new findings and implementing similar earlier requests instead. Its similarly named test file was assigned. + - Expected pattern: use complete source-root paths and explicit current finding IDs; match each fix to its named method and intended semantic change, not a similar prior request. Inspect the complete returned diff against every accepted item before publication; passing tests do not establish assignment coverage. + - Observation: even a passing focused suite can miss a narrowly accepted correction if the patch is applied to a similar but unassigned production file or covers only an earlier, related request. + - Outcome: the helper reported the wrong-file edit, and the orchestrator removed only that known comment. Integration caught the remaining mismatches before publication and returned the same helper to the exact corrections, preserving unrelated edits. The corrected batch passed 464 focused tests, integration-source compilation, enabled formatting/static checks, and documentation checks; integration runtime remains unrun locally. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 9bceb6cf4d..1d7899c580 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -20,16 +20,16 @@ Completed phases: capability allocation, implementation/proof reconciliation, cr ### Corpus section programme status -This is the sole live corpus section-status index for a fresh whole-corpus review restart after the completed ADR work. The [whole-corpus authority review plan](./whole-corpus-authority-review-plan.md) defines the section boundaries and method; this subsection records the current status, one main PR slot, and evidence or routed work per section. Prior merged reviews and pull requests are historical evidence only and do not establish completion of this restart. A published implementation draft does not by itself complete its semantic-unit review. +This is the sole live corpus section-status index. The [whole-corpus authority review plan](./whole-corpus-authority-review-plan.md) defines the section boundaries and implementation-first method; this subsection records current status, main PRs, and concise evidence or routed work. Earlier reviews and merged PRs remain historical alignment evidence. **Provisional** means the final section gate remains open because required pre-v1 work, essential proof, or a convincing whole-section review is still missing. A published draft, review taper, or discovery stop does not by itself establish corpus completion. -The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. +The preserved 5B implementation work was rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. The three 5B subunits and cross-subunit synthesis retain their earlier alignment evidence, but final completion follows the implementation-first gate in the plan; there is no separate overall 5B status row. -5B synthesis: Corpus discovery was accepted closed by Overseer at cumulative #2829 head `dce1d8246e3ff2bf9c3bfcb9649ae0e5c4181e6b`; no fourth closure cycle is required. Paired whole-5B closure Cycle 1 was dry, Cycle 2 produced three accepted obligation families after deduplication, and corrected-state Cycle 3 was dry (18 and 19 raw observations, zero new accepted obligations). The accepted corrections enforce coordinated `Recreate` and roll-forward-only deployment for incompatible Automation V3 and Game Design V26 migrations, quarantine only V13-marked unattested legacy full versions while preserving bundled and script-only rows, and classify the two Automation plugin-history retention families without inventing a cleanup TTL. This is a corpus-discovery judgment, not current-head review taper, capability completion, live proof, or merge readiness; current #2828/#2829 changes retain their own review and proof gates. +5B historical synthesis: Overseer accepted discovery closure at cumulative #2829 head `dce1d8246e3ff2bf9c3bfcb9649ae0e5c4181e6b`; no fourth historical closure cycle is required. Paired whole-5B Cycle 1 was dry, Cycle 2 was productive, and corrected-state Cycle 3 was dry. Cycle 2's two independent reviewers produced three accepted obligation families after deduplication. The corrected stack enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and classifies the two Automation plugin-history retention families without inventing a cleanup TTL. Cycle 3's two independent reviewers returned 18 and 19 raw observations with zero new accepted obligations. Remaining accepted required implementation and essential proof keep the 5B subunits provisional under the current completion rule. This historical discovery judgment is not current-head #2828/#2829 review taper, live proof, or merge readiness. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Queued | — | — | +| 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | +| 1B | Admission, session continuity, and reconnect | Provisional; earlier two-cycle report boundary completed, required implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861) | #2857 corrects bounded Game Session admission/reconnect behavior; #2861 prepares ADR 0144's non-mutating email-link GET landing and explicit POST, not a deployed mail journey. Cycle 1 found misleading current `PLAY`/`CHARS` and post-logout claims plus routed issuer, Entity roster, and signed-context gaps. Cycle 2 found stale successful-admission claims in Reconnection, TCP, Account runtime and Realm Routing; these now distinguish Account REST token issuance from fail-closed Game Session gRPC reads. The repeated issuer, signed-context and durable-reconnect observations remain named activation successors. Account runtime reads still deny new text `PLAY` before data access. Exact-current-head CI, PostgreSQL/cross-service proof, Account and Entity target authority, signed-context handoff, HTTPS/mail/abuse controls, and live browser proof remain open. The prior code-head CI run `36006632988` cleared 27 WebSocket and 39 Game Session cross-service cases but was red overall; local Docker skips are not runtime proof. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | @@ -40,12 +40,12 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 3C | Release lifecycle and activation | Queued | — | — | | 4A | Script ingress, sandbox, and runtime execution | Queued | — | — | | 4B | Scheduling, quotas, reload, and operational fairness | Queued | — | — | -| 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | -| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Merged; residual live proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor. | -| 5B-Publication | Durable version/publication/readiness state | Corrected-head review and merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Historical Cycles 1–6 and the accepted whole-5B synthesis remain recorded, but do not establish taper on the moving corrected head. V27/V28 legacy-version quarantine and V26 stop-before-start/roll-forward-only scope migration remain required. End-to-end full-version publication, live mounted-certificate/Temporal calls, mixed PostgreSQL proof, version-scoped Automation content, Game Design mapping, readiness notification, and ability-schema attestation remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Open, non-draft; corrected-head review and merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | V4 execution/replay/retention work is preserved behind Publication through [#2879](https://github.com/benhook1013/FireMUD/pull/2879) and [#2882](https://github.com/benhook1013/FireMUD/pull/2882). Historical review classified `plugin_runtime_request_history` as retry/idempotency receipts and `plugin_runtime_events` as recovery/reconciliation plus lifecycle audit. Neither is eligible for automatic deletion before measured horizons, holds, safe watermarks, bounded sweeps, and metrics. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | -| 5C | Redis roles and cache/rate-limit semantics | Corpus review tapered; implementation/proof gaps remain | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The combined 5C/5D successor preserves the #2661 Redis role, authority, reset, recovery, keyspace, and operational content behind #2829. Fifteen corrected-state whole-unit cycles ended with two dry cycles; parent reconciliation and exact-head validation are separate gates. | -| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Corpus review tapered; implementation/proof gaps remain | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The same successor preserves #2661 replay, effect identity, scheduler, tick, saga, workflow, and recovery content. Pending ADR 0183 remains a proposal without accepted authority. Parent reconciliation and exact-head validation are separate gates. | +| 5A | API, message, identifier, tenant, time, and authorization primitives | Provisional; prior corpus review complete, required implementation open | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | +| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Provisional; merged, residual live proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor. | +| 5B-Publication | Durable version/publication/readiness state | Provisional; corrected-head review and merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Historical Cycles 1–6 and the accepted whole-5B synthesis remain recorded, but do not establish taper on the moving corrected head. V27/V28 legacy-version quarantine and V26 stop-before-start/roll-forward-only scope migration remain required. End-to-end full-version publication, live mounted-certificate/Temporal calls, mixed PostgreSQL proof, version-scoped Automation content, Game Design mapping, readiness notification, and ability-schema attestation remain open. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Provisional; open non-draft, corrected-head review and merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | V4 execution/replay/retention work is preserved behind Publication through [#2879](https://github.com/benhook1013/FireMUD/pull/2879) and [#2882](https://github.com/benhook1013/FireMUD/pull/2882). Historical review classified `plugin_runtime_request_history` as retry/idempotency receipts and `plugin_runtime_events` as recovery/reconciliation plus lifecycle audit. Neither is eligible for automatic deletion before measured horizons, holds, safe watermarks, bounded sweeps, and metrics. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | +| 5C | Redis roles and cache/rate-limit semantics | Provisional; corpus review tapered, implementation/proof gaps remain | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The combined 5C/5D successor preserves the #2661 Redis role, authority, reset, recovery, keyspace, and operational content behind #2829. Fifteen corrected-state whole-unit cycles ended with two dry cycles; parent reconciliation and exact-head validation are separate gates. | +| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Provisional; corpus review tapered, implementation/proof gaps remain | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The same successor preserves #2661 replay, effect identity, scheduler, tick, saga, workflow, and recovery content. Pending ADR 0183 remains a proposal without accepted authority. Parent reconciliation and exact-head validation are separate gates. | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | | 6B | WebSocket, Telnet, protocol bridge, and session transport | Queued | — | — | | 6C | Logging & Admin/operator ingress and action authorization | Queued | — | — | @@ -114,21 +114,11 @@ Contract-authority consolidation applies to repeated normative product and archi Consolidation names one canonical owner for a target contract and reduces competing secondary definitions to owner links plus local API, persistence, transport, operational, user-visible, implementation-drift, or proof consequences. It is not editorial deduplication: useful examples, runbooks, evidence schemas, local constraints, and explanatory context remain where they serve their owning document. -The completed decision-family imports consolidated related normative duplication in each affected design area, including non-ADR contracts. Now perform one broad design-area authority review across the complete product and architecture corpus to identify residual owner conflicts and non-ADR duplication that family-local imports did not expose. - -The selective ADR-family imports are complete. The next alignment phase is the planned whole-corpus authority pass: preserve one canonical owner for each contract, retain useful local consequences and explanatory context, and remove only competing normative authority. During PR review, follow the [PR lifecycle review completion criteria](../../developer-workflows/pr-lifecycle.md#review-completion-criteria). - -Keep the authority pass focused on design review, but carry unambiguous implementation and proof corrections with the selected domain when that produces one coherent boundary. Grow the active PR across the natural whole domain while it remains within practical hosted-review headroom; a small independently reviewable capability is not, by itself, a reason to create a precursor PR. Split only for concrete size or hosted-review pressure, or when a substantial dependency or invariant requires an independently ordered checkpoint. When a split is necessary, keep every valid finding active in an identified domain contribution rather than silently discarding or indefinitely deferring it. If implementation is decision-sensitive or cannot be completed safely within the selected domain, retain an explicit tracker gap and state the blocking decision or dependency. Do not mix unrelated code into a corpus PR merely to avoid recording truthful current status, and do not repeatedly reshuffle an already-reviewed hybrid PR solely to optimize reviewer attention. +The completed decision-family imports consolidated related normative duplication in each affected design area. The [whole-corpus programme](./whole-corpus-authority-review-plan.md#implementation-and-review-method) now pairs authority review with required pre-v1 implementation. Document first reconciles known required work and its dependencies, then implements and reviews each semantic section; the sole live status table above distinguishes provisional sections from completed ones. This work retains one canonical normative owner and useful local consequences. It does not reopen accepted human decisions. PR-wide CodeRabbit review and merge readiness follow the separate [PR lifecycle](../../developer-workflows/pr-lifecycle.md#review-completion-criteria). ### Domain review operating model -For the fresh 5B restart, the Worker owns each selected semantic subunit end to end while coordinating the Schema, Publication, and Retention subunits as one 5B review boundary. The Worker first reconciles preserved domain work and seed fixes, then delegates fresh, disjoint-scope corpus investigations to identify gaps, contradictions, and duplicated authority outside the proposed changes. CodeRabbit and hosted review assess the proposed PR changes and verify their fixes; they are change-review evidence, not a substitute for a broader domain assessment. - -Across the investigation scopes and final domain assessment, cover the selected domain, including secondary consequences and proof state, while preserving canonical owner links and keeping implementation changes in their existing owner surfaces. - -Fresh disjoint-scope investigations may run while CodeRabbit reviews the active front PR. The Worker consumes and adjudicates each broad search before starting another, so every fresh search examines the updated corpus and the current fix state. During active hosted review, prepare corrections locally and preserve review safety: do not publish review-invalidating changes until the hosted review completes. Coherent stacks are allowed when they retain a stable merge front and account for fixes already downstream. - -PR closure follows the hosted review evidence and judgment described by the [PR lifecycle](../../developer-workflows/pr-lifecycle.md). Domain closure has an additional requirement: after fixes converge, complete a fresh assessment of the whole selected domain. Continue work for meaningful gaps, contradictions, owner conflicts, or proof consequences. Stop when remaining suggestions are only duplicates, unsupported, transient status churn, or low-value polishing. The Worker may advance each cycle without per-cycle Overseer approval; escalate consequential new architecture or scope, competing target states, or other decisions that require human judgment through the normal workflow. This model applies to the fresh 5B restart and its three semantic subunits; it does not modify reusable generic delegation rules or technical architecture. +Document owns required pre-v1 corrections in their canonical domain unless another active worker owns the slice. Coherent cross-service work is appropriate when one invariant spans those services. Focused investigations can prepare a difficult area, but a completion attempt uses two fresh independent unguided whole-section reviewers in parallel, including unchanged sources, implementation, proof claims, and secondary handoffs. Their observations are deduplicated and adjudicated as one paired round. Material findings are corrected and reviewed again on the corrected state; isolated documentation or fixture corrections use focused proof and explicit closeout judgment. A section stays provisional while required work, essential proof, or convincing whole-section review is missing. Independent side findings move to their owning section without being silently discarded. After the first traversal, Document revisits all provisional sections as dependencies clear, repeating the sweep when necessary. The [plan](./whole-corpus-authority-review-plan.md#implementation-and-review-method) owns the full method; this index records current status rather than a separate review ledger. ## Authority Boundaries @@ -151,11 +141,11 @@ PR closure follows the hosted review evidence and judgment described by the [PR ## Current Work Sequence -1. Run the whole-corpus authority review across current product and architecture documents now that all reviewed decisions are selectively applied. -2. For each contract family, identify one canonical owner and distinguish legitimate local consequences, examples, evidence schemas, and runbook instructions from competing normative definitions. -3. Reconcile residual owner conflicts and non-ADR duplication without reopening completed human decisions or treating ADR rationale as the operational contract. -4. Reconcile live domain trackers only where the authority pass changes implementation, verification, or remaining-gap state. -5. Validate the complete corpus before declaring post-ADR design alignment complete. The completed taxonomy, allocation, inventory, reconciliation baseline, human-led review, and selective import are historical prerequisites rather than phases to rerun. +1. Preserve the earlier section reviews, PRs, fixes, and accepted findings; reclassify any section with required pre-v1 implementation or essential proof still open, or without a convincing whole-section review, as provisional. +2. Reconcile known findings and live implementation trackers with current code. Decide and dependency-order required pre-v1 work, deliberate later work, and already-resolved rows; bring consequential scope choices to Overseer with a recommendation. +3. Implement required behavior and its producer/consumer prerequisites in coherent owner PRs. Prepare each section with a short design-authority check, then use the paired whole-section assessment defined by the [plan](./whole-corpus-authority-review-plan.md#implementation-and-review-method) when its implementation state can support closure. +4. Revisit every provisional section as dependencies advance, repeating the return sweep until the final section gates are satisfied. Then reconcile owner/secondary/tracker consistency and validate the complete corpus. +5. Keep the completed taxonomy, allocation, inventory, point-in-time reconciliation, human-led decision review, and selective ADR import as historical prerequisites rather than phases to rerun. ## Automated Gates diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index 2309011d8a..aa97b496a6 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -1,16 +1,16 @@ # Whole-Corpus Authority Review Plan -This is the maintained scope and method for the post-ADR corpus review. The [alignment index](./README.md#corpus-section-programme-status) is the **only live section-status table**. This plan defines section boundaries and starting source manifests; neither file gives technical authority. Canonical product and architecture documents own target behavior, and implementation trackers own implementation/proof state. +This is the maintained scope and method for the post-ADR corpus programme. The [alignment index](./README.md#corpus-section-programme-status) is the **only live section-status table**. This plan defines section boundaries and starting source manifests; neither file gives technical authority. Canonical product and architecture documents own target behavior, and implementation trackers own implementation/proof state. ## Purpose and sequence -The capability allocation, human-led adversarial ADR review, selective accepted-decision application, and point-in-time implementation reconciliation preceded this effort. This review now checks the *whole* product and architecture corpus for missing or conflicting contracts, duplicate normative owners, broken owner/consumer handoffs, and misleading implementation or proof claims. It preserves useful local consequences while keeping one canonical owner. It is not another ADR decision round and does not imply that every target capability must be implemented before the corpus can be aligned. +The capability allocation, human-led adversarial ADR review, selective accepted-decision application, and point-in-time implementation reconciliation preceded this effort. The corpus programme checks the *whole* product and architecture corpus for missing or conflicting contracts, duplicate normative owners, broken owner/consumer handoffs, and misleading implementation or proof claims. It preserves useful local consequences while keeping one canonical owner. It is not another ADR decision round. Document also implements accepted pre-v1 requirements and their prerequisites before claiming a section complete; deliberately later target features remain outside that gate only with a documented reason and activation boundary. -After the section passes, reconcile affected live trackers where target, implementation, proof, or gap status changed. Then run one corpus-wide owner/secondary/tracker consistency check and the documentation validation gates before claiming the post-ADR alignment effort complete. Capability implementation continues separately under the domain trackers. +The first stage catches up known required work; implementation and review then proceed section by section. Previous reviews, fixes, and evidence remain valid history, but an earlier review stop or taper does not establish the new completion gate. Reconcile live trackers as work changes target, implementation, proof, or gap status. After section completion, run a corpus-wide owner/secondary/tracker consistency check and the documentation validation gates before claiming the post-ADR programme complete. ## Section boundaries -The 23 original family sections remain the top-level corpus map, but 5B is now pre-split into three semantic review subunits: 5B-Schema, 5B-Publication, and 5B-Retention. This produces 25 review units while preserving one Shared Runtime family and one 5B source union. The split responds to repeated implementation expansion across migrations, services, runtime code, and proof; it is a review-scope split, not a map of implementation PRs. The 21 recovered exact manifests from the pre-split plan each contained 10–18 existing source paths before heading-scoped overlap was counted. This restart resets **review coverage**, including previously completed 5A; it does not undo merged code or accepted ADRs. The two missing manifests, 7A and 7B, are supplied below. These numbered lists are starting anchors, not an exhaustive inventory of allocated sources. At section start, use the current [design allocation](./design-capability-allocation.md) to identify all primary sources and separately record material secondary handoffs. A source can be read in more than one section for a specific heading-scoped handoff; that does not create two normative owners. +The 23 original family sections remain the top-level corpus map, with 5B split into three semantic review subunits: 5B-Schema, 5B-Publication, and 5B-Retention. This produces 25 review units while preserving one Shared Runtime family and one 5B source union. The split responds to implementation expansion across migrations, services, runtime code, and proof; it is a semantic boundary, not a map of implementation PRs. The 21 recovered exact manifests from the pre-split plan each contained 10–18 existing source paths before heading-scoped overlap was counted. The earlier restart and its review coverage remain historical evidence; this method does not undo merged code or accepted ADRs. The two missing manifests, 7A and 7B, are supplied below. These numbered lists are starting anchors, not an exhaustive inventory of allocated sources. At section start, use the current [design allocation](./design-capability-allocation.md) to identify all primary sources and separately record material secondary handoffs. A source can be read in more than one section for a specific heading-scoped handoff; that does not create two normative owners. | Family | Sections | Boundary | | --- | --- | --- | @@ -22,17 +22,25 @@ The 23 original family sections remain the top-level corpus map, but 5B is now p | Edge and delivery | 6A–6D | Routes; protocol transport; operator ingress; environments and deployment | | Observability and proof | 7A–7C | Logs/metrics/tracing/SLOs; verification and recovery evidence; incident/operational proof | -**5B decision before restart:** pre-split the 18-source 5B corpus union into three semantic review subunits: **5B-Schema** for SQL/schema/identifier evolution, **5B-Publication** for durable version/publication/readiness state, and **5B-Retention** for retention, cleanup, and recovery-safe durable state. Each subunit has its own heading-scoped manifest, fresh unrestricted coverage, finding adjudication, and taper. A mandatory whole-5B synthesis then checks the shared identities, migration gates, publication terminality, retention horizons, and owner handoffs across all three subunits. The synthesis is a review gate, not a fourth implementation PR. Findings that cross subunit boundaries return to the owning subunit; findings owned by 5C, 5D, 6D, 7B, 7C, or another product/domain section remain explicit handoffs. The four implementation PRs are preserved evidence and are not section boundaries: their scopes combine or omit portions of these subunits and include adjacent-family work. Reconcile and assign their remaining work when 5B resumes after 5A; do not count their historical reviews as new subunit coverage. +**5B historical boundary:** the 18-source 5B corpus union was split into **5B-Schema** for SQL/schema/identifier evolution, **5B-Publication** for durable version/publication/readiness state, and **5B-Retention** for retention, cleanup, and recovery-safe durable state. Their independent reviews and paired whole-5B synthesis remain evidence of earlier alignment work, not final implementation-first section completion. A future completion attempt retains the three semantic boundaries and checks shared identities, migration gates, publication terminality, retention horizons, and owner handoffs across the union. Findings cross back to their owner; 5C, 5D, 6D, 7B, 7C, and other domain work remain explicit dependencies or independent handoffs. Implementation PRs are not section boundaries. -## Review and tracking method +## Implementation and review method -1. Start with 5A. Before each section or 5B subunit, refresh its starting manifest against current allocation, canonical owner links, ADR rationale, consumer handoffs, and live trackers. Expand each ordinary section's numbered source list to include every allocated primary source within its boundary; for 5B, retain one 18-source union and record each subunit's selected heading-scoped anchors, overlaps, and explicit handoffs without requiring every subunit to repeat all 18 paths. Every numbered source path below existed when this plan was rebuilt, but inclusion is a review input, not an assertion that its wording remains correct. -2. Run a fresh broad pass over the **entire section or subunit**, including unchanged sources and material code/proof consequences. A focused check can answer a finding but does not replace broad discovery. Normalize findings by underlying issue; apply coherent fixes, route substantial implementation work to its owner, and retain honest tracker gaps. For 5B, the three subunit passes are independent coverage obligations; implementation PR topology must not substitute for them. -3. Repeat broad passes on the corrected state while they find useful work. Each 5B subunit needs its own coverage account, finding dispositions, and evidence-based taper. After the subunits reach their local terminals, run the mandatory whole-5B synthesis over the 18-source union and all material overlaps. Any useful synthesis finding reopens the owning subunit and requires a new synthesis pass after correction. No fixed pass count or demand for a review of every fix SHA overrides that judgment. PR-wide CodeRabbit and CI assess changed code and merge risk; they do not prove unchanged corpus coverage. -4. Update **only the alignment index** for section/subunit status, main PR, completion evidence, and routed obligations. The index keeps the three 5B subunit rows under the two-document tracking model; record their evidence and routed work in the planned **Evidence / routed work** column. Record the whole-5B synthesis as a non-row evidence line associated with those three rows, never as an aggregate 5B status row. The index must not become a PR-shaped ledger. A split implementation PR is linked from the relevant subunit evidence rather than creating a PR section. Keep detailed finding evidence with the relevant review/PR artifacts, not a second live section-status ledger. Any future semantic boundary change must update both maintained documents before assigning new subunits or PRs. -5. A section is complete only when its refreshed source list and material handoffs have been assessed, valid findings are fixed or explicitly owned elsewhere, and the current review has tapered. For 5B, completion additionally requires all three subunit terminals plus a tapered whole-5B synthesis. Record each subunit's reviewed/allocated source count, evidence, and routed work in the index; record synthesis evidence on its non-row line. At final closeout, compare the union of the refreshed section and subunit lists with the [allocation](./design-capability-allocation.md): every allocated source must be reviewed in an owning section, explicitly handed off by heading, or listed as an exemption with a reason. Merging one PR alone does not establish section or subunit completion. +### Phase 1: catch up known work -When Overseer closes broad discovery for a section by explicit judgment before taper, record that as a discovery stop, not section completion or merge readiness. Before handing off the section, reconcile each accepted finding and relevant tracker gap against current behavior: implement unsafe exposed paths in their owning boundary, or assign substantial pre-v1 work to a concrete owner and successor with dependency and activation gate. A tracker link alone does not remediate a live defect. Record deliberately deferred features with their containment, reason and revisit trigger; keep unexecuted PostgreSQL, cross-service and deployment proof attached to the applicable readiness gate. Preserve the difference between whole-corpus coverage, implemented capability and exercised proof in the index and owning trackers. +1. Preserve published PRs, corrected code, earlier review evidence, and finding dispositions. Reclassify an earlier “complete” section as **provisional** when accepted required pre-v1 implementation or essential proof remains. Do not replay historical review cycles merely because the completion rule changed. +2. Reconcile known findings and implementation-tracker rows against current code. Decide what is already resolved, required for pre-v1, or deliberately later. Record later work with its reason, containment or activation boundary, and revisit trigger. Document makes routine scope calls; bring consequential or genuinely ambiguous decisions to Overseer in small batches with a recommendation. +3. Order accepted pre-v1 work by dependency and implement it in coherent owner PRs, including shared prerequisites and cross-service consumers where the invariant requires them. Document owns this work unless another active worker owns the slice. Before substantial cross-service work, briefly verify the canonical design and producer/consumer contracts. The entire repository need not be feature-complete before a substantially implemented section resumes broad review. + +### Phase 2: work through each section + +1. Refresh the starting manifest against the current allocation, canonical owner links, ADR rationale, material secondary handoffs, live code, proof, and tracker gaps. Expand each ordinary section's numbered source list to cover its allocated primary sources; keep the 5B union and heading-scoped subunit boundaries. Check the target design briefly and resolve consequential ambiguity before implementation. Reuse earlier findings as inputs without replaying their review cycles. +2. Implement required pre-v1 behavior and the prerequisites needed for that section's current paths in coherent owner PRs, with focused proof and honest tracker status. Deliberately later features need an explicit reason and activation boundary. If a real dependency prevents progress, mark the section provisional and do another useful section or prerequisite slice rather than repeatedly scanning the blocked state. +3. Focused review sub-lanes may investigate difficult areas. For a section-closure attempt, assign **two fresh independent unguided reviewers in parallel**, each covering the complete changed and unchanged semantic section, material code and tests, proof claims, normative authority, and owner/consumer handoffs. Adjudicate their results as one paired round, deduplicated by underlying issue. Do not seed either reviewer with a list of prior findings. A focused check or PR-wide CodeRabbit review cannot substitute for this whole-section assessment. +4. Fix a material behavior or contract finding in its owner boundary and make another paired whole-section assessment of the corrected state. An isolated wording, fixture, or test correction needs focused validation and an explicit closeout judgment rather than an automatic broad restart. Numerical zero-finding streaks and arbitrary cycle counts do not decide corpus completion. If repeated independent side findings make the review unconvincing, leave the section provisional; do not create detailed partial-coverage records or narrow the return prompt to avoid those findings. Return later to a fresh unguided ground-up whole-section assessment after relevant implementation advances. +5. A finding that affects this section's current behavior or prerequisite blocks completion even when its code owner is an adjacent service. A genuinely independent side finding is recorded in its owning tracker/section and does not force this section's PR to absorb it. Split an unusually broad section into coherent semantic parts when needed, then perform a final whole/cumulative synthesis; PR topology alone never defines corpus scope. +6. Mark a section **corpus complete** only when accepted required pre-v1 behavior and prerequisites are implemented, the target design and implementation/proof claims agree, the final whole-section assessment is convincing, and no material section finding remains. Essential implementation proof that is absent keeps the section provisional; proof that necessarily requires post-merge activation stays a separate named gate. Update only the [alignment index](./README.md#corpus-section-programme-status) for current section status and concise evidence; keep detailed findings in owning trackers and PR/review artifacts. Merging a PR, completing its CodeRabbit review, or passing CI alone does not complete a corpus section. +7. After the first traversal, revisit **every provisional section** in dependency order as implementation and proof advance. Repeat that return sweep as often as needed; it is not a one-time second pass. Each return reassesses the section from current code and contracts with fresh unguided whole-section reviewers when closure is attempted. At final programme closeout, compare all refreshed source lists with the [allocation](./design-capability-allocation.md): each allocated source must have an owning section, an explicit heading-scoped handoff, or a reasoned exemption. Then run the corpus-wide owner/secondary/tracker consistency and documentation checks. ## Starting manifests @@ -97,6 +105,8 @@ Unit 1B's substantive boundary is the following 16 admission, binding, continuit Review LOGIN versus PLAY, explicit JOIN and fresh Account evidence, public versus private/playtest admission, realm/pointer/catalog/namespace selection, roster discovery versus independent actor validation, namespace-scoped controller generation and takeover, liveness versus continuity/resume/physical TTL, fresh-edge versus retained-edge recovery, reauthentication and revocation, bounded semantic context, fresh LOOK, and disconnect deduplication. Unit 1B consumes 1A Account authority and 5A shared token/identity primitives; 1C owns rendering, 6A/6B own edge/transport carriage, and gameplay/tick owners remain outside this unit. Refresh when those consumed admission, pointer, transport, Redis, or replay contracts change materially. +Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, signed first-party connect-context handoff, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three earlier independent corrected-state reviews assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. The superseding cadence then completed two fresh serial whole-unit Luna cycles after known owner corrections and the separate Account/edge email-link child. Cycle 1 accepted current-status and post-logout corrections; Cycle 2 found one new local cross-source status conflict and repeated three already-owned activation obligations. That local conflict was corrected, validated and published. The two-cycle report boundary preserves useful alignment evidence without claiming section completion, merge readiness, or live activation. Unit 1B remains provisional until its accepted required pre-v1 work and essential proof meet the implementation-first closure gate above. + ### 1C Unit 1C's substantive boundary is the following 14 command, output, and presentation sources: @@ -469,7 +479,7 @@ The subunit checks terminality, blockers, holds, horizons, safe watermarks, reta #### Whole-5B synthesis and handoff gate -After each subunit has completed its independent fresh coverage and taper, run one unrestricted synthesis over the complete 18-source union and every declared overlap. The synthesis must reconcile the durable identity tuple across schema and publication records; migration compatibility against published and retained versions; readiness terminality against retention and cleanup; owner-local foreign-key and mapping consequences; and the boundary from 5B durable state into 5C Redis, 5D transactions/replay/workflows, 6D deployment/reset/backup, and 7B/7C proof. A useful synthesis finding returns to the owning subunit and requires a new synthesis pass after correction. The 5B family is complete only when all three subunits and this synthesis have tapered; no child PR's closure or historical review count satisfies that gate. +When the three subunits reach their implementation-first closure gate, make a paired unrestricted whole-5B synthesis over the complete 18-source union and every declared overlap. The synthesis must reconcile the durable identity tuple across schema and publication records; migration compatibility against published and retained versions; readiness terminality against retention and cleanup; owner-local foreign-key and mapping consequences; and the boundary from 5B durable state into 5C Redis, 5D transactions/replay/workflows, 6D deployment/reset/backup, and 7B/7C proof. A material synthesis finding returns to the owning subunit and requires corrected-state whole-5B assessment after the fix. Earlier tapered reviews remain historical alignment evidence; neither their counts nor child-PR closure establishes this final completion gate. ### 5C diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 50443461bd..878aea6301 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -111,7 +111,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`/`CHARS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and for deliberate logout, transport loss, and takeover; scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits, with producer-owned `exitReason` metadata. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, and direct `PLAY` only when admission succeeds. Currently the Account runtime membership read fails closed before data access, and Game Session maps its in-band `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE`, so current direct-text `PLAY` does not reach command publication. Automation's `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiver RPCs fail closed before live mutation because the admission-epoch receiver fence is absent; lower-level helper proof does not establish a live `onCommand` producer for Automation handoff or remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` has conditional publication from `PlayCommandHandler` for fresh `PLAY`, but no current production route reaches it; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 1f663310f5..d6f0473c10 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -83,7 +83,7 @@ The implemented settings path uses service-local typed defaults plus Game Design Typed property binding, scoped JSONB overrides, runtime consumption, and effective-settings readback are live across Game Session and Game Logic. The old Game Session file/environment tenant/game override path was removed. Topology settings are normalized before readback, movement and topology are inspectable, and runtime readers use a short TTL cache with explicit scope refresh/eviction; later routing and communication-scope adoption remains incomplete. -Reconnect settings resolution and readback are live, but stable-namespace scoping, resume-window and context-generation enforcement, strict complete-envelope bounds, both reconnect-prompt branches, end-to-end no-buffer first-party fresh-`LOOK` reconstruction proof, and first-party post-logout suppression remain incomplete or unproved. The target and detailed status remain with [Reconnection](../../architecture/system-architecture-reconnection.md), [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md), and the [Player Access and Session tracker](./player-access-and-session.md#reconnect-and-continuity). `MoveCommandHandler` reads post-move redraw policy from typed configuration. +Reconnect settings resolution and readback are live, but stable-namespace scoping, resume-window and context-generation enforcement, strict complete-envelope bounds, end-to-end no-buffer first-party fresh-`LOOK` reconstruction, and durable post-logout episode fencing remain incomplete or unproved; focused local tests cover both reconnect-prompt branches and fresh first-party replay suppression after attempted `LOGOUT`. The target and detailed status remain with [Reconnection](../../architecture/system-architecture-reconnection.md), [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md), and the [Player Access and Session tracker](./player-access-and-session.md#reconnect-and-continuity). `MoveCommandHandler` reads post-move redraw policy from typed configuration. Bounded built-in and room-locale groundwork is live, while broader authored-content coverage, creator/browser workflows, fallback and malformed-tag proof, and external tooling remain incomplete. The target and detailed status remain with [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#localization-and-translation) and the [Player Experience tracker](./player-experience-commands-and-communication.md). 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 0ad45924d8..4cc47bf5b3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,11 +8,17 @@ This is a non-normative implementation tracker for player access and session. Ca The storage-only UUID prerequisite now persists an immutable, unique, non-nil Account UUID with provenance and the unchanged numeric source-row id through V29. Game Session V11 adds nullable Account UUID evidence to the gameplay command ledger and repository round-trip while preserving retained numeric Account IDs; historical commands receive no inferred UUID. No producer or session carrier supplies or consumes these UUIDs, and this storage work does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. Focused PostgreSQL repository and migration cases are present but skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no runtime-proof upgrade. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). -The Account JOIN worker's positive audit evidence now includes an explicit version-1 COMMITTED receipt/projection marker and nonblank receiver identities from the locked scoped outbox row. The composed Logging & Admin child implements local typed receipt/projection and readback, with focused local unit and offline-fixture proof; Account's producer-side verified-projection compare-and-set marker handling is also local. Production `CreateLogEvent` remains disabled, so new and outstanding audit rows remain pending; PostgreSQL runtime, direct text-to-Logging, exact retained-receipt/readback, guarded Account evidence-recording, retained-evidence disposition, and finite-retention proof remain open. Retained legacy JOIN IDs without the marker remain unresolved and are never promoted by deploying the receiver. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receiver implementation and proof remain under #2940. See [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) for the canonical receiver contract and current implementation status. +The Account JOIN worker reads locked scoped outbox rows and requires an explicit version-1 COMMITTED receipt/projection marker with nonblank receiver identities. Account's producer-side typed receipt validation and verified-projection compare-and-set marker handling are local; the composed Logging & Admin receiver persistence/readback is also local, with focused unit and offline-fixture proof only. Live `CreateLogEvent` returns non-OK `UNAVAILABLE` after exact Account workload authentication and before storage; `ReadLogEventReceipt` remains available, but Account audit delivery is unscheduled, so new and outstanding registration/JOIN outbox rows remain `PENDING`. Offline fixtures do not prove positive receiver, projection, or live-delivery behavior; historical rows with unknown projection provenance and retained legacy JOIN IDs without the marker remain unresolved and are not promoted by fixture markers or receiver deployment. PostgreSQL runtime/execution, direct text-to-Logging, exact retained-receipt/readback, guarded Account evidence-recording, retained-evidence disposition/readback, safe-watermark, hold/reference, cleanup, finite-retention, and positive delivery activation proof remain open. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receiver implementation and proof remain under #2940. See [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) for the canonical receiver contract and current implementation status. -Live `CreateLogEvent` writes return non-OK `UNAVAILABLE` after exact Account workload authentication and before storage, and Account audit-delivery scheduling is disabled, so new and outstanding registration/JOIN audit rows remain `PENDING`. `ReadLogEventReceipt` remains live. Positive receiver, projection, and producer-delivery behavior is limited to offline fixture proof until retention and cleanup are implemented and proved; fixture states and version markers do not upgrade retained historical evidence. +Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, owner-local Account audit outbox, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct-text `JOIN` dispatch exist locally, but Gateway blocks external route exposure and first-party browser `Join & Play` remains unavailable; those seams do not establish current public JOIN or composed admission. -Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, the owner-local Account audit outbox and producer-side typed receipt validation, the composed child's local Logging & Admin receiver/readback code, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct-text `JOIN` dispatch exist locally, but Gateway blocks external route exposure and first-party browser `Join & Play` remains unavailable. The bounded Account JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize, while absent or uncertain evidence remains pending with capped diagnostics/backoff, never because of expiry or attempt limit. PostgreSQL lost-acknowledgement/concurrency, direct text-client-to-Logging end-to-end proof, and Account's independent connect-token issuance-time membership-version/authority-generation reread proof remain open. Current `PLAY` and connect-token issuance remain partial: local `PLAY` validates lifecycle/version/generation on supplied-authority branches, but live Account runtime readers fail closed before data access. Account membership and realm-grant authorities remain separately owned. Namespace-aware binding, resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and durable post-logout `resumeContextGeneration` fencing remain incomplete. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. +The Account JOIN worker is readback-only. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; the worker cannot resubmit the expired bearer-bound request and can terminalize only exact positive prior-commit operation/scope/membership/audit evidence. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending with capped diagnostics and backoff. Terminal replay is fenced to the authenticated caller, exact target and intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL lost-acknowledgement/concurrency, unknown-outcome recovery, and direct text-client-to-Logging end-to-end proof remain open. + +Game Session locally validates identity, lifecycle, membership version, authority generation, and freshness on supplied-authority `PLAY` branches, but Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority classification is not composed admission proof: live text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` because caller/target authority is unavailable, while reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Roster access is not live or proven, and no synthesized account/name/hash actor fallback is permitted. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity/activity fields. Positive gameplay-grant elevation proof remains open. + +The catalog and `GetAdmissionPointer` fail closed unless the tenant has exactly one visible public-production realm. Existing duplicates remain a data-decision and activation gap; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Direct-text Account scope issuance checks current entitlement and denies missing, ambiguous, unavailable, or gameplay-blocked authority before retaining scope. Account connect-token issuance separately lacks the membership-version/authority-generation baseline reread and applicable private-grant validation; cached-success replay now verifies the stored result binding and rereads the current target, entitlement and membership before returning the original token without reminting or extending its lifetime. These bounded corrections do not establish complete live admission or `PLAY`. Namespace-aware binding, effective resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and broader cross-transport continuity remain incomplete. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. + +Reconnect/context persistence is partial: private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`, fresh accepted `PLAY` still renders an authoritative `LOOK`, and successful logout is unavailable. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects and does not clear the active binding or prove logout. Exact current `resumeContextGeneration` and durable terminal-episode/binding evidence are absent, so post-logout generation fencing and safe replay remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -20,7 +26,7 @@ Account runtime admission reads remain a capability/proof blocker. `GetTenantMem Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. -PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. +PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. The Unit 1B child removes `PLAY`'s synthetic account/name/hash fallback and requires a persisted account-roster actor after admission checks, with focused foreign-owner, malformed-row, absent/ambiguous roster, and no-mutation negatives. That Entity list is not yet namespace/policy-qualified, and Account's runtime reads still deny before data access; `CHARS` now returns unavailable before Entity access. These are safety corrections, not a working complete actor-entry path. Typed Account caller/target authority, stable namespace and policy snapshot, descriptor/template resolution, zero/one/many entry behavior, and fork-local copy proof remain ordered pre-v1 work and do not upgrade AA-2.1 status. Current `AA-2.1` consequence: Game Session fails closed for production `CHARS` and `PLAY` roster access because the live `ListCharactersByAccount` request and returned `Character` omit `playableStateNamespaceId`; `gameInstanceId` cannot replace that stable durable actor identity. The shared Entity client returns the existing `CHARACTER_LIST_UNAVAILABLE` outcome without calling the legacy RPC; `CHARS` remains unavailable and `PLAY` preserves `PLAY_IDENTITY_UNAVAILABLE` before binding. Existing positive handler fixtures are offline-only proof of result mapping. The target namespace and actor rules remain owned by [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity Management API](../../architecture/microservices/entity-management-service/api-contracts.md). Namespace-qualified Entity authority, retained-row convergence, and its required migration gate remain separate gaps; `WORLDS` and `REALMS` continue through their current discovery paths. @@ -47,7 +53,19 @@ Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, | Official-hosted creator terms and future creator commerce | Account acceptance authority, Game Design mutation/readback gate, Platform `PO-2.1` edge; separate accepted product successor for commerce | Gateway exposes only safe GETs for now. Official hosted writes stay unavailable until current acceptance/changed-terms negative owner-side proof; creator purchases, tips, payouts and entitlement issuance remain unsupported pending separate product/authority acceptance. | | Audit producer/receiver retention, migration, certificates and live proof | Account `AA-1.1`/`AA-1.2` producer, Logging receiver, #2847/#2848 readiness | Execute PostgreSQL receipt/projection and retained-row tests, verify exact workload certificate/render and direct text-to-Logging delivery, and define safe-watermark/hold/reference cleanup for committed payloads before long-running activation. Skipped local tests and green documentation checks do not close these gates. | -Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Its first whole-unit review has not begun; the Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. +Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Three earlier fresh corrected-state reviews covered the complete 16-source semantic unit across unchanged authority, implementation, proof, and owner/consumer handoffs; all three found material local corrections. The subsequent two serial whole-unit passes and their accepted local corrections remain historical evidence, not a current section-exit cadence or completion claim. Future section-exit assessment follows the [paired parallel review method](../design-alignment/whole-corpus-authority-review-plan.md#implementation-and-review-method). Neither the earlier report boundary nor the canonical cadence is a merge-readiness claim. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works. + +## Unit 1B Section-Exit Dispositions + +| Open item | Owner and ordered correction or successor | Current containment and exit proof | +| --- | --- | --- | +| Incorrect currently reachable Game Session behavior | Unit 1B #2857 | Current containment removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests have run; composed proof limitations remain as recorded below. | +| Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | +| First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | +| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact cached-success replay verifies the stored result binding and rereads the current pointer/target, entitlement and membership before returning the original bounded-lifetime token; it neither mints nor extends the token. Applicable private-grant and membership-version/authority-generation revalidation remain incomplete. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the complete immutable issuance baseline, generation/grant recheck and ambiguous-ack retry outcome before enabling admission; the focused cached-success denial/replay tests do not establish full admission. | +| Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after attempted `LOGOUT`, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | +| Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | +| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Historical CI run `36006632988` targeted code head `28028878d52df0dfce367bce1677a985b162115f`, not the current head: it executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green, and all 27 WebSocket integration cases passed. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures also occurred on that earlier head. These historical results do not establish current-head proof, typed Account admission, or the remaining successor contracts. | Exact #2848 composed CI run `35968901756` passed Account Build/Test with executed PostgreSQL integration but did not pass the whole Validation Gate. Automation's four PostgreSQL failures also occurred on an earlier ancestor run and are separate owner-side defects. TCP Proxy recorded 13/17 failed cross-service tests. Game Session recorded 38/39 failed after all 39 tests completed; cancellation followed the 20-minute timeout of job `107534169149`, not fail-fast behavior, and matrix fail-fast was disabled. Representative `PLAY_IDENTITY_UNAVAILABLE` traces stop at the unchanged Game Session `GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle` during Entity character lookup, before Account's new runtime-read denial is reached. The #2848 unique diff changed neither Game Session nor TCP Proxy production code. This is inherited composed Game Session setup/admission proof debt, not evidence that the Account patch caused the failure or that the Account–Game Session handoff is working. Unit 1B must correct or seed the admitted routing bundle under its canonical owner, execute focused PLAY cross-service tests through both transports, and then rerun the affected suites; the subsequent Account authority reads may expose additional intentional fail-closed gates. @@ -62,13 +80,13 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. A verified terminal minimized receiver receipt now compacts Account's producer payload while retaining audit identity and digest; cleanup of still-`COMMITTED` payloads awaits configured safe-watermark, hold, reference, and finite-retention proof. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Account V29 and `AccountRepository` persist or read back the immutable unique non-nil UUID with provenance while retaining the numeric source-row id; focused PostgreSQL repository and retained-row migration cases are present but skipped locally because Docker is disabled. This UUID remains storage-only and is not used in authentication outputs or downstream session carriers. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rereads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to the verified caller/scope and policy evidence. It atomically persists membership, terminal operation outcome and tenant audit outbox evidence, but it does not guarantee that the exact Game Session target/catalog/pointer remains valid through Account commit: the strict ADR 0025 commit fence remains incomplete. The subscription authority query locks only the subscription row, not its joined billing-owner Account; JOIN separately locks the caller Account and operation record. Terminal replay performs remote scope/target/entitlement checks outside the lock-holding transaction; unit proof covers replay after commit or rollback without rewriting the stored outcome, while the PostgreSQL row-lock regression is Docker-skipped locally. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are now swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. The Account-owned worker rechecks only exact positive operation/scope/membership/audit evidence before terminalizing; expired scopes on retained `PENDING` intents remain pending and return retryable `AUTH_UNAVAILABLE`, with no scope reissue or terminalization for expiry, attempt limit, absent, or uncertain evidence. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unclaimed; do not mark ADR 0025 complete. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target gets retryable `AUTH_UNAVAILABLE`, while unbound private selectors keep the generic hidden projection. Text `PLAY` still requires admitting membership before its applicable Account-owned realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Producer-side proof covers compaction after a verified terminal minimized receiver receipt while retaining audit identity and digest; live `CreateLogEvent` currently returns `UNAVAILABLE` and Account delivery is unscheduled, so new/outstanding rows remain `PENDING`. Historical rows with unknown projection provenance are not promoted. Cleanup of still-`COMMITTED` payloads awaits configured safe-watermark, hold, reference, and finite-retention proof; PostgreSQL runtime and retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Account V29 and `AccountRepository` persist or read back the immutable unique non-nil UUID with provenance while retaining the numeric source-row id; focused PostgreSQL repository and retained-row migration cases are present but skipped locally because Docker is disabled. This UUID is storage-only and is not used in authentication outputs or downstream session carriers. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Fresh connect-token issuance and cached-success replay share current pointer/target, entitlement and membership checks; cached replay also verifies the stored result binding and never remints or rewrites the successful result. Generation/grant and commit-postcondition revalidation remain unproved. The explicit JOIN operation validates a server-issued scope and caller, rereads Game Session routing/catalog/pointer evidence before its Account transaction, and binds a version-1 digest to caller/scope and policy evidence; membership, stored outcome, and tenant audit outbox row persist atomically, but exact target/catalog/pointer validity is not guaranteed through commit and the strict ADR 0025 commit fence remains incomplete. The subscription authority query locks the subscription row but not its joined billing-owner Account; JOIN locks the caller Account and operation row. Terminal replay's remote scope/target/entitlement reads occur outside the lock-holding transaction; unit proof covers replay after commit or rollback without rewriting stored outcome, while the PostgreSQL row-lock regression was Docker-skipped. Global-only registration creates no admitting membership. Expired unreferenced connect scopes are swept, and V27's restrictive FK preserves scopes referenced by PENDING or terminal JOIN records and fences racing intent inserts. The bounded worker is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence; an expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, and the worker does not resubmit the bearer-bound request or terminalize from expiry, attempt limit, absent evidence, or uncertainty. Exact replay remains fenced to caller, target, intent, and retained policy digest. New/outstanding audit rows remain `PENDING` because live `CreateLogEvent` is `UNAVAILABLE` and delivery scheduling is disabled; positive delivery/receipt handling is offline fixture proof, and historical unknown provenance is not promoted. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Runtime membership authority-generation evidence, issuance grant validation, complete cached-success generation/grant and commit-postcondition revalidation, and the target five-field grant codec remain incomplete. Game Session omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); fresh caller-bound prior snapshots for the exact current private target receive retryable `AUTH_UNAVAILABLE`, while unbound selectors remain hidden. Account's runtime membership, entitlement, and grant handlers fail closed before reads; text `PLAY` and namespace-qualified `CHARS` remain unavailable, not positive admission proof. Other transactional outboxes, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). Do not mark ADR 0025 complete. The target five-field grant codec still requires cross-service producer/consumer and admission-propagation proof; text `PLAY` requires admitting membership before its applicable Account-owned grant, and connect-token issuance does not yet validate that grant. | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses; unknown addresses create no token or delivery attempt, and known-account post-commit SMTP exceptions are contained and logged. Delivery remains synchronous after commit, so timing resistance and durable asynchronous delivery remain unproved; current tests prove error containment only. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | | `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. Focused repeated-call tests prove the three methods create no `PaymentService` or provider interaction. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID, and focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. | -| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with supplied-authority unit proof for local public-production admission classification. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but not namespace-aware actor revalidation or target binding-generation fencing; no synthetic account/name/hash actor fallback is permitted. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission; valid-route live text `PLAY` maps in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable membership `NOT_FOUND` and `PERMISSION_DENIED` remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Account connect-token issuance requires existing membership, but a cached-success replay now repeats current pointer/target, entitlement and membership reads without minting or extending the original token; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; malformed actor rows and normalized-duplicate IDs remain unvalidated response cases because the current handler stops before those responses. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID. Focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and this storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. | +| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. The first-party private-transcript fence is a fail-closed boundary and does not establish durable post-`LOGOUT` replay suppression. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. The target fresh-edge input-replay, fresh-`LOOK`, and reconnect-prompt rules are owned by [Reconnection](../../architecture/system-architecture-reconnection.md); current proof of their composed behavior remains open. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; that local suppression does not establish durable post-logout replay fencing. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. Current proof asserts `LOGOUT_UNAVAILABLE` and no side effects. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this work does not complete AA-2.1, first-party `Join & Play`, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject `stateScope` values other than exact `SHARED` or `ISOLATED`. Account-owned public-production JOIN writing and Game Session direct text JOIN dispatch are implemented locally. Expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence may terminalize, and absent or uncertain evidence remains readback-only and pending. The live Account membership/grant/entitlement runtime readers still fail closed before data access, so first-party `Join & Play`, direct text-client end-to-end proof, PostgreSQL lost-acknowledgement/concurrency proof, complete authority, and target admission-pointer fields remain open as recorded above. @@ -92,7 +110,8 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. On a fresh connect-token issuance or cache miss, issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; a cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not revalidate the applicable non-public grant, so that target grant-validation proof remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Current text `PLAY` outcome mappings and proof status are recorded under [AA-2.1](#capability-status); an in-band Account entitlement `FAILED_PRECONDITION` remains retryable `ENTITLEMENT_UNAVAILABLE` and preserves the existing gameplay binding, not a billing denial. +On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay verifies its stored request/result binding and repeats those reads before returning the original token without minting, extending its expiry, or rewriting session/cache state. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Account's `JoinPublicProductionMembership` writer and `POST /auth/bootstrap/join` operation, plus Game Session's direct text `JOIN` dispatch, are implemented locally; the current Gateway guard blocks external Account HTTP exposure and first-party `Join & Play` remains unavailable. The bounded worker is readback-only: expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, does not reissue scope, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Connect-token issuance's membership-version and authority-generation baseline reread remains unimplemented; canonical JOIN eligibility and ordering remain defined by [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). @@ -106,7 +125,7 @@ Live Account authentication hashes and verifies passwords with `argon2-jvm` Argo Telnet and generic WebSocket clients share one Game Session line-oriented parser/interpreter and gameplay queue. The parser trims input, accepts case-insensitive command names, handles empty or malformed lines, and maps unknown commands to `UNKNOWN`; Telnet performs no separate gameplay parsing. The current canonical flow is optional `WORLDS`, `LOGIN`, `PLAY`, and gameplay commands such as `LOOK` and `SAY`, with built-in `LOGOUT`. `LOGON` remains an accepted login spelling where the protocol documents it. The old typed `SESSION` attach flow is not part of the canonical initial-development protocol; future smart-client metadata, if revived, is transport metadata rather than a player command and is never authoritative. -TCP Proxy bootstrap metadata is proxy-owned hidden transport context, not a player-visible attach command. `TelnetSessionContext` and `TelnetServerHandler` validate the envelope before forwarding it, record connect events with session/tenant/client identity, reconnect with bounded backoff, preserve ordered buffered input, and close once `MAX_BUFFER_DEPTH` is exhausted while metering discarded input. Telnet logging redacts `LOGIN` arguments. `NotifyDisconnect` validates proxy/session identity, maps a proxy connection to the authenticated session where possible, records suspension for unexpected loss, and returns application-level `ErrorDetail` results while metering duplicate, missing-context, transport-failure, and application-error classes. **Current implementation gap:** Redis sequence dedupe fails open on Redis errors and is reset-loss-vulnerable, and no current connection/generation binding guard precedes presence, region-exit, or `GameInstance` suspension effects. The live path is therefore not yet proof of the target advisory safety contract; the eventual binding design is not specified here. +TCP Proxy bootstrap metadata is proxy-owned hidden transport context, not a player-visible attach command. `TelnetSessionContext` and `TelnetServerHandler` validate the envelope before forwarding it, record connect events with session/tenant/client identity, reconnect with bounded backoff, preserve ordered buffered input, and close once `MAX_BUFFER_DEPTH` is exhausted while metering discarded input. Telnet logging redacts `LOGIN` arguments. `NotifyDisconnect` validates supplied instance ownership, meters duplicate and missing-context hints, and returns application-level `ErrorDetail` results; it currently makes no presence, region-exit, or instance-suspension mutation because the proxy hint lacks proved current binding/generation authority. Redis sequence dedupe still fails open on Redis errors and is reset-loss-vulnerable. A current-connection/generation compare and stale-hint/Redis-loss proof are required before target lifecycle effects can be enabled. `LOGIN` is available in parameterized text form as `LOGIN ` and in challenge-initiation form as `LOGIN `. The supplied secret is one opaque value forwarded to Account Service. Account Service interprets it from the account's enabled modes rather than guessing from its shape: live policy tries a valid active email code before password fallback when both are enabled, and rejects modes that do not permit email OTP. Successful Account authentication is required before Game Session creates authenticated session state or accepts gameplay commands. Failures map to canonical `ErrorDetail` and text `ERROR ` responses, including invalid credentials, locked accounts, upstream unavailability, and unauthenticated gameplay. @@ -138,7 +157,7 @@ The lifecycle classes are deliberately distinct: - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. - Current deliberate `LOGOUT` returns `LOGOUT_UNAVAILABLE` without terminal mutations; logout before login is a bounded in-band failure. The target lifecycle and teardown contract is owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript). -Current Game Session suppresses private retained-context reads on reconnect and after attempted `LOGOUT`, and renders fresh `LOOK` after accepted `PLAY`; unexpected transport loss remains reconnect-eligible for fresh authority checks. `LOGOUT_UNAVAILABLE` does not clear an active binding because durable terminal `resumeContextGeneration` evidence is absent. Strict-fence enforcement and live recovery proof remain incomplete. The canonical logout and resume-context contracts are owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript), [Reconnection](../../architecture/system-architecture-reconnection.md#canonical-durable-resume-context-policy), [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md), and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Partial gameplay shells are not authoritative: current private replay suppression does not read retained output from them. +Current Game Session suppresses private retained-context reads on reconnect and after a `LOGOUT` attempt, and renders fresh `LOOK` after accepted `PLAY`; unexpected transport loss remains reconnect-eligible for fresh authority checks. `LOGOUT_UNAVAILABLE` does not complete logout or clear an active binding because durable terminal `resumeContextGeneration` evidence is absent. Strict-fence enforcement and live recovery proof remain incomplete. The canonical logout and resume-context contracts are owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript), [Reconnection](../../architecture/system-architecture-reconnection.md#canonical-durable-resume-context-policy), [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md), and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Partial gameplay shells are not authoritative: current private replay suppression does not read retained output from them. ### Reconnect and Continuity @@ -156,7 +175,7 @@ Shared coordination state now carries reconnect/connect-context tracking, discon The auth/session/routing guardrail family is complete at its current bounded seams and is now a standing regression boundary, not a claim that every future ingress path has been audited. Shared helpers and direct adopters cover: -- `JwtClaims`, `SessionClaims`, current-account access, current global-role-based gameplay classification drift, and downstream gRPC bearer creation. The current Common Security seam still uses legacy session attestation and service-identity handling; the target replaces that with certificate-derived mTLS workload identity plus allowlists and typed `PlayerExecutionContext` for player scope; +- `JwtClaims`, `SessionClaims`, current-account access, tenant-scoped gameplay presence classification, and downstream gRPC bearer creation. The current Common Security seam still uses legacy session attestation and service-identity handling; the target replaces that with certificate-derived mTLS workload identity plus allowlists and typed `PlayerExecutionContext` for player scope; - bootstrap/connect-scope/runtime membership/grant/entitlement claim readers, account-subject coherence, replay readers/writers, and account REST/gRPC request readers in Account Service; - `GameplayAdmissionPointerSnapshots`, `ControlPlaneRequestParser`, `SessionIdParsing`, positive-ID readers, gameplay-character parsing, partial-shell classification, IP counter parsing, and command/control-plane routing normalization in Game Session; - signed first-party handshake/connect-context checks and `TrustedTcpProxyIdentity` at Gateway, plus `TelnetRoutingBundle` and hidden bootstrap envelope handling at TCP Proxy; @@ -164,7 +183,7 @@ The auth/session/routing guardrail family is complete at its current bounded sea The current numeric-reader guardrail is: numeric identifiers still used by an implemented seam must be present, well-formed, and positive; opaque room ids remain textual. This is not the durable cross-boundary target. [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) makes durable cross-boundary account, tenant, game-instance, character, and version identities scoped UUIDs, so replacing current numeric forms and proving scope-qualified comparison remains tracked migration work. Malformed or contradictory JWT/signed-token claims reject before identity comparison; partial routing bundles are absent or rejected, never completed by fallback; malformed persisted replay state is ignored/rejected or terminalizes only its affected durable work item; and request validation occurs before replay lookup when malformed shape could otherwise be masked by a stored effect. Malformed persisted Automation tenant identity terminalizes only that work item rather than aborting the batch. Unexpected parser/runtime bugs are not mislabeled as auth failures. -This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and invalid session JWTs used only for presence classification consistently degrade to the ordinary `PLAYER` presence role. The current classifier still maps a valid global `platformAdmin` claim to in-game `ADMIN`, contrary to the target rule that only explicit tenant-scoped gameplay grants may elevate presence or capabilities. Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. +This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and invalid session JWTs used only for presence classification consistently degrade to the ordinary `PLAYER` presence role. The Game Session classifier and shared gameplay-specific claim helpers now ignore global roles and require an explicit tenant-scoped role for in-game elevation; this focused correction does not make the disabled Account runtime reads live. Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. Replay boundaries validate both read and write sides. Account connect-token and public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. @@ -178,7 +197,7 @@ The focused admission proofs cover fresh acceptance, same-IP replacement reserva Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, current membership, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and contained export/deletion/recovery boundaries. Every current `DeleteAccount` entry denies before account or financial-row mutation; provider/transfer clearance and retained-data workflow remain successor requirements. Explicit JOIN and its bounded worker are local: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency, direct text-client proof, connect-token membership-version/authority-generation baseline reread, and canonical tenant-role/lifecycle/generation follow-through remain partial or unproved. -- **Validation record:** Required current documentation, contract, settings-generation, allocation, ADR, and `git diff --check` gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Runtime proof is not applicable to this documentation-only change. +- **Validation record:** The earlier documentation-only gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Current Unit 1B work changes Account/Game Session runtime behavior and tests, so its focused validation and runtime-proof limits are recorded with the owning PRs; Docker-backed and live paths must not be inferred from earlier documentation checks. ## Active Gaps @@ -191,8 +210,9 @@ Account authority proof covers account-first tenantless bootstrap authentication - Private first-party replay is currently suppressed even if retained transcript rows remain. A safe eligible replay path and terminal `resumeContextGeneration` fence are not implemented; `LOGOUT_UNAVAILABLE` must not be mistaken for a completed logout. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. -- Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. -- Every current Account deletion entry fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation; deletion does not currently remove payment or subscription rows, and no active `hasRetainedOperation` check governs the path. The full ADR 0043 pending-deletion and `DATA-01` retention workflow, provider/transfer clearance, and approved finite schedules remain named pre-v1 requirements. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are also unimplemented; safe disposition of retained terminal receipts and unknown outcomes depends on #2848 and the Account retention workflow under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md). The canonical data-rights design retains billing/audit records for settlement and compliance. No universal retention duration is selected. +- Gameplay presence remains `PLAYER` until fresh Account-authenticated evidence proves an explicit tenant-scoped gameplay grant: JWT role claims do not elevate it, and existing cached elevated Redis roles are projected as `PLAYER` on reads and rewritten as `PLAYER` on activity/AFK updates. The positive/current Account grant carrier and its proof remain unimplemented; staff impersonation and hidden-observer mode are not part of the target. +- New Game Session Redis session-context aliases and movement-effect replay writes strip the raw Account delegation JWT, and their readers do not return legacy raw values. Existing untouched Redis values still require a fenced inventory/cleanup and readback before this new-write containment may be deployed as a complete at-rest correction. The ADR 0031 Account-issued opaque rebind handle, non-secret token metadata, refresh/revocation, and tenant-scoped presence evidence remain ordered pre-v1 work; a token hash alone is not restart authority. +- Every current Account deletion entry fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation. The full ADR 0043 pending-deletion and `DATA-01` retention workflow, provider/transfer clearance, and approved finite schedules remain the named pre-v1 successor required before deletion is enabled. Deletion does not currently remove payment or subscription rows, and no active `hasRetainedOperation` check governs the path. Bounded JOIN receipt cleanup/minimization and deletion reconciliation remain unimplemented; safe disposition of retained terminal receipts and unknown outcomes depends on #2848 and the Account retention workflow under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md). The canonical data-rights design retains billing/audit records for settlement and compliance; no universal retention duration is selected. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. - Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. - The continuity boundary intentionally excludes generalized chaos testing, arbitrary command replay, transport-byte replay, and reconstruction of queue/tick ownership if Game Logic later owns durable execution. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 642a7f6e1e..93836bed73 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -6,13 +6,12 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable post-logout termination/generation fencing, and broader client consumption are not yet proven. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`, but focused recovery proof for this suppression boundary remains incomplete. +This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable post-logout termination/generation fencing, and broader client consumption are not yet proven. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`, but that local boundary does not prove successful logout, durable episode fencing, or recovery behavior. Focused WebSocket proof shows fresh first-party `PLAY` does not read retained screen-buffer rows solely from connect-token context; concurrent and delayed replay still require durable episode-fence proof. Packet 5 moderation/communication/social provenance is represented by [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md), [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md); Packet 6 P0 shared consequences are represented by [ADR 0151](../../architecture/decisions/adr-0151-event-scoped-automated-tier-a-credential-compliance.md), [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md), [ADR 0153](../../architecture/decisions/adr-0153-measured-online-backup-rpo-and-future-pitr-trigger.md), [ADR 0154](../../architecture/decisions/adr-0154-automated-recovery-proof-and-differentiated-traffic-open-gates.md), [ADR 0155](../../architecture/decisions/adr-0155-automated-event-classified-post-restore-trust-reset.md), [ADR 0156](../../architecture/decisions/adr-0156-risk-tiered-progressive-rollout-with-compatibility-bounded-rollback.md), [ADR 0157](../../architecture/decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md), [ADR 0158](../../architecture/decisions/adr-0158-simplified-observability-degradation-without-fallback-alert-authority.md), and [ADR 0159](../../architecture/decisions/adr-0159-profile-dependent-independent-deadman-and-public-path-monitoring.md) where player-facing delivery, history, or privacy boundaries are affected. These links do not upgrade any implementation or verification state. ## Current Gaps -- Gameplay presence role classification still maps global `platformAdmin` and legacy global `god` into in-game `ADMIN` and `GOD`; reconcile this against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md). - Profile-policy surfaces still accept `HIDDEN_STAFF` and fail closed to `PRIVATE` during projection; reconcile the vocabulary against [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). - Player-facing presence responses still expose disconnect disposition; reconcile the response shape against [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). @@ -21,11 +20,11 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. | `proven` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. | -| EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | -| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; durable logout termination and strict generation fencing remain incomplete. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and Game Session suppresses private retained-context reads on reconnect and after attempted `LOGOUT`. Durable `resumeContextGeneration` termination/fencing and focused recovery proof remain incomplete. Full transcript archive/export and raw transport-byte replay remain outside this capability. | +| EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler now requires both effective prompt settings, with focused four-combination local proof; real structured-client consumption and complete reconnect proof remain open. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | +| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; durable logout termination and strict generation fencing remain incomplete. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Fresh first-party `PLAY` does not read retained screen-buffer rows solely from connect-token context; this bounded suppression is independent of successful `LOGOUT`, which remains unavailable until durable episode fencing exists. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; local read suppression does not prove durable `resumeContextGeneration` termination/fencing or live recovery. Concurrent/delayed replay proof remains absent. Full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. | -| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, but current gameplay-role classification translates global `platformAdmin` and legacy global `god` inputs into gameplay roles contrary to ADR 0026, while payload/policy surfaces retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Remove global-role inputs from presence/capability resolution, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | +| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, and the gameplay-role classifier no longer treats global `platformAdmin` or legacy global `god` inputs as gameplay grants, while payload/policy surfaces still retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Complete caller-bound role proof, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | | EA-2.4 Player blocking, reporting, and safety controls | `partial` - bounded internal report persistence and the live synchronous moderation-policy evaluation seam used at enforcement boundaries exist, but owner-local fixed-category restriction state, moderation cases, appeals, and caller-bound player submission remain incomplete; unsafe public administrative report persistence is disabled. | `drift-found` - focused tests prove the bounded internal gRPC persistence and live policy-evaluation seam, plus fail-closed absence of the former public route, not the canonical player-authenticated reporting boundary or target owner-local controls. | [Moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [Authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [ReportGrpcService.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java); [ReportServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImpl.java); [ModerationServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java); [report proto](../../../protos/logging-admin/v1/report_service.proto); [Logging & Admin V1__baseline.sql](../../../services/logging-admin-service/src/main/resources/db/migration/V1__baseline.sql) | [LoggingAdminApplicationIntegrationTest.java](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java); [ReportGrpcServiceTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java); [ModerationServiceImplTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java) | [PO-1.2](./platform-operations-and-delivery.md); [EA-2.1](./player-experience-commands-and-communication.md); [AA-1.3](./player-access-and-session.md) | The live `BLOCK` command is a combat action-state effect, not social blocking. Player block/mute/ignore and safety UI remain absent; reporting needs canonical administrative authorization/live reference checks before public operator ingress and a distinct player route deriving reporter and tenant identity from authenticated caller context. | | EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, but this is not the independently released static player application boundary. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. No independently released static host/public-site routing or browser proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json) | No focused executable proof: `npm run lint` and `npm run build` from the [web-client package](../../../web-client/package.json) passed as general frontend validation and emitted the `dist/frontend-assets/` bundle, but no focused browser or independently released host proof exists. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, unprivileged static host and deployment, reserved-path routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | | EA-3.4 Shared navigation, accessibility, client state, and interaction foundations | `partial` - shared QueryClient, local feature state, and basic socket lifecycle are present. | `audited` - production scaffolding was inspected; no focused navigation, accessibility, or client-state executable proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [main.tsx](../../../web-client/src/main.tsx); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [websocket.ts](../../../web-client/src/websocket.ts); [App.tsx](../../../web-client/src/App.tsx) | No focused executable proof: the [web-client package](../../../web-client/package.json) exposes general lint, build, formatting, preview, and accessibility scripts, but no focused navigation, accessibility, or client-state test exists. | [EA-1.2](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Shared navigation, accessibility coverage, semantic structured gameplay client integration, reconnect/error state, and durable interaction foundations remain absent. | @@ -49,9 +48,9 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text behavior exposes `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path. `PlayCommandHandler` has focused unit response-classification coverage for supplied membership and entitlement/policy responses. In live composition, Account runtime membership, entitlement, and grant readers fail closed before data access; Game Session maps the membership failure to `WORLD_ACCESS_DENIED`, so successful composed public `PLAY` and live `JOIN_REQUIRED` are not established. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path; realm and character discovery helpers are not currently required ceremony. `PlayCommandHandler` has focused response-classification coverage for supplied membership and entitlement/policy responses. Account's trusted-peer runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access, so live valid-route text `PLAY` maps the membership failure to retryable `AUTH_UNAVAILABLE` before conditional membership/grant classification or Entity-roster evaluation. With supplied Account responses, `PlayCommandHandler` recognizes missing or `INACTIVE` public-production membership and checks fresh entitlement and `allowPublicJoin`: denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, while permitted policy returns `JOIN_REQUIRED`. These conditional branches are not reachable in live composition and do not establish successful composed public `PLAY` or live `JOIN_REQUIRED`. Other non-admitting membership states are denied without JOIN advice. Account connect-token issuance is a separate Account-owned path with separate current checks and outcomes; its current public `allowPublicJoin` check does not establish text `PLAY`, and the target membership-authority-generation reread remains incomplete. An unambiguous eligible supplied-authority `PLAY` branch enters with the required authority; ambiguous/inaccessible selections return bounded selection errors, and wrong-stage input gives guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical admission policy and outcomes remain owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispatch now exist locally; the browser bootstrap facade is present, but its public Gateway route remains denied and target-only. Account's transactional audit outbox and producer-side typed receipt validation/verified-projection marker are implemented locally; Logging & Admin receiver persistence/readback remains unavailable and unproved under #2940. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, direct text-to-Logging end-to-end coverage, complete event/authority-tuple propagation, and reconnect freshness. The bounded Account worker reads back abandoned JOIN `PENDING` intents, but this does not prove runtime/recovery outcomes. Connect-token membership-authority-generation reread remains incomplete; focused Account unit coverage exercises missing-membership and policy-denial mappings. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The explicit Account JOIN RPC/controller, browser bootstrap facade, and direct-text REALMS-scope/JOIN dispatch exist locally, but the public Gateway bootstrap JOIN route remains denied and target-only. Account's transactional audit outbox, producer-side typed receipt validation and verified-projection marker, and bounded readback worker for abandoned JOIN `PENDING` intents are implemented locally; #2940 supplies local Logging & Admin receiver persistence and live receipt readback, while write ingress remains unavailable and Account delivery is unscheduled. Offline receiver fixtures do not prove live delivery. The worker does not prove runtime or recovery outcomes. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, lost-acknowledgement/concurrency, direct text-to-Logging end-to-end coverage, complete event/authority-tuple propagation, reconnect freshness, first-party `Join & Play`, full lifecycle/generation propagation, and the connect-token membership-authority-generation reread. Focused Account tests do not establish these runtime outcomes; they cover local missing-membership and policy-denial classifications. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation @@ -61,8 +60,8 @@ The explicit Account JOIN RPC/controller and direct-text REALMS-scope/JOIN dispa ### Transcript, History, and Room Views -- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; durable episode termination is not implemented. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). -- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. Local read suppression does not prove durable `resumeContextGeneration` termination/fencing or live recovery behavior, and full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. +- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects and does not clear presence, stored context, or reconnect eligibility; private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`, but durable episode termination is not implemented. A fresh first-party `PLAY` does not read retained screen-buffer rows solely from connect-token context. Durable retained rows are distinct from reconnect eligibility. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). +- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. A focused fresh first-party WebSocket test proves a new connect-token context does not read retained screen-buffer rows; it does not exercise successful command logout. Local suppression does not prove durable `resumeContextGeneration` termination/fencing or live recovery. Durable terminal episode fencing, concurrent/delayed replay proof, full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. - Current behavior: Game Logic composes ordinary floor-free `LookResult` data from World Management and Entity Management; Game Session enforces access and renders the result. Current request/proto evidence carries no causal-floor evidence, so target propagation and participant proof remain gaps linked to [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md). `LOOK`, `QUICKLOOK`, movement refresh, localization, brief/color handling, and bounded error mapping are covered. The current renderer also writes disposable legacy cache values; reads remain authoritative/uncached, and this incomplete scope plus ten-minute TTL does not prove the target causal-floor/freshness contract. Combat-sensitive brief-on-move and broader world-content localization remain incomplete. ### Communication, Social, and Presence diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index ebd5c70052..0f9531df65 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The realm catalog, admission-pointer reads, bootstrap/connect-scope flow, runtime projections, and bounded direct-text [REALMS-to-JOIN handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) have local implementation. Game Session retains caller-bound Account scopes and JOIN request IDs in shared Redis, binds `WORLDS` ordinals to their catalog snapshot, and uses the shared `DirectTextOrdinalSelectionResolver`; current numeric selectors fail closed when their snapshot is stale or changed. The pointer projection lacks `tenantSlug`, so the stable target `tenantSlug/worldSlug` selector is unavailable; current unique bare-world-slug resolution is implementation drift from the target prohibition on global bare `worldSlug` resolution. Focused unit proof exists; the Docker-gated Redis cross-instance/retry proof was skipped locally, and full direct-text/Telnet and first-party `Join & Play` proof remains open. Account runtime membership, entitlement, and grant handlers deny before data reads until the typed caller/target binding exists, so there is no composed live admission proof. Routing remains partial: explicit `CLOSED`, consumer-wide revision convergence, canonical `{tenantId, realmId}` addressing, atomic prepared-cutover execution, and bounded active-session drain remain gaps. Public/grant policy lacks expiry, monotonic mutation outcomes/tombstones, and tenant-admin management; playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration remain unimplemented or unproved. See [Authentication](../../architecture/system-architecture-authentication.md) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) for canonical contracts. +The realm-catalog projection, exact `WORLDS`/`REALMS` ordinal snapshots, persisted-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, and local runtime projections are implemented; this does not establish complete routing or live admission. `WORLDS` and its ordinal snapshot share one catalog read. Game Session retains caller-bound Account scopes and JOIN request IDs in bounded shared Redis state keyed by the stable numeric transport session; it binds world and realm ordinals to their exact response snapshots through the shared `DirectTextOrdinalSelectionResolver`, and stale or changed numeric selectors fail closed. Current text `JOIN` accepts the retained `WORLDS` ordinal or a uniquely resolving bare world slug; the latter is implementation drift. The pointer has no `tenantSlug`, so stable `tenantSlug/worldSlug` selection remains unavailable. Authority-backed discovery suppresses cross-tenant case-insensitive slug collisions without collapsing tenant-bound ordinal choices. Scope and selector snapshots expire; per-key compare-and-set protects retry binding and replacement. The source-YAML initializer proof reads shipped application YAML directly and proves source-configuration binding only; it is not packaged-artifact, fresh-boot, persisted-seed, or live-admission proof. Focused unit proof exists; Docker-gated Redis cross-instance/retry proof was skipped locally. Full direct-text/Telnet and first-party `Join & Play` end-to-end proof, PostgreSQL lost-acknowledgement/concurrency proof, and complete pending-operation recovery remain open. + +Account membership, entitlement, and grant readers fail closed before data access until typed caller/target binding is available, so there is no composed live admission proof; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. `GetAdmissionPointer` preserves exactly-one-visible-public-production-realm cardinality from one authoritative snapshot; catalog-revision and pointer-read failures retain typed retryable unavailable outcomes instead of becoming missing selectors or generic failures. Duplicate public rows remain an activation/data-decision gap. The internal pointer authority locks an existing row, checks expected `pointerVersion` and `catalogRevision`, conditionally updates against both prior values, and commits pointer plus audit together. Public pointer mutation and cutover RPCs remain fail-closed; prepared-cutover execution, explicit `CLOSED`, complete revision-consumer convergence, canonical `{tenantId, realmId}` repository addressing and retained catalog mapping, hold/drain atomicity, and bounded active-session drain remain incomplete. Public/grant policy is also partial: lifecycle-bound grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent; playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration remain unimplemented or unproved. See [Authentication](../../architecture/system-architecture-authentication.md) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) for canonical contracts. ## Packet 4 Status and Proof Gaps @@ -21,7 +23,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority now uses a row-locked expected `{pointerVersion, catalogRevision}` check, a conditional existing-row update, separate route/catalog revisions, and one pointer-plus-audit transaction. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Public pointer mutation/cutover RPCs remain fail-closed, so the full target cutover operation is not live. Explicit `CLOSED`, repository addressing by the canonical `{tenantId, realmId}` key and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java); [V12 migration-shape test](../../../services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java); [V12 cardinality PostgreSQL integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. The V12 migration-shape test runs locally; its PostgreSQL cardinality integration remains Docker-gated and unrun locally, and existing duplicate visible-public rows remain an activation/data-disposition blocker. Migration ordering and retained-history, inventory, and lock/quiescence requirements are owned by [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md). Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -37,7 +39,7 @@ These links add decision provenance only; they do not upgrade routing or playabl Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. `pointerVersion` tracks runtime-target changes while `catalogRevision` tracks catalog/policy changes; see the [Versioning & Runtime Configuration owner status](../../architecture/system-architecture-versioning-runtime.md#implementation-status) for the current persistence boundary and remaining cutover gaps. Complete all-consumer convergence and exact retained-audit proof remain open; unknown historical identity/revision is not backfilled. -Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. The current persistence primitive checks the expected `{pointerVersion, catalogRevision}` under a row lock, conditionally updates an existing row against both prior values, and commits the pointer with its audit event in one transaction. This is owner-local persistence proof, not public mutation or full prepared-cutover support; see the [Versioning & Runtime Configuration owner status](../../architecture/system-architecture-versioning-runtime.md#implementation-status). V2 enforces tenant-local selector uniqueness, but persistence has not converged on canonical `{tenantId, realmId}` addressing or retained catalog-to-realm mapping. +Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; target `GetAdmissionPointer(tenantId, realmId)` reads direct authority rather than reconstructing it through a browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support are not live. Target Account bootstrap admission, public-production membership creation, prepared-cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the IDs are not interchangeable. Current pointer persistence locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer and audit in one transaction. This owner-local persistence boundary does not provide public mutation or full prepared-cutover support; PostgreSQL concurrency/lost-acknowledgement proof remains open when Docker-gated runs skip. V2 enforces tenant-local selector uniqueness, but canonical `{tenantId, realmId}` repository addressing and retained catalog-to-realm mapping remain incomplete. Configured bootstrap pointer seeds are validated but not published automatically: startup creates no authority rows without World-owned lifecycle proof, and an empty store remains closed. `GameplayCatalogProperties` is not production routing authority: Game Session's production catalog projection is pointer-backed, Account Service no longer ships the old local catalog config, and property-to-catalog construction remains only in explicit test support. See the canonical [World Lifecycle and Admission Boundary](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and the [Game Session runtime tracker](./game-session-runtime-and-tick-coordination.md) for current implementation and proof status. @@ -47,7 +49,7 @@ Game Session exposes canonical world, realm, and pointer reads plus pointer list The shared `GameplayAdmissionPointerSnapshots` rule defines a complete pointer as one with positive `tenantId`, positive `gameInstanceId`, positive `pointerVersion`, nonblank `worldSlug`, `realmSlug`, and `stateScope`. Singular runtime-target authority exists only when the raw current-pointer result contains exactly one row and that row is complete. Any additional row, incomplete row, missing runtime identity, or missing scope makes the singular projection unavailable; incomplete rows are not discarded before multiplicity is assessed. Raw pointer lists still expose such rows for operator inspection. -`GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. It groups rows by `{tenantId, worldSlug, realmSlug}` and emits a visible catalog entry only for exactly one complete row in that tenant-qualified selector scope. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target; duplicate selector rows within a tenant, duplicate runtime matches, and incomplete rows disappear from player-facing catalog projection rather than selecting an arbitrary row. +`GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. V2 enforces tenant-qualified pointer uniqueness. The current player-facing catalog suppresses complete pointers with a cross-tenant case-insensitive world-slug collision before grouping and refuses ambiguous bare-slug resolution, so it cannot merge two tenants into one displayed world; text browse currently exposes public-production realms only, pending typed Account grant evidence for private discovery; WORLDS and its ordinal targets share one catalog read; numeric selection binds to that response-local snapshot, catalog revision, and target/catalog fingerprints, rejecting stale or reordered values instead of reindexing them. Focused local unit proof covers this bounded snapshot behavior. The full live direct-text/Telnet path remains unproved; the stable tenant-qualified selector remains unavailable until the pointer carries `tenantSlug`. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target. Incomplete pointer rows are excluded from the player-facing projection; stable tenant-qualified discovery is a distinct remaining capability gap. Admission-pointer `stateScope` is the canonical realm policy. Downstream `playableStateScope` is its resolved cross-service representation: `SHARED` maps to `PLAYABLE_STATE_SCOPE_SHARED` and `ISOLATED` maps to `PLAYABLE_STATE_SCOPE_ISOLATED`; it is not a second admission authority. If no single complete pointer can be proved, the singular downstream scope and routing bundle fail closed to unspecified/absent rather than reverse-inferring authority from `gameInstanceId`. @@ -55,9 +57,9 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account's explicit public-production membership writer and Game Session direct-text JOIN invocation are implemented locally; first-party browser JOIN remains blocked at Gateway. Game Session validates lifecycle, membership version, authority generation, caller/target identity, and freshness on supplied-authority PLAY branches, and recommends public JOIN_REQUIRED only for missing or INACTIVE membership after fresh entitlement and allowPublicJoin checks. An ACTIVE but non-admitting membership is denied. The proto's uint64 generation and incomplete Account issuance reread/private-grant validation remain implementation gaps; live Account readers fail before data access, so composed admission is unproved. Canonical admission rules belong to [Authentication](../../architecture/system-architecture-authentication.md#implementation-status); Account and Game Session implementation/proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, while other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. Canonical `JOIN_REQUIRED` eligibility and ordering belong to [Authentication](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries); the local supplied-authority classification does not establish live `JOIN_REQUIRED` proof. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity access, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Canonical non-public membership and realm-grant rules and outcome mappings belong to [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence). Current Account readers fail closed before data access, so local supplied-authority `PLAY` grant classification does not establish composed admission; the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). -First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. On fresh `/auth/connect-token` issuance or a replay-cache miss, the current path revalidates pointer/visibility and membership but does not validate the applicable grant; a cached-success replay can return before those fresh reads. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. Fresh `/auth/connect-token` issuance and cached-success replay share current pointer/target, entitlement and membership checks; cached replay also verifies the stored result binding and returns the original token without reminting or rewriting cache/session state. Applicable grant and membership-version/authority-generation baseline validation remain incomplete. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; the current bare-world-slug selection re-resolves current authority only when unique in the catalog. Canonical tenant-scoped stable selector resolution remains a separate gap. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, terminal-outcome recovery, and direct text-to-Logging proof remain unproved. Account's bounded readback-only worker for abandoned JOIN `PENDING` intents is implemented, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and complete pending-operation recovery/reconciliation remain open. This is distinct from the browser/WebSocket bootstrap snapshot. @@ -71,7 +73,7 @@ Current normalization clears a stored gameplay binding when it no longer matches Command staging chooses an admitted gameplay runtime first, then an explicit bootstrap runtime only when the shell retains a complete bootstrap routing bundle; otherwise it fails closed with `NOT_FOUND`. It never treats a numeric `sessionId` as a runtime target. Current runtime-target authority repairs stale command metadata only when one complete pointer proves the target. For an already selected gameplay scope, missing, ambiguous, or incomplete authority persists `playableStateScope=UNSPECIFIED` with no world/realm/version bundle. The current blank-scope login/bootstrap branch is a narrower exception: when runtime authority cannot be resolved, it preserves a normalized shell `{worldSlug, realmSlug, pointerVersion}` trio while persisting `playableStateScope=UNSPECIFIED`. This trio is a non-authoritative lobby selection hint, not an admitted routing bundle: it cannot establish or preserve a runtime route, authorize `PLAY`, or become downstream gameplay metadata. Complete pre-`PLAY` shell metadata is freshness-checked before persistence. Durable command execution and selected-work manifests normalize/collapse admitted routing metadata before replay or tick-batch sealing. -`QueryState(sessionId)` requires a normalized live session shell with positive tenant authority and never guesses a Redis key from a runtime id. Logout stops a runtime only when explicit scope or exactly one complete current isolated pointer positively proves that decision; missing, partial, or multiple pointers mean keep the runtime running. TCP Proxy disconnects suspend runtime state only with explicit `gameInstanceId`; advisory `sessionId` is never promoted, and missing runtime metadata remains best-effort session cleanup plus missing-context metering. Proxy producers and consumers preserve this envelope contract, and partial proxy routing headers are normalized to an unscoped bootstrap rather than forwarded as malformed authority. Authenticated TCP Proxy/Game Session callbacks and Game Session/Game Logic blocking clients use internal-service gRPC identity, with packaged-stack blocking stubs bound to the resolved customizer rather than a provider/no-op fallback. +`QueryState(sessionId)` requires a normalized live session shell with positive tenant authority and never guesses a Redis key from a runtime id. Logout stops a runtime only when explicit scope or exactly one complete current isolated pointer positively proves that decision; missing, partial, or multiple pointers mean keep the runtime running. `NotifyDisconnect` is advisory, read-only handling: Game Session deduplicates proxy event keys, meters duplicate or missing-context events, and validates an explicit `{tenantId, gameInstanceId}` against its `GameInstance`; it does not suspend runtime state or clean up sessions, and advisory `sessionId` is never promoted to runtime authority. Proxy producers and consumers preserve this envelope contract, and partial proxy routing headers are normalized to an unscoped bootstrap rather than forwarded as malformed authority. Authenticated TCP Proxy/Game Session callbacks and Game Session/Game Logic blocking clients use internal-service gRPC identity, with packaged-stack blocking stubs bound to the resolved customizer rather than a provider/no-op fallback. ### Durable Delegation and Control-Plane Projection @@ -101,18 +103,18 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers deny before data reads, and Game Session maps the membership failure to `WORLD_ACCESS_DENIED`. Focused direct text-to-Logging end-to-end proof remains open. +- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before data reads, which text `PLAY` maps to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity access; AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Focused direct text-to-Logging end-to-end proof remains open. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. - Replacement-instance migration/remap mechanics and domain-specific carry-forward rules remain unimplemented, including economy, guild, and combat-specific policy. - The current pointer model cannot represent explicit `CLOSED`. Runtime-target changes advance `pointerVersion`; catalog/policy changes advance separate `catalogRevision`, so display and other catalog-only edits do not advance the runtime route version. Current active bindings are still fenced against current pointer state rather than ended through the target bounded drain. - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. -- The internal authority locks an existing pointer row, requires the expected `pointerVersion` and `catalogRevision` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable control-plane mutation: the public mutation path remains fail-closed, and full prepared-cutover CAS/readback is unimplemented. -- The internal pointer authority commits pointer state and its audit event together. The `ExecutePreparedVersionCutover` RPC currently fails closed before authority/preparation reads or execution marking, so no live cutover writes prepared-execution state in that transaction. The full target atomic retry/reconciliation boundary, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- Current storage uses the tenant-local selector key `(tenant_id, world_slug, realm_slug)` (V2) and separately persists globally unique `realm_id` values (V6). The target composite `{tenantId, realmId}` key/index is not yet the repository lookup or uniqueness key; canonical realm-ID addressing and retained catalog-to-realm mapping remain unimplemented. +- The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. +- The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. V12 migration-shape proof runs locally, while its PostgreSQL cardinality integration remains Docker-gated and unrun locally. Migration ordering and retained-data activation requirements are owned by [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md). - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. -- The current documentation-only slice passed `./gradlew linkCheck lintMarkdown`. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md); runtime proof is not applicable to this documentation-only checkpoint. +- An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; historical hosted proof and its current-head gaps are recorded in [Player Access and Session](./player-access-and-session.md#unit-1b-section-exit-dispositions). Retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). ## To Discuss diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { 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 2a688ab098..7c03d909bf 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 @@ -90,9 +90,11 @@ import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.exception.ConfigurationException; +import org.jooq.exception.DataAccessException; import org.jooq.exception.IntegrityConstraintViolationException; +import org.jooq.exception.MappingException; import org.slf4j.Logger; -import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -1079,26 +1081,7 @@ private static JoinAttemptOutcome terminal(JoinOperation operation) { } private RuntimeEntitlementsDto joinEntitlement(long tenantId, boolean lockSubscription) { - List rows = - lockSubscription - ? subscriptionRepository.findByTenantIdForUpdate(tenantId) - : subscriptionRepository.findByTenantId(tenantId); - if (rows.size() != 1) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); - } - var subscription = rows.getFirst(); - if (subscription.getEntitlementVersion() <= 0L) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); - } - return new RuntimeEntitlementsDto( - tenantId, - isGameplayAvailableStatus(subscription.getStatus()), - isPublicJoinAllowedStatus(subscription.getStatus()), - subscription.getEntitlementVersion(), - subscription.getEntitlementVersion(), - Instant.now().toString()); + return readTenantEntitlements(tenantId, lockSubscription); } @Override @@ -1119,6 +1102,9 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR if (cachedReplay.isPresent()) { var replay = cachedReplay.orElseThrow(); if (replay.success()) { + ConnectTokenResult cachedResult = replay.result(); + requireConnectTokenReplayBinding(cachedResult, bootstrapContext, scopeContext, request); + authorizeConnectTokenIssuance(bootstrapContext, scopeContext, request.requestId()); logger.info( "Replayed connect-token attempt for account {} tenant {} world {} realm {} requestId {}", bootstrapContext.accountId(), @@ -1126,7 +1112,7 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR scopeContext.worldSlug(), scopeContext.realmSlug(), request.requestId()); - return replayedConnectTokenResult(replay.result()); + return replayedConnectTokenResult(cachedResult); } logger.info( "Replayed failed connect-token attempt for account {} tenant {} world {} realm {} requestId {} code {}", @@ -1160,54 +1146,8 @@ private ConnectTokenResult issueConnectTokenFresh( BootstrapContext bootstrapContext, ConnectScopeContext scopeContext, ConnectTokenRequest request) { - RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - RuntimeMembershipDto membership = - getTenantMembershipForRuntime( - bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); - - if (membership.membershipExists() - && !"ACTIVE".equals(membership.membershipLifecycleState()) - && !"INACTIVE".equals(membership.membershipLifecycleState())) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); - } - if (membership.membershipExists() - && "INACTIVE".equals(membership.membershipLifecycleState()) - && isPublicProductionRealm(realm)) { - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - - if (!membership.membershipExists()) { - if (!isPublicProductionRealm(realm)) { - throw new AuthenticationException( - "NON_PUBLIC_ENROLLMENT_REQUIRED", - "Existing game membership is required for this non-public realm"); - } - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - + RuntimeRealmTarget realm = + authorizeConnectTokenIssuance(bootstrapContext, scopeContext, request.requestId()); String jti = stableId( "gameplay-connect", @@ -1283,6 +1223,88 @@ && isPublicProductionRealm(realm)) { return result; } + private RuntimeRealmTarget authorizeConnectTokenIssuance( + BootstrapContext bootstrapContext, ConnectScopeContext scopeContext, String requestId) { + RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(scopeContext.tenantId(), requestId); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + RuntimeMembershipDto membership; + try { + membership = + getTenantMembershipForRuntime( + bootstrapContext.accountId(), scopeContext.tenantId(), requestId); + } catch (MappingException | ConfigurationException ex) { + throw ex; + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Membership authority is unavailable; retry later", ex); + } + + if (membership.membershipExists() + && !"ACTIVE".equals(membership.membershipLifecycleState()) + && !"INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); + } + if (membership.membershipExists() + && "INACTIVE".equals(membership.membershipLifecycleState()) + && isPublicProductionRealm(realm)) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + + if (!membership.membershipExists()) { + if (!isPublicProductionRealm(realm)) { + throw new AuthenticationException( + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "Existing game membership is required for this non-public realm"); + } + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + return realm; + } + + private void requireConnectTokenReplayBinding( + ConnectTokenResult result, + BootstrapContext bootstrapContext, + ConnectScopeContext scopeContext, + ConnectTokenRequest request) { + if (result == null + || result.accountId() != bootstrapContext.accountId() + || result.tenantId() != scopeContext.tenantId() + || result.gameInstanceId() != scopeContext.gameInstanceId() + || !java.util.Objects.equals(result.realmSlug(), scopeContext.realmSlug()) + || !java.util.Objects.equals(result.connectScopeId(), request.connectScopeId()) + || !java.util.Objects.equals(result.requestId(), request.requestId()) + || !StringUtils.hasText(result.connectToken()) + || !StringUtils.hasText(result.jti()) + || !StringUtils.hasText(result.issuedAt()) + || !StringUtils.hasText(result.expiresAt())) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", + "Cached connect-token result does not match the current request scope"); + } + } + @Override @Transactional(readOnly = true) @Timed(value = "account.runtime_membership") @@ -1376,16 +1398,25 @@ public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, S @Transactional(readOnly = true) @Timed(value = "account.runtime_entitlements") public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId) { + return readTenantEntitlements(tenantId, false); + } + + private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean lockSubscription) { List subscriptions; try { - subscriptions = subscriptionRepository.findByTenantId(tenantId); - } catch (DataAccessException ex) { + subscriptions = + lockSubscription + ? subscriptionRepository.findByTenantIdForUpdate(tenantId) + : subscriptionRepository.findByTenantId(tenantId); + } catch (MappingException | ConfigurationException ex) { + throw ex; + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is unavailable; retry later", ex); } - if (subscriptions.size() != 1) { + if (subscriptions == null || subscriptions.size() != 1 || subscriptions.getFirst() == null) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later"); @@ -1395,6 +1426,10 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str boolean gameplayAvailable = isGameplayAvailableStatus(subscription.getStatus()); boolean allowPublicJoin = isPublicJoinAllowedStatus(subscription.getStatus()); long version = subscription.getEntitlementVersion(); + if (version <= 0L) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement version is invalid; retry later"); + } return new RuntimeEntitlementsDto( tenantId, gameplayAvailable, allowPublicJoin, version, version, Instant.now().toString()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 5955eff9dc..dfaed6b04a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -229,10 +229,11 @@ void failedJoinReplaysStoredOutcomeAndRejectsChangedPolicyDigest() { dsl.execute( "UPDATE subscription SET status = 'active', entitlement_version = 2 WHERE tenant_id = ?", fixture.tenantId()); - AuthenticationException conflict = - assertThrows(AuthenticationException.class, () -> join(fixture)); + JoinPublicProductionResult conflict = join(fixture); - assertThat(conflict.getCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(conflict.success()).isFalse(); + assertThat(conflict.outcomeCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(conflict.replayed()).isFalse(); assertThat( dsl.resultQuery( "SELECT request_digest FROM account_join_operations WHERE request_id = ?", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index 167cc948af..474888f792 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -458,7 +458,7 @@ private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int a assertThat(updated).isEqualTo(1); int auditUpdated = dsl.execute( - "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', next_attempt_at = NULL, receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", joinAuditEventId(fixture.requestId()), fixture.tenantId()); assertThat(auditUpdated).isEqualTo(1); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index eae5444b36..596e170c21 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -1459,11 +1459,28 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { .isEqualTo(explicitMembershipBefore); assertThat( jsonRow( - "SELECT to_jsonb(j)::text FROM " + "SELECT (to_jsonb(j) - 'reconciliation_attempt_count' " + + "- 'last_reconciliation_attempt_at' " + + "- 'last_reconciliation_attempt_reason' " + + "- 'next_reconciliation_attempt_at')::text FROM " + schema + ".account_join_operations j WHERE request_id = ?", pendingJoinRequestId)) .isEqualTo(pendingJoinBefore); + assertThat( + dsl.fetchOne( + "SELECT reconciliation_attempt_count, last_reconciliation_attempt_at, " + + "last_reconciliation_attempt_reason, next_reconciliation_attempt_at FROM " + + schema + + ".account_join_operations WHERE request_id = ?", + pendingJoinRequestId)) + .satisfies( + row -> { + assertThat(row.get("reconciliation_attempt_count", Integer.class)).isZero(); + assertThat(row.get("last_reconciliation_attempt_at")).isNull(); + assertThat(row.get("last_reconciliation_attempt_reason", String.class)).isNull(); + assertThat(row.get("next_reconciliation_attempt_at")).isNotNull(); + }); assertThat( jsonRow( "SELECT to_jsonb(s)::text FROM " 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 46bbe07e1d..b38935c7c2 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 @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; @@ -73,6 +74,8 @@ import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.exception.ConfigurationException; +import org.jooq.exception.MappingException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -638,8 +641,8 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers } @ParameterizedTest - @CsvSource({"false", "true"}) - void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { + @ValueSource(strings = {"missing", "ambiguous", "null-list", "null-row"}) + void missingOrInvalidEntitlementRetainsUnavailableJoinReceipt(String rowsKind) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -672,12 +675,15 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou retainJoinEvidence(retainedScope, retainedOperation); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + java.util.List unavailableRows = + switch (rowsKind) { + case "ambiguous" -> java.util.List.of(new Subscription(), new Subscription()); + case "null-list" -> null; + case "null-row" -> java.util.Arrays.asList((Subscription) null); + default -> java.util.List.of(); + }; when(subscriptionRepository.findByTenantId(7L)) - .thenReturn( - ambiguous - ? java.util.List.of(new Subscription(), new Subscription()) - : java.util.List.of(), - java.util.List.of(recovered)); + .thenReturn(unavailableRows, java.util.List.of(recovered)); when(subscriptionRepository.findByTenantIdForUpdate(7L)) .thenReturn(java.util.List.of(recovered)); JoinPublicProductionRequest request = @@ -720,6 +726,73 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou .findByTenantIdForUpdate(7L); } + @ParameterizedTest + @ValueSource( + strings = {"jooq-data-access", "spring-data-access", "jooq-mapping", "jooq-configuration"}) + void joinClassifiesLockedEntitlementReadFailuresWithoutCommittingMembership(String failureType) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + active.setEntitlementVersion(1L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + RuntimeException cause = + switch (failureType) { + case "jooq-data-access" -> + new org.jooq.exception.DataAccessException("subscription store unavailable"); + case "spring-data-access" -> + new DataAccessResourceFailureException("subscription store unavailable"); + default -> unexpectedEntitlementFailure(failureType); + }; + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenThrow(cause); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-locked-entitlement-1"); + String expectedCode; + if (failureType.endsWith("data-access")) { + JoinPublicProductionResult result = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(result.success()); + expectedCode = "ENTITLEMENT_UNAVAILABLE"; + assertEquals(expectedCode, result.outcomeCode()); + } else { + AuthenticationException propagated = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + expectedCode = "AUTH_UNAVAILABLE"; + assertEquals(expectedCode, propagated.getCode()); + assertSame(cause, propagated.getCause()); + } + assertEquals("PENDING", retainedOperation.get().status()); + assertNull(retainedOperation.get().outcome()); + assertEquals(expectedCode, retainedOperation.get().lastAttemptFailureCode()); + verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository).findByTenantIdForUpdate(7L); + } + @Test void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { Account account = new Account(); @@ -885,6 +958,60 @@ void scopeExpiringDuringFinalJoinEvaluationLeavesNewOrRetainedIntentPending( org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); } + @Test + void joinPublicProductionKeepsPendingWhenLateDuplicateMakesPublicRealmAmbiguous() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + net.firedevops.firemud.gamesession.v1.GameplayRealm selectedRealm = + gameSessionClient.listGameplayRealms("demo").getFirst(); + net.firedevops.firemud.gamesession.v1.GameplayRealm lateDuplicate = + selectedRealm.toBuilder() + .setRealmSlug(selectedRealm.getRealmSlug()) + .setDisplayName("Duplicate Live Realm") + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .setGameInstanceId("45") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(24L) + .setPointerVersion(1L) + .build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(selectedRealm, lateDuplicate)); + org.mockito.Mockito.clearInvocations(gameSessionClient); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-late-ambiguous-realm-1")); + + assertFalse(result.success()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) + .getAdmissionPointer(7L, "demo", "production"); + } + @Test void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); @@ -1074,7 +1201,7 @@ void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { } @Test - void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { + void joinIntentCommitsSeparatelyWhenEntitlementReadIsUnavailable() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1093,25 +1220,23 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); when(subscriptionRepository.findByTenantId(7L)) - .thenThrow(new IllegalStateException("entitlement storage unavailable")); + .thenThrow(new org.jooq.exception.DataAccessException("entitlement storage unavailable")); - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); + JoinPublicProductionResult unavailable = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertFalse(unavailable.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.outcomeCode()); assertEquals("PENDING", retainedOperation.get().status()); assertEquals(null, retainedOperation.get().outcome()); assertNotNull(retainedOperation.get().intentDigest()); assertEquals(null, retainedOperation.get().requestDigest()); - assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) .commit(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.never()) .rollback(org.mockito.ArgumentMatchers.any()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); @@ -3188,6 +3313,123 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } + @ParameterizedTest + @ValueSource(strings = {"null-list", "null-row"}) + void getTenantEntitlementsForRuntimeTreatsNullSubscriptionReadAsUnavailable(String rowsKind) { + java.util.List rows = + "null-list".equals(rowsKind) ? null : java.util.Arrays.asList((Subscription) null); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(rows); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-null-entitlement")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void issueDirectTextConnectScopeDoesNotMintScopeWithoutUniqueEntitlement(boolean ambiguous) { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus("active"); + Subscription duplicate = new Subscription(); + duplicate.setId(32L); + duplicate.setTenantId(7L); + duplicate.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(ambiguous ? java.util.List.of(active, duplicate) : java.util.List.of()); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void issueDirectTextConnectScopeDoesNotMintScopeWhenEntitlementReadIsUnavailable( + boolean jooqFailure) { + RuntimeException cause = + jooqFailure + ? new org.jooq.exception.DataAccessException("subscription store unavailable") + : new DataAccessResourceFailureException("subscription store unavailable"); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertSame(cause, exception.getCause()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @ParameterizedTest + @ValueSource(strings = {"illegal-state", "jooq-mapping", "jooq-configuration"}) + void issueDirectTextConnectScopePropagatesUnexpectedRuntimeFailureWithoutMintingScope( + String failureType) { + RuntimeException cause = unexpectedEntitlementFailure(failureType); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + RuntimeException propagated = + assertThrows(RuntimeException.class, this::issueDirectTextConnectScopeForTest); + + assertSame(cause, propagated); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeDoesNotMintScopeWhenGameplayIsUnavailable() { + Subscription canceled = new Subscription(); + canceled.setId(31L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeRejectsNonPositiveEntitlementVersion() { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus("active"); + active.setEntitlementVersion(0L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeAllowsDiscoveryWhenPublicJoiningIsDisabled() { + Subscription grace = new Subscription(); + grace.setId(31L); + grace.setTenantId(7L); + grace.setStatus("grace"); + grace.setEntitlementVersion(4L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); + + DirectTextJoinScope scope = issueDirectTextConnectScopeForTest(); + + assertNotNull(scope.connectScopeId()); + assertFalse(scope.connectScopeId().isBlank()); + verify(subscriptionRepository).findByTenantId(7L); + verify(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + @Test void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingScope() { Account account = directTextAccount(); @@ -3263,10 +3505,13 @@ void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); } - @Test - void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { - DataAccessResourceFailureException cause = - new DataAccessResourceFailureException("subscription store unavailable"); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void getTenantEntitlementsForRuntimeTreatsDataAccessFailuresAsUnavailable(boolean jooqFailure) { + RuntimeException cause = + jooqFailure + ? new org.jooq.exception.DataAccessException("subscription store unavailable") + : new DataAccessResourceFailureException("subscription store unavailable"); when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); AuthenticationException exception = @@ -3275,7 +3520,23 @@ void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-store-failure")); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - assertEquals(cause, exception.getCause()); + assertSame(cause, exception.getCause()); + } + + @ParameterizedTest + @ValueSource(strings = {"illegal-state", "jooq-mapping", "jooq-configuration"}) + void getTenantEntitlementsForRuntimePropagatesUnexpectedRuntimeFailureByIdentity( + String failureType) { + RuntimeException cause = unexpectedEntitlementFailure(failureType); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + RuntimeException propagated = + assertThrows( + RuntimeException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-runtime-failure")); + + assertSame(cause, propagated); + verifyNoInteractions(accountConnectScopeRepository); } @Test @@ -3549,7 +3810,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { } @Test - void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() { + void issueConnectTokenRevalidatesCachedSuccessAndPreservesItsImmutableResult() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -3575,6 +3836,51 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, firstResult, "", ""))); + org.mockito.Mockito.clearInvocations( + sessionService, + gameSessionClient, + subscriptionRepository, + accountTenantMembershipRepository); + + ConnectTokenResult replayed = + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + + assertEquals(firstResult.accountId(), replayed.accountId()); + assertEquals(firstResult.tenantId(), replayed.tenantId()); + assertEquals(firstResult.gameInstanceId(), replayed.gameInstanceId()); + assertEquals(firstResult.realmSlug(), replayed.realmSlug()); + assertEquals(firstResult.connectScopeId(), replayed.connectScopeId()); + assertEquals(firstResult.connectToken(), replayed.connectToken()); + assertEquals(firstResult.jti(), replayed.jti()); + assertEquals(firstResult.issuedAt(), replayed.issuedAt()); + assertEquals(firstResult.expiresAt(), replayed.expiresAt()); + assertEquals(firstResult.requestId(), replayed.requestId()); + assertTrue(replayed.replayed()); + verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + verify(subscriptionRepository).findByTenantId(7L); + verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); + verifyNoConnectTokenReplayWrites(); + + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(24L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() @@ -3583,10 +3889,10 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setRealmSlug("production") .setRealmDisplayName("Live Realm") .setTenantId("7") - .setGameInstanceId("99") + .setGameInstanceId("44") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) + .setCatalogRevision(24L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -3594,16 +3900,290 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); + AuthenticationException advancedPointer = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); + assertEquals("CONNECT_SCOPE_MISMATCH", advancedPointer.getCode()); - ConnectTokenResult replayed = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(24L) + .setPointerVersion(19L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + AuthenticationException invalidPointer = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", invalidPointer.getCode()); + + ConnectTokenResult mismatchedReplay = + new ConnectTokenResult( + firstResult.accountId(), + firstResult.tenantId(), + firstResult.gameInstanceId() + 1L, + firstResult.realmSlug(), + firstResult.connectScopeId(), + firstResult.connectToken(), + firstResult.jti(), + firstResult.requestId(), + firstResult.issuedAt(), + firstResult.expiresAt(), + false); + verifyNoConnectTokenReplayWrites(); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) + .thenReturn( + Optional.of(new SessionService.ConnectTokenReplay(true, mismatchedReplay, "", ""))); + org.mockito.Mockito.clearInvocations(gameSessionClient, sessionService); + AuthenticationException mismatchedRecord = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); + assertEquals("AUTH_UNAVAILABLE", mismatchedRecord.getCode()); + verifyNoInteractions(gameSessionClient); + verifyNoConnectTokenReplayWrites(); + } - assertEquals(firstResult.connectToken(), replayed.connectToken()); - assertEquals(firstResult.issuedAt(), replayed.issuedAt()); - assertEquals(firstResult.expiresAt(), replayed.expiresAt()); - assertEquals(firstResult.requestId(), replayed.requestId()); - assertTrue(replayed.replayed()); + @ParameterizedTest + @ValueSource(strings = {"revoked", "inactive", "removed"}) + void issueConnectTokenRevalidatesMembershipForCachedSuccess(String membershipChange) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership activeMembership = membership(account, 7L); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(activeMembership)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-membership-replay"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + + String expectedCode; + if ("revoked".equals(membershipChange)) { + activeMembership.setGameplayAdmissionAllowed(false); + expectedCode = "CONNECT_TOKEN_REJECTED"; + } else if ("inactive".equals(membershipChange)) { + activeMembership.setLifecycleState("INACTIVE"); + activeMembership.setGameplayAdmissionAllowed(false); + expectedCode = "JOIN_REQUIRED"; + } else { + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + expectedCode = "JOIN_REQUIRED"; + } + + org.mockito.Mockito.clearInvocations(sessionService); + AuthenticationException deniedReplay = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals(expectedCode, deniedReplay.getCode()); + verifyNoConnectTokenReplayWrites(); + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "disabled,TENANT_BILLING_BLOCKED", + "unavailable,ENTITLEMENT_UNAVAILABLE" + }) + void issueConnectTokenRevalidatesEntitlementForCachedSuccess( + String entitlementState, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-entitlement-replay"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + if ("disabled".equals(entitlementState)) { + Subscription canceled = new Subscription(); + canceled.setId(23L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + } else { + when(subscriptionRepository.findByTenantId(7L)) + .thenThrow(new DataAccessResourceFailureException("entitlement authority unavailable")); + } + + org.mockito.Mockito.clearInvocations(sessionService); + AuthenticationException deniedReplay = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals(expectedCode, deniedReplay.getCode()); + verifyNoConnectTokenReplayWrites(); + } + + @ParameterizedTest + @ValueSource( + strings = {"jooq-data-access", "spring-data-access", "jooq-mapping", "jooq-configuration"}) + void issueConnectTokenClassifiesMembershipReadFailuresWithoutWritingReplay(String failureType) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-membership-outage"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + RuntimeException cause = + switch (failureType) { + case "jooq-data-access" -> + new org.jooq.exception.DataAccessException("membership authority unavailable"); + case "spring-data-access" -> + new DataAccessResourceFailureException("membership authority unavailable"); + case "jooq-mapping" -> new MappingException("membership mapping failed"); + case "jooq-configuration" -> new ConfigurationException("membership query misconfigured"); + default -> throw new IllegalArgumentException("Unknown membership failure type"); + }; + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)).thenThrow(cause); + + org.mockito.Mockito.clearInvocations(sessionService); + if (failureType.endsWith("data-access")) { + AuthenticationException freshFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertEquals("AUTH_UNAVAILABLE", freshFailure.getCode()); + assertSame(cause, freshFailure.getCause()); + } else { + RuntimeException freshFailure = + assertThrows( + RuntimeException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertSame(cause, freshFailure); + } + verifyNoConnectTokenReplayWrites(); + + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + org.mockito.Mockito.clearInvocations(sessionService); + if (failureType.endsWith("data-access")) { + AuthenticationException replayFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertEquals("AUTH_UNAVAILABLE", replayFailure.getCode()); + assertSame(cause, replayFailure.getCause()); + } else { + RuntimeException replayFailure = + assertThrows( + RuntimeException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertSame(cause, replayFailure); + } + verifyNoConnectTokenReplayWrites(); + } + + @Test + void issueConnectTokenDoesNotReplayCachedSuccessWhenPointerAuthorityIsUnavailable() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-pointer-outage"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenThrow( + new AuthenticationException( + "AUTH_UNAVAILABLE", "Admission pointer authority unavailable")); + org.mockito.Mockito.clearInvocations( + sessionService, + gameSessionClient, + subscriptionRepository, + accountTenantMembershipRepository); + + AuthenticationException replayFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals("AUTH_UNAVAILABLE", replayFailure.getCode()); + verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + verifyNoInteractions(subscriptionRepository, accountTenantMembershipRepository); + verifyNoConnectTokenReplayWrites(); } @Test @@ -3959,6 +4539,11 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); + org.mockito.Mockito.clearInvocations( + sessionService, + gameSessionClient, + subscriptionRepository, + accountTenantMembershipRepository); AuthenticationException replayedFailure = assertThrows( @@ -3973,6 +4558,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { assertEquals( "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", replayedFailure.getMessage()); + verifyNoInteractions( + gameSessionClient, subscriptionRepository, accountTenantMembershipRepository); + verifyNoConnectTokenReplayWrites(); } @Test @@ -6156,6 +6744,15 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } + private static RuntimeException unexpectedEntitlementFailure(String failureType) { + return switch (failureType) { + case "illegal-state" -> new IllegalStateException("subscription mapping failed"); + case "jooq-mapping" -> new MappingException("subscription mapping failed"); + case "jooq-configuration" -> new ConfigurationException("subscription query misconfigured"); + default -> throw new IllegalArgumentException("Unknown entitlement failure type"); + }; + } + private static Account directTextAccount() { Account account = new Account(); account.setId(11L); @@ -6198,6 +6795,34 @@ private static String hash(String password) { } } + private DirectTextJoinScope issueDirectTextConnectScopeForTest() { + Account account = new Account(); + account.setId(11L); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + DirectTextCallerContext caller = + new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + "session-1", + "direct-realms-request-1"); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L); + return service.issueDirectTextConnectScope(caller, target); + } + private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( long tenantId, String worldSlug, @@ -6239,6 +6864,33 @@ private static String playableStateNamespaceIdForTenant(long tenantId) { }; } + private void verifyNoConnectTokenReplayWrites() { + verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString()); + verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + verify(sessionService, org.mockito.Mockito.never()) + .storeAccountSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), + org.mockito.ArgumentMatchers.anyLong()); + } + private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java index 079c3c15e3..7123da4b50 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java @@ -12,7 +12,7 @@ public class GameplayCatalogProperties { new ArrayList<>( List.of( defaultWorld("demo", "Demo World", 1L, 1L, false), - defaultWorld("sandbox", "Builder Sandbox", 1L, 2L, true))); + defaultWorld("sandbox", "Builder Sandbox", 2L, 2L, true))); private static World defaultWorld( String slug, diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java index 9be0d460e1..f594d8e5cf 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java @@ -65,23 +65,6 @@ public boolean hasPrivilegedRole() { return false; } - public boolean hasGameplayElevatedRole(String tenantId) { - if (containsAnyRoleIgnoreCase(globalRoles, "platformAdmin", "moderator", "god")) { - return true; - } - return StringUtils.hasText(tenantId) - && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), "tenantAdmin", "moderator", "god"); - } - - /** Returns whether a global or requested tenant-scoped role matches a gameplay role. */ - public boolean hasGameplayRole(String tenantId, String... expectedRoles) { - if (containsAnyRoleIgnoreCase(globalRoles, expectedRoles)) { - return true; - } - return StringUtils.hasText(tenantId) - && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), expectedRoles); - } - private static List extractGlobalRoles(Object rawGlobalRoles) { if (rawGlobalRoles == null) { return List.of(); @@ -123,22 +106,4 @@ private static List normalizeRoleValues(List values) { } return normalizedRoles; } - - private static boolean containsAnyRoleIgnoreCase( - Iterable roles, String... expectedRoles) { - if (roles == null) { - return false; - } - for (String role : roles) { - if (!StringUtils.hasText(role)) { - continue; - } - for (String expectedRole : expectedRoles) { - if (role.equalsIgnoreCase(expectedRole)) { - return true; - } - } - } - return false; - } } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index 3097b0f1b7..238ea418ee 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.common.security; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; @@ -10,37 +9,19 @@ class SessionClaimsTest { @Test - void hasGameplayElevatedRoleRecognizesGlobalGodAndScopedModerator() { - SessionClaims globalGod = - new SessionClaims("11", List.of("god"), Map.of("7", List.of("player")), false, null, null); - SessionClaims scopedModerator = - new SessionClaims("11", List.of(), Map.of("7", List.of("moderator")), false, null, null); - - assertTrue(globalGod.hasGameplayElevatedRole("7")); - assertTrue(scopedModerator.hasGameplayElevatedRole("7")); - } - - @Test - void hasGameplayElevatedRoleIgnoresUnrelatedTenantScopes() { + void privilegedRoleCheckStillRecognizesGlobalControlPlaneRoles() { SessionClaims claims = - new SessionClaims("11", List.of(), Map.of("8", List.of("tenantAdmin")), false, null, null); + new SessionClaims("11", List.of("platformAdmin"), Map.of(), false, null, null); - assertFalse(claims.hasGameplayElevatedRole("7")); + assertTrue(claims.hasPrivilegedRole()); } @Test - void hasGameplayRoleChecksGlobalAndRequestedTenantScopeOnly() { + void privilegedRoleCheckStillRecognizesTenantScopedControlPlaneRoles() { SessionClaims claims = new SessionClaims( - "11", - List.of("platformAdmin"), - Map.of("7", List.of("moderator"), "8", List.of("god")), - false, - null, - null); + "11", List.of(), Map.of("7", List.of("tenantAdmin", "moderator")), false, null, null); - assertTrue(claims.hasGameplayRole("7", "platformAdmin")); - assertTrue(claims.hasGameplayRole("7", "moderator")); - assertFalse(claims.hasGameplayRole("7", "god")); + assertTrue(claims.hasPrivilegedRole()); } } 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 77891d456b..5e9db93b62 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 @@ -73,8 +73,7 @@ void runtimeAuthorityResponsesUseCurrentInjectedClockTime() throws Exception { } @Test - void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() - throws Exception { + void authenticationAndRuntimeAuthoritySnapshotsAreFreshAndComplete() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); @@ -92,6 +91,35 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .getAccountId()) .isEqualTo("7"); + var activeMembership = + stub.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-active") + .build()); + assertThat(activeMembership.getMembershipExists()).isTrue(); + assertThat(activeMembership.getGameplayAdmissionAllowed()).isTrue(); + assertThat(activeMembership.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(activeMembership.getMembershipVersion()).isEqualTo(1L); + assertThat(activeMembership.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertFresh(activeMembership.getEvaluatedAt()); + + server.denyGameplayAdmission(); + var deniedMembership = + stub.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-denied") + .build()); + assertThat(deniedMembership.getMembershipExists()).isTrue(); + assertThat(deniedMembership.getGameplayAdmissionAllowed()).isFalse(); + assertThat(deniedMembership.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(deniedMembership.getMembershipVersion()).isEqualTo(1L); + assertThat(deniedMembership.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertFresh(deniedMembership.getEvaluatedAt()); + server.setMembershipExists(false); var membership = @@ -103,12 +131,48 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .build()); assertThat(membership.getMembershipExists()).isFalse(); assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); + assertThat(membership.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(membership.getMembershipVersion()).isZero(); + assertThat(membership.getMembershipAuthorityGeneration()).isZero(); + assertFresh(membership.getEvaluatedAt()); + + var grant = + stub.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("request-grant") + .build()); + assertThat(grant.getGranted()).isTrue(); + assertThat(grant.getGrantVersion()).isEqualTo(1L); + assertFresh(grant.getEvaluatedAt()); + + var entitlement = + stub.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("request-entitlement") + .build()); + assertThat(entitlement.getGameplayAvailable()).isTrue(); + assertThat(entitlement.getAllowPublicJoin()).isTrue(); + assertThat(entitlement.getEntitlementVersion()).isEqualTo(1L); + assertThat(entitlement.getTenantBillingSequence()).isEqualTo(1L); + assertFresh(entitlement.getEvaluatedAt()); } finally { channel.shutdownNow(); } } } + private static void assertFresh(String evaluatedAt) { + Instant evaluated = Instant.parse(evaluatedAt); + Instant now = Instant.now(); + assertThat(!evaluated.isBefore(now.minusSeconds(15))).isTrue(); + assertThat(!evaluated.isAfter(now)).isTrue(); + } + @Test void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java index 5e6af546a9..bcf65911e9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolver.java @@ -114,13 +114,27 @@ static Resolution resolveRealmOrdinal( if (store == null) { return new Unavailable<>(); } - return resolveRealmOrdinal( + return resolveRealmOrdinalWithSnapshotValidation( selector, () -> store.realmsSnapshot(caller, tenantId, world.slug(), now), tenantId, world, now, currentCatalogReader, + (snapshot, currentCatalog) -> { + if (!currentCatalog.worldSlug().equalsIgnoreCase(world.slug())) { + return Optional.empty(); + } + return worldCatalog + .revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()) + .filter( + currentResponse -> + currentResponse.worldSlug().equalsIgnoreCase(world.slug()) + && snapshot + .catalogFingerprint() + .equals(currentResponse.catalogFingerprint()) + && snapshot.ordinalTargets().equals(currentResponse.ordinalTargets())); + }, (current, target) -> worldCatalog.resolveRealmSnapshotOrdinal(world, current, target)); } @@ -132,10 +146,32 @@ static Resolution resolveRealmOrdinal( Instant now, Supplier currentCatalogReader, BiFunction> currentTargetResolver) { + return resolveRealmOrdinalWithSnapshotValidation( + selector, + snapshotReader, + tenantId, + world, + now, + currentCatalogReader, + (snapshot, currentCatalog) -> Optional.of(currentCatalog), + currentTargetResolver); + } + + private static Resolution resolveRealmOrdinalWithSnapshotValidation( + String selector, + Supplier> snapshotReader, + long tenantId, + WorldView world, + Instant now, + Supplier currentCatalogReader, + BiFunction> + currentSnapshotResolver, + BiFunction> currentTargetResolver) { Objects.requireNonNull(snapshotReader, "snapshotReader must not be null"); Objects.requireNonNull(world, "world must not be null"); Objects.requireNonNull(now, "now must not be null"); Objects.requireNonNull(currentCatalogReader, "currentCatalogReader must not be null"); + Objects.requireNonNull(currentSnapshotResolver, "currentSnapshotResolver must not be null"); Objects.requireNonNull(currentTargetResolver, "currentTargetResolver must not be null"); Optional maybeSnapshot; @@ -158,16 +194,21 @@ static Resolution resolveRealmOrdinal( return new SnapshotMismatch<>(); } - RealmDiscoverySnapshot currentCatalog; + Optional maybeCurrentResponse; try { - currentCatalog = currentCatalogReader.get(); + RealmDiscoverySnapshot currentCatalog = currentCatalogReader.get(); + maybeCurrentResponse = currentSnapshotResolver.apply(snapshot, currentCatalog); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return new Unavailable<>(); } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { return new PointerUnavailable<>(); } - if (!currentCatalog.worldSlug().equalsIgnoreCase(world.slug()) - || !snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + if (maybeCurrentResponse.isEmpty()) { + return new SnapshotMismatch<>(); + } + RealmDiscoverySnapshot currentResponse = maybeCurrentResponse.orElseThrow(); + if (!currentResponse.worldSlug().equalsIgnoreCase(world.slug()) + || !snapshot.catalogFingerprint().equals(currentResponse.catalogFingerprint())) { return new SnapshotMismatch<>(); } Optional maybeOrdinal = parseOrdinal(selector); @@ -181,7 +222,7 @@ static Resolution resolveRealmOrdinal( if (maybeTarget.isEmpty()) { return new UnboundSelector<>(); } - Optional selected = currentTargetResolver.apply(currentCatalog, maybeTarget.orElseThrow()); + Optional selected = currentTargetResolver.apply(currentResponse, maybeTarget.orElseThrow()); return selected.>map(Selected::new).orElseGet(SnapshotMismatch::new); } 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 c384459fab..cb68592db1 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 @@ -16,6 +16,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.LongFunction; +import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; @@ -66,15 +67,18 @@ public static GameplayWorldCatalog forWorldSupplier(Supplier> wo } public WorldsViewOutput browseView() { - return readDiscoverySnapshot().output(); + CatalogState catalogState = readCatalogState(); + return buildDiscoverySnapshot(catalogState, visibleWorlds(catalogState)).output(); } - /** Reads the catalog once and builds the exact public WORLDS projection and ordinal authority. */ + /** Reads a tenant-qualified snapshot for retained, response-local world ordinals. */ public DiscoverySnapshot readDiscoverySnapshot() { CatalogState catalogState = readCatalogState(); - List catalogWorlds = catalogState.worlds(); - List visibleWorlds = - catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); + return buildDiscoverySnapshot(catalogState, qualifiedVisibleWorlds(catalogState)); + } + + private DiscoverySnapshot buildDiscoverySnapshot( + CatalogState catalogState, List visibleWorlds) { List discoverableWorlds = visibleWorlds.stream() .filter(world -> hasPublicDiscoveryRealm(world, catalogState)) @@ -153,37 +157,38 @@ public static boolean isOrdinalSelector(String selector) { } public Optional browseRealms(String worldSelector) { - if (worldSelector == null || worldSelector.isBlank()) { + return resolvePublicWorld(worldSelector) + .map(world -> new RealmBrowseViewOutput(world.slug(), realmEntries(world))); + } + + /** Resolves only realms currently safe to expose through the public browse projections. */ + public Optional resolvePublicWorld(String selector) { + if (selector == null || selector.isBlank()) { return Optional.empty(); } - return resolveWorld(worldSelector) - .filter(world -> visibleRealms(world).stream().anyMatch(RealmView::publicProductionRealm)) - .map( - world -> - new RealmBrowseViewOutput( - world.slug(), - realmEntries( - new WorldView( - world.slug(), - world.displayName(), - visibleRealms(world).stream() - .filter(RealmView::publicProductionRealm) - .toList())))); + if (isOrdinalSelector(selector)) { + return Optional.empty(); + } + List worlds = publicVisibleWorlds(); + String normalized = selector.trim().toLowerCase(Locale.ROOT); + List matches = + worlds.stream() + .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } - /** Reads the current realm catalog and records the exact response-local ordinal targets. */ + /** Builds the public REALMS snapshot from the entries currently exposed in that response. */ public RealmDiscoverySnapshot readRealmDiscoverySnapshot(WorldView world) { Objects.requireNonNull(world, "world must not be null"); return realmDiscoverySnapshot(world, publicProductionRealms(world)); } - /** Builds a REALMS snapshot whose ordinals match the filtered response entries. */ + /** Builds a REALMS snapshot and fingerprint from the exact caller-visible response entries. */ public RealmDiscoverySnapshot realmDiscoverySnapshot( WorldView world, List responseRealms) { Objects.requireNonNull(world, "world must not be null"); List visibleCatalogRealms = visibleRealms(world); - List publicCatalogRealms = - visibleCatalogRealms.stream().filter(RealmView::publicProductionRealm).toList(); List safeResponseRealms = List.copyOf(Objects.requireNonNull(responseRealms, "responseRealms must not be null")); if (safeResponseRealms.stream().anyMatch(realm -> !visibleCatalogRealms.contains(realm))) { @@ -201,25 +206,51 @@ public RealmDiscoverySnapshot realmDiscoverySnapshot( realm.pointerVersion(), realmTargetFingerprint(world, realm))); } - List catalogTargets = new ArrayList<>(publicCatalogRealms.size()); - for (int index = 0; index < publicCatalogRealms.size(); index++) { - RealmView realm = publicCatalogRealms.get(index); - catalogTargets.add( + return new RealmDiscoverySnapshot( + world.slug(), realmDiscoveryFingerprint(targets), List.copyOf(targets)); + } + + /** + * Revalidates pointer identity for only the targets included in a caller's REALMS response. + * Callers must still perform fresh membership, entitlement, and grant checks before admission. + */ + public Optional revalidateRealmDiscoverySnapshot( + WorldView world, List responseTargets) { + Objects.requireNonNull(world, "world must not be null"); + List safeResponseTargets = + List.copyOf(Objects.requireNonNull(responseTargets, "responseTargets must not be null")); + if (safeResponseTargets.isEmpty()) { + return Optional.empty(); + } + + List currentRealms = visibleRealms(world); + List currentTargets = new ArrayList<>(safeResponseTargets.size()); + for (int index = 0; index < safeResponseTargets.size(); index++) { + RealmOrdinalTarget responseTarget = safeResponseTargets.get(index); + if (responseTarget.ordinal() != index + 1) { + return Optional.empty(); + } + List matches = + currentRealms.stream() + .filter(realm -> realm.slug().equalsIgnoreCase(responseTarget.realmSlug())) + .filter(realm -> realm.tenantId() == responseTarget.tenantId()) + .toList(); + if (matches.size() != 1) { + return Optional.empty(); + } + RealmView realm = matches.getFirst(); + currentTargets.add( new RealmOrdinalTarget( - index + 1, + responseTarget.ordinal(), realm.slug(), realm.tenantId(), realm.catalogRevision(), realm.pointerVersion(), realmTargetFingerprint(world, realm))); } - return new RealmDiscoverySnapshot( - world.slug(), - fingerprint( - catalogTargets.stream() - .map(GameplayWorldCatalog::realmTargetFingerprintInput) - .toList()), - List.copyOf(targets)); + return Optional.of( + new RealmDiscoverySnapshot( + world.slug(), realmDiscoveryFingerprint(currentTargets), List.copyOf(currentTargets))); } /** Resolves a numeric REALMS target by identity, never by its current ordinal. */ @@ -231,15 +262,18 @@ public Optional resolveRealmSnapshotOrdinal( if (!world.slug().equalsIgnoreCase(current.worldSlug())) { return Optional.empty(); } - return visibleRealms(world).stream() - .filter(realm -> realm.slug().equalsIgnoreCase(originatingTarget.realmSlug())) - .filter(realm -> realm.tenantId() == originatingTarget.tenantId()) - .filter(realm -> realm.catalogRevision() == originatingTarget.catalogRevision()) - .filter(realm -> realm.pointerVersion() == originatingTarget.pointerVersion()) - .filter( - realm -> - realmTargetFingerprint(world, realm).equals(originatingTarget.targetFingerprint())) - .findFirst(); + List matches = + visibleRealms(world).stream() + .filter(realm -> realm.slug().equalsIgnoreCase(originatingTarget.realmSlug())) + .filter(realm -> realm.tenantId() == originatingTarget.tenantId()) + .filter(realm -> realm.catalogRevision() == originatingTarget.catalogRevision()) + .filter(realm -> realm.pointerVersion() == originatingTarget.pointerVersion()) + .filter( + realm -> + realmTargetFingerprint(world, realm) + .equals(originatingTarget.targetFingerprint())) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } public Optional resolveWorld(String selector) { @@ -247,9 +281,7 @@ public Optional resolveWorld(String selector) { return Optional.empty(); } CatalogState catalogState = readCatalogState(); - List catalogWorlds = catalogState.worlds(); - List visibleWorlds = - catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); + List visibleWorlds = visibleWorlds(catalogState); return resolveWorld(selector, visibleWorlds, discoverableWorlds(visibleWorlds, catalogState)); } @@ -257,40 +289,44 @@ public Optional resolveWorldFromAuthoritySnapshot(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - CatalogState state; - if (authorityPointerSupplier != null && !isOrdinalSelector(selector)) { - List pointers = loadAuthorityPointers(); - Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); - String selectedWorld = selectorKey(selector); - boolean selectedInvalidTenant = - pointers.stream() - .filter(Objects::nonNull) - .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) - .filter(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))) - .anyMatch(pointer -> invalidTenantIds.contains(pointer.tenantId())); - if (!selectedInvalidTenant && !invalidTenantIds.isEmpty()) { - boolean selectorExists = - pointers.stream() - .filter(Objects::nonNull) - .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) - .anyMatch(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))); - if (!selectorExists) { - requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); - } - } - state = catalogStateFromPointers(healthyTenantPointers(pointers)); - } else if (authorityPointerSupplier != null) { - state = catalogStateFromPointers(healthyTenantPointers(loadAuthorityPointers())); - } else { - state = loadAuthorityWorldSnapshot(); + if (authorityPointerSupplier == null) { + return resolveStableWorld(selector, visibleWorlds(readCatalogState())); + } + List pointers = loadAuthorityPointers(); + Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); + String selectedWorld = selectorKey(selector); + boolean selectorExists = + pointers.stream() + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .anyMatch(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))); + boolean selectedInvalidTenant = + pointers.stream() + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .filter(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))) + .anyMatch(pointer -> invalidTenantIds.contains(pointer.tenantId())); + if (selectedInvalidTenant) { + return Optional.empty(); + } + if (!invalidTenantIds.isEmpty() && !selectorExists) { + requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); } - List worlds = visibleWorlds(state); - return resolveWorld(selector, worlds, discoverableWorlds(worlds, state)); + CatalogState snapshot = catalogStateFromPointers(pointers); + return resolveStableWorld(selector, visibleWorlds(snapshot)); } /** Builds the no-caller discovery projection from one validated authority snapshot. */ public List publicWorldsFromAuthoritySnapshot() { - return unambiguousTenantWorlds(publicDiscoveryWorlds(loadAuthorityWorldSnapshot())); + if (authorityPointerSupplier == null) { + return unambiguousTenantWorlds(publicDiscoveryWorlds(loadAuthorityWorldSnapshot())); + } + return publicWorldsFromAuthoritySnapshot(loadAuthorityPointers()); + } + + /** Builds the no-caller discovery projection from the supplied authoritative snapshot. */ + public List publicWorldsFromAuthoritySnapshot( + List pointerSnapshot) { + List validated = validateAuthoritySnapshot(pointerSnapshot); + return unambiguousTenantWorlds(publicDiscoveryWorlds(catalogStateFromPointers(validated))); } /** Resolves only worlds exposed by the no-caller public discovery surface. */ @@ -299,25 +335,51 @@ public Optional resolvePublicWorldFromAuthoritySnapshot(String select return Optional.empty(); } if (authorityPointerSupplier == null) { - return resolveWorld(selector, publicWorldsFromAuthoritySnapshot()); + return resolveStableWorld(selector, publicWorldsFromAuthoritySnapshot()); } - List pointers = loadAuthorityPointers(); - if (!isOrdinalSelector(selector)) { - Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); - String selectedWorld = selectorKey(selector); - boolean selectedUnhealthyTenant = + return resolvePublicWorldFromAuthoritySnapshot(selector, loadAuthorityPointers()); + } + + /** Resolves a stable world slug against the supplied authoritative snapshot. */ + public Optional resolvePublicWorldFromAuthoritySnapshot( + String selector, List pointerSnapshot) { + if (selector == null || selector.isBlank()) { + return Optional.empty(); + } + List pointers = validateAuthoritySnapshot(pointerSnapshot); + Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); + String selectedWorld = selectorKey(selector); + if (ambiguousWorldSelectors(pointers).contains(selectedWorld)) { + return Optional.empty(); + } + boolean selectedInvalidTenant = + pointers.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .filter(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))) + .anyMatch(pointer -> invalidTenantIds.contains(pointer.tenantId())); + if (selectedInvalidTenant) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm count is invalid for selected world"); + } + if (!invalidTenantIds.isEmpty()) { + boolean selectorExists = pointers.stream() .filter(Objects::nonNull) .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) - .filter(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))) - .anyMatch(pointer -> invalidTenantIds.contains(pointer.tenantId())); - if (selectedUnhealthyTenant) { - throw new AuthorityPointerUnavailableException( - "Authoritative public-production realm count is invalid for selected world"); + .anyMatch(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))); + if (!selectorExists) { + requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); } } - CatalogState snapshot = catalogStateFromPointers(healthyTenantPointers(pointers)); - return resolveWorld(selector, unambiguousTenantWorlds(publicDiscoveryWorlds(snapshot))); + CatalogState snapshot = catalogStateFromPointers(pointers); + // This RPC accepts a stable slug, not a response-local menu ordinal. Digit-only authored + // slugs resolve by exact normalized slug rather than by list position. + return resolveStableWorld(selector, unambiguousTenantWorlds(publicDiscoveryWorlds(snapshot))); + } + + private Optional resolveStableWorld(String selector, List worlds) { + return resolveWorldBySlug(selector, worlds); } private Optional resolveWorld( @@ -333,18 +395,6 @@ private Optional resolveWorld( return resolveWorldBySlug(selector, visibleWorlds); } - private Optional resolveWorld(String selector, List worlds) { - try { - int index = Integer.parseInt(selector); - if (index >= 1 && index <= worlds.size()) { - return Optional.of(worlds.get(index - 1)); - } - } catch (NumberFormatException ignored) { - // Fall back to slug matching. - } - return resolveWorldBySlug(selector, worlds); - } - private Optional resolveWorldBySlug(String selector, List worlds) { String normalized = selectorKey(selector); List matches = @@ -478,6 +528,11 @@ private static String realmTargetFingerprintInput(RealmOrdinalTarget target) { + target.targetFingerprint(); } + private static String realmDiscoveryFingerprint(List targets) { + return fingerprint( + targets.stream().map(GameplayWorldCatalog::realmTargetFingerprintInput).toList()); + } + private static String targetFingerprintInput(WorldOrdinalTarget target) { return target.ordinal() + "|" @@ -612,7 +667,8 @@ public boolean isPubliclyDiscoverable(DiscoverySnapshot snapshot, WorldView worl } public boolean requiresExplicitRealmSelection(WorldView world) { - return visibleRealms(world).size() > 1; + List publicRealms = publicVisibleRealms(world); + return publicRealms.size() > 1 || (publicRealms.isEmpty() && visibleRealms(world).size() > 1); } public Optional resolveRealmByRuntimeTarget(long tenantId, long gameInstanceId) { @@ -674,15 +730,24 @@ public List visibleRealms(WorldView world) { if (world == null || world.realms() == null) { return List.of(); } - return world.realms().stream().filter(RealmView::visible).toList(); + return normalizedRealmViews(world.realms()).stream().filter(RealmView::visible).toList(); } - private List publicProductionRealms(WorldView world) { + public List publicVisibleRealms(WorldView world) { return visibleRealms(world).stream().filter(RealmView::publicProductionRealm).toList(); } + private List publicProductionRealms(WorldView world) { + return publicVisibleRealms(world); + } + public List visibleWorlds() { - return readCatalogState().worlds().stream().filter(this::hasVisibleRealmEntries).toList(); + return visibleWorlds(readCatalogState()); + } + + /** Returns only worlds whose public browse projection has one unambiguous realm. */ + public List publicVisibleWorlds() { + return unambiguousTenantWorlds(publicDiscoveryWorlds(readCatalogState())); } /** Builds the visible world projection from one validated authoritative pointer snapshot. */ @@ -709,6 +774,31 @@ public void requireUniqueVisiblePublicProductionRealm( } List pointers = loadAuthorityPointersForTenant(expectedPointer.tenantId()); + requireUniqueVisiblePublicProductionRealm(expectedPointer, pointers); + } + + /** Validates one tenant's complete catalog from an already-read authority snapshot. */ + public void requireHealthyPointerCatalog( + List pointerSnapshot, long tenantId) { + List pointers = + tenantPointersFromSnapshot(pointerSnapshot, tenantId); + if (!tenantHasValidPublicProductionAuthority(pointers, tenantId)) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm is incomplete or ambiguous for tenant " + + tenantId); + } + } + + /** Validates a public target against one previously-read authority snapshot. */ + public void requireUniqueVisiblePublicProductionRealm( + GameplayAdmissionPointerSnapshot expectedPointer, + List pointerSnapshot) { + if (expectedPointer == null || expectedPointer.tenantId() <= 0L) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm identity is unavailable"); + } + List pointers = + tenantPointersFromSnapshot(pointerSnapshot, expectedPointer.tenantId()); if (!tenantHasValidPublicProductionAuthority(pointers, expectedPointer.tenantId())) { throw new AuthorityPointerUnavailableException( "Authoritative public-production realm is incomplete or ambiguous for tenant " @@ -812,6 +902,24 @@ public void requireHealthyVisiblePrivateRealm(GameplayAdmissionPointerSnapshot e } List pointers = loadAuthorityPointersForTenant(expectedPointer.tenantId()); + requireHealthyVisiblePrivateRealm(expectedPointer, pointers); + } + + /** Validates a visible private target against one previously-read authority snapshot. */ + public void requireHealthyVisiblePrivateRealm( + GameplayAdmissionPointerSnapshot expectedPointer, + List pointerSnapshot) { + if (expectedPointer == null + || expectedPointer.tenantId() <= 0L + || !expectedPointer.visible() + || expectedPointer.publicProductionRealm() + || !isPlayerAddressable(expectedPointer) + || !hasCompleteAuthorityPointer(expectedPointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative visible private realm identity is unavailable"); + } + List pointers = + tenantPointersFromSnapshot(pointerSnapshot, expectedPointer.tenantId()); if (!tenantHasValidPublicProductionAuthority(pointers, expectedPointer.tenantId())) { throw new AuthorityPointerUnavailableException( "Authoritative public-production realm is incomplete or ambiguous for tenant " @@ -830,6 +938,25 @@ public void requireHealthyVisiblePrivateRealm(GameplayAdmissionPointerSnapshot e requireCollisionSafeVisiblePointer(pointers, expectedPointer); } + private static List tenantPointersFromSnapshot( + List pointerSnapshot, long tenantId) { + if (tenantId <= 0L || pointerSnapshot == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer snapshot is unavailable"); + } + List tenantPointers = new ArrayList<>(); + for (GameplayAdmissionPointerSnapshot pointer : pointerSnapshot) { + if (pointer == null || pointer.tenantId() <= 0L) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer identity is unavailable"); + } + if (pointer.tenantId() == tenantId) { + tenantPointers.add(pointer); + } + } + return List.copyOf(tenantPointers); + } + private static void requireCollisionSafeVisiblePointer( List pointers, GameplayAdmissionPointerSnapshot expectedPointer) { @@ -910,7 +1037,7 @@ && hasValidPublicProductionRealm( } private List realmEntries(WorldView world) { - List realms = visibleRealms(world); + List realms = publicVisibleRealms(world); ArrayList entries = new ArrayList<>(realms.size()); for (int i = 0; i < realms.size(); i++) { RealmView realm = realms.get(i); @@ -968,29 +1095,39 @@ private static List unambiguousTenantWorlds(List worlds) { .toList(); } - private static boolean isPlayerAddressable(RealmView realm) { - return realm != null - && realm.visible() - && realm.slug() != null - && !realm.slug().isBlank() - && realm.tenantId() > 0L; - } - private boolean hasValidPublicProductionRealm(CatalogState catalogState, long tenantId) { return tenantId > 0L && catalogState.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L; } private CatalogState readCatalogState() { if (authorityPointerSupplier == null) { - List worlds = normalizeWorlds(worldSupplier.get()); - return new CatalogState(worlds, publicProductionCounts(worlds)); + List suppliedWorlds = Objects.requireNonNullElse(worldSupplier.get(), List.of()); + List worlds = normalizeWorlds(suppliedWorlds); + // Count authoritative rows before normalization removes case-colliding realm selectors. + Map publicCounts = publicProductionCounts(suppliedWorlds); + return new CatalogState( + worlds, + publicCounts, + ambiguousWorldSelectorsFromWorlds(suppliedWorlds), + ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds(suppliedWorlds, publicCounts)); } - return catalogStateFromPointers(healthyTenantPointers(readAuthorityPointers())); + return catalogStateFromPointers(loadAuthorityPointers()); } private static CatalogState catalogStateFromPointers( List pointers) { - return new CatalogState(toWorlds(pointers), publicProductionCountsFromPointers(pointers)); + List validated = validateAuthoritySnapshot(pointers); + Set ambiguousSelectors = ambiguousWorldSelectors(validated); + Set unhealthyTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(validated); + List healthyPointers = + validated.stream() + .filter(pointer -> !unhealthyTenantIds.contains(pointer.tenantId())) + .toList(); + return new CatalogState( + toWorlds(healthyPointers), + publicProductionCountsFromPointers(healthyPointers), + ambiguousSelectors, + ambiguousWorldSelectorsWithUnhealthyTenants(validated, unhealthyTenantIds)); } private List readAuthorityPointers() { @@ -1022,12 +1159,18 @@ private static List readAuthorityPointers( private Map publicProductionCounts(List worlds) { Map counts = new LinkedHashMap<>(); + if (worlds == null) { + return Map.of(); + } for (WorldView world : worlds) { - if (world.realms() == null) { + if (world == null || world.realms() == null) { continue; } for (RealmView realm : world.realms()) { - if (isPlayerAddressable(realm) && realm.publicProductionRealm()) { + if (realm != null + && realm.visible() + && realm.tenantId() > 0L + && realm.publicProductionRealm()) { counts.merge(realm.tenantId(), 1L, Long::sum); } } @@ -1049,22 +1192,34 @@ private CatalogState loadAuthorityWorldSnapshot() { if (authorityPointerSupplier == null) { return readCatalogState(); } - return catalogStateFromPointers(healthyTenantPointers(loadAuthorityPointers())); + return catalogStateFromPointers(loadAuthorityPointers()); } private List visibleWorlds(CatalogState snapshot) { - return snapshot.worlds().stream().filter(this::hasVisibleRealmEntries).toList(); + return snapshot.worlds().stream() + .filter(world -> !snapshot.ambiguousWorldSelectors().contains(selectorKey(world.slug()))) + .filter(this::hasVisibleRealmEntries) + .toList(); + } + + private List qualifiedVisibleWorlds(CatalogState snapshot) { + return snapshot.worlds().stream() + .filter( + world -> + !snapshot + .ambiguousWorldSelectorsWithUnhealthyTenants() + .contains(selectorKey(world.slug()))) + .filter(this::hasVisibleRealmEntries) + .toList(); } private static Map publicProductionCountsFromPointers( List pointers) { Map counts = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { - if (hasCompleteAuthorityPointer(pointer) + if (pointer != null && pointer.visible() && pointer.tenantId() > 0L - && pointer.realmSlug() != null - && !pointer.realmSlug().isBlank() && pointer.publicProductionRealm()) { counts.merge(pointer.tenantId(), 1L, Long::sum); } @@ -1101,19 +1256,42 @@ private static List normalizeWorlds(List worlds) { .toList(); } - private record CatalogState(List worlds, Map publicProductionCounts) { + private record CatalogState( + List worlds, + Map publicProductionCounts, + Set ambiguousWorldSelectors, + Set ambiguousWorldSelectorsWithUnhealthyTenants) { + private CatalogState(List worlds, Map publicProductionCounts) { + this( + worlds, + publicProductionCounts, + ambiguousWorldSelectorsFromWorlds(worlds), + ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds(worlds, publicProductionCounts)); + } + private CatalogState { worlds = List.copyOf(Objects.requireNonNull(worlds, "worlds must not be null")); publicProductionCounts = Map.copyOf( Objects.requireNonNull( publicProductionCounts, "publicProductionCounts must not be null")); + ambiguousWorldSelectors = + Set.copyOf( + Objects.requireNonNull( + ambiguousWorldSelectors, "ambiguousWorldSelectors must not be null")); + ambiguousWorldSelectorsWithUnhealthyTenants = + Set.copyOf( + Objects.requireNonNull( + ambiguousWorldSelectorsWithUnhealthyTenants, + "ambiguousWorldSelectorsWithUnhealthyTenants must not be null")); } } private static List toWorlds(List pointers) { + List sourcePointers = + pointers == null ? List.of() : pointers.stream().filter(Objects::nonNull).toList(); Map> worldSpellings = new HashMap<>(); - for (GameplayAdmissionPointerSnapshot pointer : pointers) { + for (GameplayAdmissionPointerSnapshot pointer : sourcePointers) { if (hasCompleteAuthorityPointer(pointer)) { WorldIdentity identity = worldIdentity(pointer); worldSpellings @@ -1128,7 +1306,7 @@ private static List toWorlds(List p .collect(Collectors.toSet()); Map worlds = new LinkedHashMap<>(); - for (GameplayAdmissionPointerSnapshot pointer : pointers) { + for (GameplayAdmissionPointerSnapshot pointer : sourcePointers) { if (!hasCompleteAuthorityPointer(pointer) || ambiguousWorldSlugs.contains(worldIdentity(pointer))) { continue; @@ -1205,6 +1383,76 @@ private static List healthyTenantPointers( .toList(); } + private static Set ambiguousWorldSelectors( + List pointers) { + return ambiguousWorldSelectors(selectorTenantsByPointer(pointers), null); + } + + private static Set ambiguousWorldSelectorsFromWorlds(List worlds) { + return ambiguousWorldSelectors(selectorTenantsByWorld(worlds), null); + } + + private static Map> selectorTenantsByPointer( + List pointers) { + Map> tenantsBySelector = new HashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (pointer.worldSlug() == null || pointer.worldSlug().isBlank()) { + continue; + } + tenantsBySelector + .computeIfAbsent(selectorKey(pointer.worldSlug()), ignored -> new HashSet<>()) + .add(pointer.tenantId()); + } + return tenantsBySelector; + } + + private static Map> selectorTenantsByWorld(List worlds) { + Map> tenantsBySelector = new HashMap<>(); + for (WorldView world : worlds) { + if (world == null + || world.slug() == null + || world.slug().isBlank() + || world.realms() == null) { + continue; + } + world.realms().stream() + .filter(Objects::nonNull) + .map(RealmView::tenantId) + .filter(tenantId -> tenantId > 0L) + .forEach( + tenantId -> + tenantsBySelector + .computeIfAbsent(selectorKey(world.slug()), ignored -> new HashSet<>()) + .add(tenantId)); + } + return tenantsBySelector; + } + + private static Set ambiguousWorldSelectors( + Map> tenantsBySelector, Predicate unhealthyTenantPredicate) { + return tenantsBySelector.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .filter( + entry -> + unhealthyTenantPredicate == null + || entry.getValue().stream().anyMatch(unhealthyTenantPredicate)) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); + } + + private static Set ambiguousWorldSelectorsWithUnhealthyTenants( + List pointers, Set unhealthyTenantIds) { + return ambiguousWorldSelectors( + selectorTenantsByPointer(pointers), unhealthyTenantIds::contains); + } + + private static Set ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds( + List worlds, Map publicProductionCounts) { + return ambiguousWorldSelectors( + selectorTenantsByWorld(worlds), + tenantId -> publicProductionCounts.getOrDefault(tenantId, 0L) != 1L); + } + private static boolean tenantHasValidPublicProductionAuthority( List pointers, long tenantId) { long visiblePublicRealmCount = 0L; @@ -1298,10 +1546,15 @@ private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { } private static WorldView copyWorldView(WorldView input) { + List realms = normalizedRealmViews(input.realms()); + return new WorldView(input.slug(), input.displayName(), realms); + } + + private static List normalizedRealmViews(List input) { List realms = - input.realms() == null + input == null ? List.of() - : input.realms().stream() + : input.stream() .filter(Objects::nonNull) .filter(realm -> realm.slug() != null && !realm.slug().isBlank()) .map(GameplayWorldCatalog::copyRealmView) @@ -1311,16 +1564,12 @@ private static WorldView copyWorldView(WorldView input) { realmCounts.merge( new RealmSelectorKey(realm.tenantId(), selectorKey(realm.slug())), 1, Integer::sum); } - return new WorldView( - input.slug(), - input.displayName(), - realms.stream() - .filter( - realm -> - realmCounts.get( - new RealmSelectorKey(realm.tenantId(), selectorKey(realm.slug()))) - == 1) - .toList()); + return realms.stream() + .filter( + realm -> + realmCounts.get(new RealmSelectorKey(realm.tenantId(), selectorKey(realm.slug()))) + == 1) + .toList(); } private static String selectorKey(String slug) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index cd07448647..dc26f8c5f3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -83,7 +83,8 @@ public TextCommandInterpretationResult handle( success( "PLAY [realm] [character]\n" + "Select the world to enter, optionally name a visible realm, and optionally choose a character.\n" - + "Use the character name shown by CHARS, not its list number."); + + "Character browsing is currently unavailable; " + + "use a known character name, not a list number."); case "JOIN" -> success( "JOIN \n" @@ -94,18 +95,19 @@ public TextCommandInterpretationResult handle( success( "REALMS \n" + "List visible realms for the selected world.\n" - + "Use this before CHARS or PLAY when a world exposes more than one realm."); + + "Use this before PLAY when a world exposes more than one realm.\n" + + "Character browsing is currently unavailable; PLAY requires a known character when selection is needed."); case "CHARS" -> success( "CHARS [realm]\n" - + "List visible characters for the selected world and realm.\n" - + "Use REALMS first when the world exposes more than one realm.\n" - + "Use the character name with PLAY; list numbers are not character selectors."); + + "Character browsing is currently unavailable.\n" + + "Use PLAY [realm] with a known character."); case "WHO" -> success( "WHO\n" + "List currently connected players in this game instance.\n" - + "Gods appear first, then players.\n" + + "Connected users are currently classified as players; " + + "gameplay-grant roles are not yet shown.\n" + "You must already be in-world with PLAY."); case "STATUS" -> success( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index adaa51cde8..caea2f0f07 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -437,6 +437,24 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { return characterIdentityUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); } + boolean retainedTargetMatchesSelection = + context.hasGameplayIdentity() + && context.tenantId() == selectedRealm.tenantId() + && context.gameInstanceId() == selectedRealm.gameInstanceId() + && (!StringUtils.hasText(context.worldSlug()) + || sameSlug(context.worldSlug(), selectedWorld.slug())) + && (!StringUtils.hasText(context.realmSlug()) + || sameSlug(context.realmSlug(), selectedRealm.slug())); + if (!StringUtils.hasText(character) + && retainedTargetMatchesSelection + && context.characterId() != resolvedCharacter.id()) { + return characterIdentityUnavailableFailure( + selectedTenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(context.characterId()), + new IllegalStateException( + "Current persisted roster no longer contains the retained actor")); + } String characterName = resolvedCharacter.name(); Optional moderationFailure = validateModerationPolicy(context, selectedRealm, selectedTenantTag); @@ -646,6 +664,9 @@ private ResolvedCharacter resolveCharacter( GameplayWorldCatalog.RealmView selectedRealm, String requestedCharacter) { PlayableStateScope playableStateScope = toPlayableStateScope(selectedRealm); + if (playableStateScope == PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) { + throw new IllegalStateException("Selected realm has no playable-state scope"); + } ListCharactersByAccountResponse response = entityManagementClient.listCharactersByAccount( Long.toString(selectedRealm.tenantId()), @@ -669,7 +690,6 @@ private ResolvedCharacter resolveCharacter( "Malformed or unauthorized character roster for selected gameplay target"); } } - Character selected; if (StringUtils.hasText(requestedCharacter)) { List matches = @@ -804,6 +824,14 @@ private Optional validateRuntimeAdmission( String tenantTag, long requestedCharacterId) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); + // This is only a denial-cleanup hint for an already bound runtime, never actor admission. + long denialCleanupCharacterId = + context.accountId() > 0L + && context.tenantId() == selectedRealm.tenantId() + && context.gameInstanceId() == selectedRealm.gameInstanceId() + && context.characterId() > 0L + ? context.characterId() + : requestedCharacterId > 0L ? requestedCharacterId : 0L; GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); @@ -814,7 +842,7 @@ private Optional validateRuntimeAdmission( tenantTag, selectedWorld, selectedRealm, - requestedCharacterId, + denialCleanupCharacterId, requestId); if (membershipFailure.isPresent()) { return membershipFailure; @@ -829,7 +857,7 @@ private Optional validateRuntimeAdmission( tenantTag, selectedWorld, selectedRealm, - requestedCharacterId); + denialCleanupCharacterId); } private long requireResolvedCharacterId(String characterId) { @@ -869,6 +897,11 @@ private Optional validateMembershipResponse( String requestId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { + if ("FAILED_PRECONDITION".equalsIgnoreCase(maybeError.orElseThrow().getCode())) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } if (!isAuthorityUnavailable(maybeError.orElseThrow())) { return Optional.of( worldAccessDeniedFailure( @@ -909,12 +942,12 @@ private Optional validateMembershipResponse( } recordResumeDeniedIfApplicable( context, + selectedRealm.tenantId(), selectedWorld.slug(), selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "join_required"); return Optional.of( failure( @@ -968,12 +1001,12 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( long requestedCharacterId) { recordResumeDeniedIfApplicable( context, + selectedRealm.tenantId(), selectedWorld.slug(), selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "access_denied"); return failure( GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE, @@ -999,12 +1032,12 @@ private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( long requestedCharacterId) { recordResumeDeniedIfApplicable( context, + selectedRealm.tenantId(), selectedWorld.slug(), selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "public_admission_denied"); return failure( PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE, @@ -1026,7 +1059,10 @@ private Optional validateEntitlementsResponse( long requestedCharacterId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { - if (isEntitlementUnavailable(maybeError.get())) { + if (isEntitlementUnavailable(maybeError.get()) + || "FAILED_PRECONDITION".equalsIgnoreCase(maybeError.get().getCode())) { + // Account uses FAILED_PRECONDITION when this request cannot prove its caller/target + // binding; that is unavailable authority, not a gameplay-policy denial. return Optional.of( entitlementUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); @@ -1061,12 +1097,12 @@ private PlayCommandHandlingResult tenantBillingBlockedFailure( long requestedCharacterId) { recordResumeDeniedIfApplicable( context, + selectedRealm.tenantId(), selectedWorld.slug(), selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "tenant_unavailable"); return failure( GameplayStageCommandConstants.TENANT_BILLING_BLOCKED_CODE, @@ -1383,9 +1419,7 @@ private String characterSelectionMessage( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { return "Selection required. Use " + playUsage(selectedWorld, selectedRealm) - + " or browse " - + charsUsage(selectedWorld, selectedRealm) - + " first."; + + " with a known character; character browsing is currently unavailable."; } private PlayCommandHandlingResult characterSelectionRequiredFailure( @@ -1396,15 +1430,7 @@ private PlayCommandHandlingResult characterSelectionRequiredFailure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, characterSelectionMessage(selectedWorld, selectedRealm), "error.play.character-selection-required", - Map.of( - "worldSlug", - selectedWorld.slug(), - "realmSlug", - selectedRealm.slug(), - "playUsage", - playUsage(selectedWorld, selectedRealm), - "charsUsage", - charsUsage(selectedWorld, selectedRealm)), + Map.of("playUsage", playUsage(selectedWorld, selectedRealm)), tenantTag, Long.toString(selectedRealm.gameInstanceId()), null, @@ -1431,13 +1457,6 @@ private String playUsage( + " "; } - private String charsUsage( - GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { - return "CHARS " - + selectedWorld.slug() - + (selectedRealm.publicProductionRealm() ? "" : " " + selectedRealm.slug()); - } - private record ResolvedPlaySelection( String worldSelector, String explicitRealmSelector, String characterSelector) {} @@ -1453,24 +1472,21 @@ private CharacterSelectionRequiredException(String message) { private void recordResumeDeniedIfApplicable( SessionContext context, + long requestedTenantId, String requestedWorldSlug, String requestedRealmSlug, long requestedPointerVersion, long requestedGameInstanceId, - long requestedCharacterId, - String tenantTag, + String selectedTenantTag, String reason) { - boolean sameGameplayIdentity = - Long.toString(context.tenantId()).equals(tenantTag) - && context.gameInstanceId() == requestedGameInstanceId - && (requestedCharacterId > 0 - ? context.characterId() == requestedCharacterId - : context.hasGameplayBinding()); - boolean sameVisibleRealm = - Long.toString(context.tenantId()).equals(tenantTag) - && sameSlug(context.worldSlug(), requestedWorldSlug) - && sameSlug(context.realmSlug(), requestedRealmSlug); - if (!sameGameplayIdentity && !sameVisibleRealm) { + boolean sameRuntimeTarget = + requestedTenantId > 0L + && context.tenantId() > 0L + && requestedTenantId == context.tenantId() + && requestedGameInstanceId > 0L + && context.gameInstanceId() > 0L + && context.gameInstanceId() == requestedGameInstanceId; + if (!sameRuntimeTarget) { return; } meterRegistry.counter(RESUME_DENIED_METRIC, "reason", reason).increment(); @@ -1496,7 +1512,7 @@ && sameSlug(context.worldSlug(), requestedWorldSlug) context.connectRequestId())); LOG.debug( "Cleared stale gameplay binding after denied reconnect-style PLAY for tenant {} session {} world {} realm {} reason {}", - tenantTag, + selectedTenantTag, context.sessionId(), requestedWorldSlug, requestedRealmSlug, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 6a0034f618..cb43acdf1b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -5,27 +5,18 @@ import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.OptionalLong; -import java.util.Set; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; -import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; -import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; -import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.springframework.beans.factory.annotation.Autowired; @@ -40,7 +31,6 @@ @Component public class WorldsCommandHandler { private final GameplayWorldCatalog worldCatalog; - private final EntityManagementClient entityManagementClient; private final AccountClient accountClient; private final DirectTextConnectScopeSessionStore connectScopeSessionStore; private final Clock clock; @@ -48,26 +38,17 @@ public class WorldsCommandHandler { @Autowired public WorldsCommandHandler( GameplayWorldCatalog worldCatalog, - EntityManagementClient entityManagementClient, AccountClient accountClient, DirectTextConnectScopeSessionStore connectScopeSessionStore) { - this( - worldCatalog, - entityManagementClient, - accountClient, - connectScopeSessionStore, - Clock.systemUTC()); + this(worldCatalog, accountClient, connectScopeSessionStore, Clock.systemUTC()); } WorldsCommandHandler( GameplayWorldCatalog worldCatalog, - EntityManagementClient entityManagementClient, AccountClient accountClient, DirectTextConnectScopeSessionStore connectScopeSessionStore, Clock clock) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); - this.entityManagementClient = - Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); this.connectScopeSessionStore = Objects.requireNonNull( @@ -75,16 +56,6 @@ public WorldsCommandHandler( this.clock = Objects.requireNonNull(clock, "clock must not be null"); } - WorldsCommandHandler( - GameplayWorldCatalog worldCatalog, EntityManagementClient entityManagementClient) { - this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); - this.entityManagementClient = - Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); - this.accountClient = null; - this.connectScopeSessionStore = null; - this.clock = Clock.systemUTC(); - } - public WorldsViewOutput browseView() { return worldCatalog.browseView(); } @@ -332,16 +303,16 @@ private RealmSelectorResolution resolveLobbyRealm( if (resolution instanceof DirectTextOrdinalSelectionResolver.Unavailable) { return new RealmSelectorResolution.Unavailable(); } - return resolution instanceof DirectTextOrdinalSelectionResolver.UnboundSelector - ? new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR) - : new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + if (resolution instanceof DirectTextOrdinalSelectionResolver.PointerUnavailable) { + return new RealmSelectorResolution.PointerUnavailable(); + } + return new RealmSelectorResolution.Stale(); } private RealmSelectorResolution resolveOmittedLobbyRealm( SessionContext caller, GameplayWorldCatalog.DiscoverySnapshot currentWorldCatalog, - GameplayWorldCatalog.WorldView world, - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog) { + GameplayWorldCatalog.WorldView world) { if (connectScopeSessionStore == null) { return new RealmSelectorResolution.Unavailable(); } @@ -359,23 +330,31 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( } if (maybeSnapshot.isPresent()) { DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); + RealmSnapshotRevalidation revalidation = revalidateRealmSnapshot(world, snapshot); + if (revalidation instanceof RealmSnapshotRevalidation.Unavailable) { + return new RealmSelectorResolution.Unavailable(); + } + if (revalidation instanceof RealmSnapshotRevalidation.Stale) { + return new RealmSelectorResolution.Stale(); + } if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) - || snapshot.tenantId() != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world) - || !snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + || snapshot.tenantId() + != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world)) { + return new RealmSelectorResolution.Stale(); } + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = + ((RealmSnapshotRevalidation.Current) revalidation).snapshot(); if (snapshot.ordinalTargets().size() > 1) { return new RealmSelectorResolution.RequiresSelection(); } if (snapshot.ordinalTargets().isEmpty()) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + return new RealmSelectorResolution.Stale(); } return worldCatalog .resolveRealmSnapshotOrdinal( world, currentRealmCatalog, snapshot.ordinalTargets().getFirst()) .map(RealmSelectorResolution.Selected::new) - .orElseGet( - () -> new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH)); + .orElseGet(RealmSelectorResolution.Stale::new); } // Without a caller-specific REALMS snapshot, only the canonical public default is a safe @@ -396,7 +375,6 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( private boolean isBoundToCurrentRealmSnapshot( SessionContext caller, GameplayWorldCatalog.WorldView world, - GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog, GameplayWorldCatalog.RealmView realm) { if (connectScopeSessionStore == null) { return false; @@ -418,10 +396,15 @@ private boolean isBoundToCurrentRealmSnapshot( } DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) - || snapshot.tenantId() != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world) - || !snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + || snapshot.tenantId() + != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world)) { + return false; + } + RealmSnapshotRevalidation revalidation = revalidateRealmSnapshot(world, snapshot); + if (!(revalidation instanceof RealmSnapshotRevalidation.Current current)) { return false; } + GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog = current.snapshot(); return snapshot.ordinalTargets().stream() .filter(target -> target.tenantId() == realm.tenantId()) .filter(target -> target.realmSlug().equalsIgnoreCase(realm.slug())) @@ -433,9 +416,32 @@ private boolean isBoundToCurrentRealmSnapshot( .isPresent()); } - private enum RealmSelectorStaleReason { - UNBOUND_SELECTOR, - SNAPSHOT_MISMATCH + private RealmSnapshotRevalidation revalidateRealmSnapshot( + GameplayWorldCatalog.WorldView world, + DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot) { + Optional maybeCurrentCatalog; + try { + maybeCurrentCatalog = + worldCatalog.revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return new RealmSnapshotRevalidation.Unavailable(); + } + if (maybeCurrentCatalog.isEmpty() + || !snapshot + .catalogFingerprint() + .equals(maybeCurrentCatalog.orElseThrow().catalogFingerprint())) { + return new RealmSnapshotRevalidation.Stale(); + } + return new RealmSnapshotRevalidation.Current(maybeCurrentCatalog.orElseThrow()); + } + + private sealed interface RealmSnapshotRevalidation { + record Current(GameplayWorldCatalog.RealmDiscoverySnapshot snapshot) + implements RealmSnapshotRevalidation {} + + record Stale() implements RealmSnapshotRevalidation {} + + record Unavailable() implements RealmSnapshotRevalidation {} } private sealed interface RealmSelectorResolution @@ -444,7 +450,8 @@ private sealed interface RealmSelectorResolution RealmSelectorResolution.Invalid, RealmSelectorResolution.RequiresSelection, RealmSelectorResolution.Stale, - RealmSelectorResolution.Unavailable { + RealmSelectorResolution.Unavailable, + RealmSelectorResolution.PointerUnavailable { record Selected(GameplayWorldCatalog.RealmView realm) implements RealmSelectorResolution {} record NoSelection() implements RealmSelectorResolution {} @@ -453,9 +460,11 @@ record Invalid() implements RealmSelectorResolution {} record RequiresSelection() implements RealmSelectorResolution {} - record Stale(RealmSelectorStaleReason reason) implements RealmSelectorResolution {} + record Stale() implements RealmSelectorResolution {} record Unavailable() implements RealmSelectorResolution {} + + record PointerUnavailable() implements RealmSelectorResolution {} } private sealed interface WorldSelectorResolution { @@ -503,22 +512,23 @@ public JoinMembershipResult joinPublicProductionMembership( } WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); - if (selection instanceof WorldSelectorResolution.Invalid - || selection instanceof WorldSelectorResolution.Stale) { + if (selection instanceof WorldSelectorResolution.Invalid) { + try { + worldCatalog.resolvePublicWorldFromAuthoritySnapshot(worldSelector); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + if (selection instanceof WorldSelectorResolution.Stale) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } if (selection instanceof WorldSelectorResolution.Unavailable) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; - try { - currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { - return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); - } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { - return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); - } Optional maybeRealmSnapshot; try { maybeRealmSnapshot = @@ -532,14 +542,19 @@ public JoinMembershipResult joinPublicProductionMembership( return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } if (maybeRealmSnapshot.isEmpty() - || !maybeRealmSnapshot - .orElseThrow() - .catalogFingerprint() - .equals(currentRealmCatalog.catalogFingerprint()) || !normalizeSelector(worldSelector) .equals(maybeRealmSnapshot.orElseThrow().requestedWorldSelector())) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } + DirectTextConnectScopeSessionStore.RealmsSnapshot realmSnapshot = + maybeRealmSnapshot.orElseThrow(); + RealmSnapshotRevalidation revalidation = revalidateRealmSnapshot(world, realmSnapshot); + if (revalidation instanceof RealmSnapshotRevalidation.Unavailable) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + if (revalidation instanceof RealmSnapshotRevalidation.Stale) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } Optional maybeJoinScope; try { maybeJoinScope = @@ -703,7 +718,6 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot; - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; try { catalogSnapshot = worldCatalog.readDiscoverySnapshot(); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { @@ -714,6 +728,13 @@ public CharacterBrowseResult browseCharacters( WorldSelectorResolution selection = resolveLobbyWorld(sessionContext, worldSelector, catalogSnapshot); if (selection instanceof WorldSelectorResolution.Invalid) { + try { + worldCatalog.resolvePublicWorldFromAuthoritySnapshot(worldSelector); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } return CharacterBrowseResult.invalidWorld(); } if (selection instanceof WorldSelectorResolution.Stale) { @@ -723,6 +744,11 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); + // Redact private-only targets before CHARS can reveal realm-selection hints. + if (!worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { + return CharacterBrowseResult.invalidWorld(); + } + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; try { currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { @@ -733,17 +759,15 @@ public CharacterBrowseResult browseCharacters( RealmSelectorResolution realmSelection = resolveLobbyRealm(sessionContext, world, realmSelector, currentRealmCatalog); if (realmSelection instanceof RealmSelectorResolution.NoSelection) { - realmSelection = - resolveOmittedLobbyRealm(sessionContext, catalogSnapshot, world, currentRealmCatalog); + realmSelection = resolveOmittedLobbyRealm(sessionContext, catalogSnapshot, world); } if (realmSelection instanceof RealmSelectorResolution.Unavailable) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); } - if (realmSelection instanceof RealmSelectorResolution.Stale stale) { - if (stale.reason() == RealmSelectorStaleReason.UNBOUND_SELECTOR - && !worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { - return CharacterBrowseResult.invalidWorld(); - } + if (realmSelection instanceof RealmSelectorResolution.PointerUnavailable) { + return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); + } + if (realmSelection instanceof RealmSelectorResolution.Stale) { return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } if (realmSelection instanceof RealmSelectorResolution.RequiresSelection) { @@ -751,7 +775,6 @@ public CharacterBrowseResult browseCharacters( } if (realmSelection instanceof RealmSelectorResolution.Invalid) { return StringUtils.hasText(realmSelector) - && worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) ? CharacterBrowseResult.invalidRealm(world.slug()) : CharacterBrowseResult.invalidWorld(); } @@ -759,16 +782,14 @@ public CharacterBrowseResult browseCharacters( GameplayWorldCatalog.RealmView realm = ((RealmSelectorResolution.Selected) realmSelection).realm(); if (!realm.publicProductionRealm() - && !isBoundToCurrentRealmSnapshot(sessionContext, world, currentRealmCatalog, realm)) { - // An unbound private slug must project exactly like an unknown realm. A fresh caller-bound - // snapshot may establish that the caller already knows this target, but it is not grant - // authority for the target. - return worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) - ? CharacterBrowseResult.invalidRealm(world.slug()) - : CharacterBrowseResult.invalidWorld(); + && !isBoundToCurrentRealmSnapshot(sessionContext, world, realm)) { + // A fresh caller-bound snapshot establishes knowledge of the target, not grant authority. + return CharacterBrowseResult.invalidRealm(world.slug()); } boolean currentPointerMatches; try { + // A failed authority read is AUTH_UNAVAILABLE; a reachable invalid/stale pointer + // snapshot is classified below as ADMISSION_POINTER_UNAVAILABLE. currentPointerMatches = worldCatalog.matchesCurrentAdmissionPointer(world, realm); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); @@ -778,147 +799,12 @@ public CharacterBrowseResult browseCharacters( || !currentPointerMatches) { return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - if (!realm.publicProductionRealm()) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); } - - String requestId = sessionContext.sessionId() + ":" + UUID.randomUUID(); - CharacterBrowseAuthorization authorization = - authorizePublicCharacterBrowse(sessionContext, realm, requestId); - if (authorization != CharacterBrowseAuthorization.AUTHORIZED) { - return CharacterBrowseResult.failure(authorization.code()); - } - - ListCharactersByAccountResponse response = - entityManagementClient.listCharactersByAccount( - Long.toString(realm.tenantId()), - Long.toString(sessionContext.accountId()), - Long.toString(realm.gameInstanceId()), - toPlayableStateScope(realm)); - if (response.hasError()) { - return CharacterBrowseResult.unavailable(); - } - java.util.List entries = - new java.util.ArrayList<>(response.getCharactersCount()); - Set characterIds = new HashSet<>(); - for (int i = 0; i < response.getCharactersCount(); i++) { - net.firedevops.firemud.entitymanagement.v1.Character character = response.getCharacters(i); - PositiveLongParsing.ParsedPositiveLong parsedCharacterId = - PositiveLongParsing.parseOptionalText(character.getId(), "characterId"); - if (!Long.toString(realm.tenantId()).equals(character.getTenantId()) - || !Long.toString(sessionContext.accountId()).equals(character.getAccountId()) - || character.getPlayableStateScope() != toPlayableStateScope(realm) - || !parsedCharacterId.valid() - || !StringUtils.hasText(character.getName()) - || !characterIds.add(parsedCharacterId.value())) { - return CharacterBrowseResult.unavailable(); - } - entries.add( - new CharacterBrowseViewOutput.CharacterEntry( - i + 1, character.getId(), character.getName(), character.getLevel())); - } - return CharacterBrowseResult.success( - new CharacterBrowseViewOutput( - world.slug(), - realm.slug(), - realm.stateScope(), - realm.characterCreationPolicy(), - entries)); - } - - private CharacterBrowseAuthorization authorizePublicCharacterBrowse( - SessionContext sessionContext, GameplayWorldCatalog.RealmView realm, String requestId) { - if (accountClient == null) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - GetTenantMembershipForRuntimeResponse membershipResponse = - accountClient.getTenantMembershipForRuntime( - Long.toString(sessionContext.accountId()), Long.toString(realm.tenantId()), requestId); - if (membershipResponse == null) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - if (membershipResponse.hasError()) { - String errorCode = membershipResponse.getError().getCode(); - if (!StringUtils.hasText(errorCode)) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - return isAuthorityUnavailable(errorCode) - ? CharacterBrowseAuthorization.AUTH_UNAVAILABLE - : CharacterBrowseAuthorization.DENIED; - } - if (!isValidMembershipAuthoritySnapshot(membershipResponse, sessionContext, realm)) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - - PublicEntitlementAuthorization entitlementAuthorization = - authorizePublicCharacterEntitlement(realm, requestId); - if (entitlementAuthorization.authorization() != CharacterBrowseAuthorization.AUTHORIZED) { - return entitlementAuthorization.authorization(); - } - if (!membershipResponse.getMembershipExists() - || "INACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { - return entitlementAuthorization.allowPublicJoin() - ? CharacterBrowseAuthorization.JOIN_REQUIRED - : CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; - } - if (!membershipResponse.getGameplayAdmissionAllowed()) { - return CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; - } - if (!AccountAuthorityEvidence.isActiveMembership( - membershipResponse, sessionContext.accountId(), realm.tenantId(), clock)) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - return CharacterBrowseAuthorization.AUTHORIZED; - } - - private PublicEntitlementAuthorization authorizePublicCharacterEntitlement( - GameplayWorldCatalog.RealmView realm, String requestId) { - if (accountClient == null) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); - } - GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime(Long.toString(realm.tenantId()), requestId); - if (entitlementResponse == null) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); - } - if (entitlementResponse.hasError()) { - String errorCode = entitlementResponse.getError().getCode(); - if (!StringUtils.hasText(errorCode)) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); - } - if (GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE.equalsIgnoreCase(errorCode)) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE, false); - } - return new PublicEntitlementAuthorization( - isAuthorityUnavailable(errorCode) - ? CharacterBrowseAuthorization.AUTH_UNAVAILABLE - : CharacterBrowseAuthorization.DENIED, - false); - } - if (!AccountAuthorityEvidence.isValidEntitlement( - entitlementResponse, realm.tenantId(), clock)) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE, false); - } - if (!entitlementResponse.getGameplayAvailable()) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.TENANT_BILLING_BLOCKED, false); - } - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTHORIZED, entitlementResponse.getAllowPublicJoin()); - } - - private boolean isValidMembershipAuthoritySnapshot( - GetTenantMembershipForRuntimeResponse response, - SessionContext sessionContext, - GameplayWorldCatalog.RealmView realm) { - return AccountAuthorityEvidence.isSafeMembershipSnapshot( - response, sessionContext.accountId(), realm.tenantId(), clock); + // The current Entity roster API is not qualified by the stable playable-state namespace. + // Keep CHARS closed until that actor-identity contract is available. + return CharacterBrowseResult.unavailable(); } private boolean hasCompleteSelectedRealmPointerEvidence(GameplayWorldCatalog.RealmView realm) { @@ -933,40 +819,12 @@ private boolean hasCompleteSelectedRealmPointerEvidence(GameplayWorldCatalog.Rea && StringUtils.hasText(realm.slug()); } - private enum CharacterBrowseAuthorization { - AUTHORIZED(null), - JOIN_REQUIRED("JOIN_REQUIRED"), - DENIED("WORLD_ACCESS_DENIED"), - PUBLIC_PRODUCTION_ADMISSION_DENIED("PUBLIC_PRODUCTION_ADMISSION_DENIED"), - TENANT_BILLING_BLOCKED("TENANT_BILLING_BLOCKED"), - AUTH_UNAVAILABLE("AUTH_UNAVAILABLE"), - ENTITLEMENT_UNAVAILABLE("ENTITLEMENT_UNAVAILABLE"); - - private final String code; - - CharacterBrowseAuthorization(String code) { - this.code = code; - } - - private String code() { - return code; - } - } - - private record PublicEntitlementAuthorization( - CharacterBrowseAuthorization authorization, boolean allowPublicJoin) {} - public sealed interface CharacterBrowseResult - permits CharacterBrowseResult.Success, - CharacterBrowseResult.InvalidWorld, + permits CharacterBrowseResult.InvalidWorld, CharacterBrowseResult.InvalidRealm, CharacterBrowseResult.RealmSelectionRequired, CharacterBrowseResult.Unavailable, CharacterBrowseResult.Failure { - static CharacterBrowseResult success(CharacterBrowseViewOutput output) { - return new Success(output); - } - static CharacterBrowseResult invalidWorld() { return new InvalidWorld(); } @@ -987,8 +845,6 @@ static CharacterBrowseResult failure(String code) { return new Failure(code); } - record Success(CharacterBrowseViewOutput output) implements CharacterBrowseResult {} - record InvalidWorld() implements CharacterBrowseResult {} record InvalidRealm(String worldSlug) implements CharacterBrowseResult {} @@ -999,16 +855,4 @@ record Unavailable() implements CharacterBrowseResult {} record Failure(String code) implements CharacterBrowseResult {} } - - private PlayableStateScope toPlayableStateScope(GameplayWorldCatalog.RealmView realm) { - String scope = - realm.stateScope() == null - ? "" - : realm.stateScope().trim().toUpperCase(java.util.Locale.ROOT); - return switch (scope) { - case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; - default -> PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED; - }; - } } 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 fb8d941f35..cc05787056 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 @@ -211,12 +211,6 @@ private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest r request.sessionContext().orElseThrow(), payload.worldSelector(), payload.realmSelector())) { - case WorldsCommandHandler.CharacterBrowseResult.Success success -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( - success.output()))); case WorldsCommandHandler.CharacterBrowseResult.InvalidWorld ignored -> errorResult( "INVALID_ARGUMENT", "CHARS requires a valid world selector. Use WORLDS first."); @@ -234,8 +228,7 @@ private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest r case WorldsCommandHandler.CharacterBrowseResult.Failure failure -> errorResult(failure.code(), characterBrowseFailureMessage(failure.code())); case WorldsCommandHandler.CharacterBrowseResult.Unavailable ignored -> - errorResult( - "CHARACTER_LIST_UNAVAILABLE", "Character list unavailable. Retry CHARS shortly."); + errorResult("CHARACTER_LIST_UNAVAILABLE", "Character browsing is currently unavailable."); }; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java index 52beec5126..ed2a67c117 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -55,7 +55,8 @@ public ProbeResult probeSessionContextStore() { sessionContextService .findByTenantAndSessionId(PROBE_TENANT_ID, probeSessionId) .orElseThrow(() -> new IllegalStateException("session context was not persisted")); - if (!stored.equals(context)) { + // Redis deliberately persists the no-secret projection, not the probe JWT. + if (!stored.equals(context.withoutJwt())) { return ProbeResult.down("stored session context did not round-trip"); } return ProbeResult.up("ROUND_TRIP_OK"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index d32a473932..01cf34ef35 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -281,6 +281,30 @@ public boolean hasGameplayIdentity() { return gameInstanceId > 0 && characterId > 0; } + public SessionContext withoutJwt() { + if (jwt == null) { + return this; + } + return new SessionContext( + sessionId, + tenantId, + accountId, + loginName, + characterId, + characterName, + gameInstanceId, + roomInstanceId, + null, + localeTag, + bootstrapGameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + playableStateScope, + connectScopeId, + connectRequestId); + } + public boolean hasGameplayBinding() { return gameInstanceId > 0 || characterId > 0 diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java index 8d1ff2ac5f..c7ac3323f6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java @@ -62,13 +62,16 @@ public void clearGameplayBinding(SessionContext context, String clearReason) { @Override public void recordDisconnected(long sessionId, AccountRecentPresenceDisposition disposition) { - sessionRoutingNormalizationService - .resolveProjectedSessionContext(Long.toString(sessionId)) - .filter(SessionContext::hasGameplayRegionBindingOrFalse) - .ifPresent( - context -> - scriptEventPublisher.publishRegionExitEvent( - context, disconnectEventId(context, disposition), disposition.name())); + // A controller takeover displaces a socket, not the character from its current region. + if (disposition != AccountRecentPresenceDisposition.TAKEOVER) { + sessionRoutingNormalizationService + .resolveProjectedSessionContext(Long.toString(sessionId)) + .filter(SessionContext::hasGameplayRegionBindingOrFalse) + .ifPresent( + context -> + scriptEventPublisher.publishRegionExitEvent( + context, disconnectEventId(context, disposition), disposition.name())); + } accountRecentPresenceService.recordDisconnect(sessionId, disposition); gameplayPresenceService.removeBySessionId(sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index d415a8532e..f8048ae033 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -5,6 +5,7 @@ import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; import java.util.List; +import java.util.Objects; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; @@ -21,6 +22,7 @@ import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; import net.firedevops.firemud.gamesession.service.SessionIdParsing; @@ -58,6 +60,7 @@ import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.jooq.exception.DataAccessException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -523,7 +526,9 @@ public void listGameplayWorlds( ListGameplayWorldsResponse response = ListGameplayWorldsResponse.newBuilder() .addAllWorlds( - gameplayWorldCatalog.publicWorldsFromAuthoritySnapshot().stream() + gameplayWorldCatalog + .publicWorldsFromAuthoritySnapshot(readGameplayAdmissionPointerSnapshots()) + .stream() .map( world -> net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() @@ -534,6 +539,13 @@ public void listGameplayWorlds( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + ListGameplayWorldsResponse response = + ListGameplayWorldsResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, "AUTH_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { ListGameplayWorldsResponse response = ListGameplayWorldsResponse.newBuilder() @@ -562,16 +574,24 @@ public void listGameplayRealms( String worldSelector = requireWorldSelector(request.getWorldSlug()); WorldView world = gameplayWorldCatalog - .resolvePublicWorldFromAuthoritySnapshot(worldSelector) + .resolvePublicWorldFromAuthoritySnapshot( + worldSelector, readGameplayAdmissionPointerSnapshots()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); List realms = - gameplayWorldCatalog.visibleRealms(world).stream() + gameplayWorldCatalog.publicVisibleRealms(world).stream() .map(realm -> toGameplayRealm(world.slug(), realm)) .toList(); ListGameplayRealmsResponse response = ListGameplayRealmsResponse.newBuilder().addAllRealms(realms).build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + ListGameplayRealmsResponse response = + ListGameplayRealmsResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, "AUTH_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (AuthorityProjectionUnavailableException | GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { ListGameplayRealmsResponse response = @@ -607,15 +627,42 @@ public void getAdmissionPointer( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); - GameplayAdmissionPointerSnapshot realm = - gameplayAdmissionPointerAuthorityService - .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) - .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); + List pointerSnapshot = + readGameplayAdmissionPointerSnapshots(tenantId); + if (pointerSnapshot.stream() + .anyMatch(pointer -> pointer == null || pointer.tenantId() != tenantId)) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay pointer snapshot escaped the requested tenant scope"); + } + gameplayWorldCatalog.requireHealthyPointerCatalog(pointerSnapshot, tenantId); + List selectedRealms = + pointerSnapshot.stream() + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(pointer -> Objects.equals(pointer.worldSlug(), request.getWorldSlug())) + .filter(pointer -> Objects.equals(pointer.realmSlug(), request.getRealmSlug())) + .toList(); + if (selectedRealms.isEmpty()) { + throw new IllegalArgumentException("Unknown gameplay realm selection"); + } + if (selectedRealms.size() > 1) { + throw new CatalogRevisionUnavailableException( + "Multiple current gameplay realms match the requested tenant and selector"); + } + GameplayAdmissionPointerSnapshot realm = selectedRealms.getFirst(); + if (!GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(realm) + || realm.catalogRevision() <= 0L + || realm.realmId() == null + || realm.playableStateNamespaceId() == null + || realm.characterCreationPolicy() == null + || realm.characterCreationPolicy().isBlank()) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay pointer identity is missing or invalid"); + } if (realm.visible()) { if (realm.publicProductionRealm()) { - gameplayWorldCatalog.requireUniqueVisiblePublicProductionRealm(realm); + gameplayWorldCatalog.requireUniqueVisiblePublicProductionRealm(realm, pointerSnapshot); } else { - gameplayWorldCatalog.requireHealthyVisiblePrivateRealm(realm); + gameplayWorldCatalog.requireHealthyVisiblePrivateRealm(realm, pointerSnapshot); } } GetAdmissionPointerResponse response = @@ -643,6 +690,22 @@ public void getAdmissionPointer( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, "AUTH_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (CatalogRevisionUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (AuthorityProjectionUnavailableException | GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { GetAdmissionPointerResponse response = @@ -670,6 +733,37 @@ public void getAdmissionPointer( } } + private List readGameplayAdmissionPointerSnapshots() { + try { + List pointerSnapshots = + gameplayAdmissionPointerAuthorityService.listPointers(); + if (pointerSnapshots == null) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + return pointerSnapshots; + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable", ex); + } + } + + private List readGameplayAdmissionPointerSnapshots( + long tenantId) { + try { + List pointerSnapshots = + gameplayAdmissionPointerAuthorityService.listPointersByTenant(tenantId); + if (pointerSnapshots == null) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative tenant gameplay pointer list is unavailable"); + } + return pointerSnapshots; + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative tenant gameplay pointer list is unavailable", ex); + } + } + @Override @Timed(value = "gamesessionGrpc.toggleFeatureFlag") public void toggleFeatureFlag( @@ -869,6 +963,12 @@ private static long requireCatalogRevision(long catalogRevision) { return catalogRevision; } + private static final class CatalogRevisionUnavailableException extends RuntimeException { + private CatalogRevisionUnavailableException(String message) { + super(message); + } + } + private static final class AuthorityProjectionUnavailableException extends RuntimeException { private AuthorityProjectionUnavailableException(String message) { super(message); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java index e5fe41710a..309769ec1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java @@ -1,39 +1,16 @@ package net.firedevops.firemud.gamesession.service.impl; -import io.jsonwebtoken.JwtException; -import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.common.security.SessionClaims; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; -import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; -import org.springframework.util.StringUtils; final class GameplayPresenceRoleClassifier { private GameplayPresenceRoleClassifier() {} - static GameplayPresenceRole classifyRole(SessionContext context, JwtUtil jwtUtil, Logger logger) { - if (!StringUtils.hasText(context.jwt())) { - return GameplayPresenceRole.PLAYER; - } - try { - SessionClaims claims = SessionClaims.fromJwt(jwtUtil.parseToken(context.jwt())); - String tenantId = Long.toString(context.tenantId()); - if (claims.hasGameplayRole(tenantId, "god")) { - return GameplayPresenceRole.GOD; - } - if (claims.hasGameplayRole(tenantId, "platformAdmin", "tenantAdmin")) { - return GameplayPresenceRole.ADMIN; - } - if (claims.hasGameplayRole(tenantId, "moderator")) { - return GameplayPresenceRole.MODERATOR; - } - } catch (IllegalArgumentException | JwtException ex) { - logger.debug( - "Failed to classify WHO role from JWT for session {} tenant {}", - context.sessionId(), - context.tenantId(), - ex); - } + /** + * Current session context carries no fresh Account-authenticated gameplay-grant evidence. JWT + * roles, including tenant-scoped administrative roles, are not a grant carrier and cannot + * preserve gameplay elevation across reconnects. + */ + static GameplayPresenceRole classifyRole() { return GameplayPresenceRole.PLAYER; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index 47dcad6f62..a577c3af0f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -11,14 +11,11 @@ import java.util.Optional; import java.util.Set; import java.util.function.LongSupplier; -import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; @@ -30,7 +27,6 @@ /** Redis-backed gameplay presence store for the first WHO implementation. */ @Service public final class RedisGameplayPresenceService implements GameplayPresenceService { - private static final Logger logger = LoggingUtil.getLogger(RedisGameplayPresenceService.class); private static final String PRESENCE_KEY_TEMPLATE = "gameplaypresence:session:%d"; private static final String GAME_INSTANCE_SET_TEMPLATE = "gameplaypresence:%d:%d:sessions"; private static final String ACCOUNT_SET_TEMPLATE = "gameplaypresence:%d:account:%d:sessions"; @@ -46,24 +42,20 @@ public final class RedisGameplayPresenceService implements GameplayPresenceServi private final RedisTemplate redisTemplate; private final Duration presenceTtl; - private final JwtUtil jwtUtil; private final LongSupplier currentTimeMillisSupplier; @Autowired public RedisGameplayPresenceService( RedisTemplate redisTemplate, - JwtUtil jwtUtil, @Value("${FIREMUD_AUTH_SESSION_EXPIRATION_MS:3600000}") long sessionExpirationMs) { - this(redisTemplate, jwtUtil, sessionExpirationMs, System::currentTimeMillis); + this(redisTemplate, sessionExpirationMs, System::currentTimeMillis); } RedisGameplayPresenceService( RedisTemplate redisTemplate, - JwtUtil jwtUtil, long sessionExpirationMs, LongSupplier currentTimeMillisSupplier) { this.redisTemplate = redisTemplate; - this.jwtUtil = jwtUtil; this.presenceTtl = Duration.ofMillis(sessionExpirationMs); this.currentTimeMillisSupplier = currentTimeMillisSupplier; } @@ -91,7 +83,7 @@ public void registerConnected(SessionContext context) { StringUtils.hasText(context.characterName()) ? context.characterName().trim() : fallbackCharacterName(context), - classifyRole(context), + GameplayPresenceRoleClassifier.classifyRole(), currentTimeMillisSupplier.getAsLong(), null, null, @@ -127,27 +119,28 @@ public void setExplicitAfk(long sessionId, boolean explicitAfk) { if (existing == null) { return; } + GameplayPresence current = playerPresence(existing); GameplayPresence updated = new GameplayPresence( - existing.sessionId(), - existing.tenantId(), - existing.gameInstanceId(), - existing.playableStateScope(), - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion(), - existing.accountId(), - existing.characterId(), - existing.characterName(), - existing.role(), - existing.connectedAtEpochMs(), + current.sessionId(), + current.tenantId(), + current.gameInstanceId(), + current.playableStateScope(), + current.worldSlug(), + current.realmSlug(), + current.pointerVersion(), + current.accountId(), + current.characterId(), + current.characterName(), + GameplayPresenceRole.PLAYER, + current.connectedAtEpochMs(), explicitAfk ? Long.valueOf(currentTimeMillisSupplier.getAsLong()) : null, - existing.lastAcceptedCommandAtEpochMs(), - existing.lastMeaningfulActivityAtEpochMs()); + current.lastAcceptedCommandAtEpochMs(), + current.lastMeaningfulActivityAtEpochMs()); valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( - gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + gameInstanceKey(current.tenantId(), current.gameInstanceId()), presenceTtl); + redisTemplate.expire(accountKey(current.tenantId(), current.accountId()), presenceTtl); } @Override @@ -158,29 +151,30 @@ public void recordCommandActivity(long sessionId, boolean meaningfulGameplayActi return; } long now = currentTimeMillisSupplier.getAsLong(); + GameplayPresence current = playerPresence(existing); GameplayPresence updated = new GameplayPresence( - existing.sessionId(), - existing.tenantId(), - existing.gameInstanceId(), - existing.playableStateScope(), - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion(), - existing.accountId(), - existing.characterId(), - existing.characterName(), - existing.role(), - existing.connectedAtEpochMs(), - existing.explicitAfkSinceEpochMs(), + current.sessionId(), + current.tenantId(), + current.gameInstanceId(), + current.playableStateScope(), + current.worldSlug(), + current.realmSlug(), + current.pointerVersion(), + current.accountId(), + current.characterId(), + current.characterName(), + GameplayPresenceRole.PLAYER, + current.connectedAtEpochMs(), + current.explicitAfkSinceEpochMs(), Long.valueOf(now), meaningfulGameplayActivity ? Long.valueOf(now) - : existing.lastMeaningfulActivityAtEpochMs()); + : current.lastMeaningfulActivityAtEpochMs()); valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( - gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + gameInstanceKey(current.tenantId(), current.gameInstanceId()), presenceTtl); + redisTemplate.expire(accountKey(current.tenantId(), current.accountId()), presenceTtl); } @Override @@ -207,7 +201,7 @@ public List listConnectedByGameInstance(long tenantId, long ga continue; } if (presence.tenantId() == tenantId && presence.gameInstanceId() == gameInstanceId) { - matches.add(presence); + matches.add(playerPresence(presence)); } } @@ -256,7 +250,7 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } - accountMatches.add(presence); + accountMatches.add(playerPresence(presence)); } if (!accountMatches.isEmpty()) { accountMatches.sort(ACCOUNT_PRESENCE_PREFERENCE.reversed()); @@ -269,7 +263,30 @@ public Map> listConnectedByAccountIds( @Override public Optional findConnectedBySessionId(long sessionId) { ValueOperations valueOps = redisTemplate.opsForValue(); - return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))); + return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))) + .map(RedisGameplayPresenceService::playerPresence); + } + + private static GameplayPresence playerPresence(GameplayPresence presence) { + if (presence.role() == GameplayPresenceRole.PLAYER) { + return presence; + } + return new GameplayPresence( + presence.sessionId(), + presence.tenantId(), + presence.gameInstanceId(), + presence.playableStateScope(), + presence.worldSlug(), + presence.realmSlug(), + presence.pointerVersion(), + presence.accountId(), + presence.characterId(), + presence.characterName(), + GameplayPresenceRole.PLAYER, + presence.connectedAtEpochMs(), + presence.explicitAfkSinceEpochMs(), + presence.lastAcceptedCommandAtEpochMs(), + presence.lastMeaningfulActivityAtEpochMs()); } private String presenceKey(long sessionId) { @@ -293,10 +310,6 @@ private String accountKey(long tenantId, long accountId) { return String.format(ACCOUNT_SET_TEMPLATE, tenantId, accountId); } - private GameplayPresenceRole classifyRole(SessionContext context) { - return GameplayPresenceRoleClassifier.classifyRole(context, jwtUtil, logger); - } - private String fallbackCharacterName(SessionContext context) { if (StringUtils.hasText(context.loginName())) { return context.loginName().trim(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java index 96178b1c8e..dbf9224517 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java @@ -116,7 +116,7 @@ private SessionContext updateRoom(SessionContext current, String destinationRoom current.characterName(), current.gameInstanceId(), destinationRoomInstanceId, - current.jwt(), + null, current.localeTag(), current.bootstrapGameInstanceId(), current.worldSlug(), @@ -141,7 +141,8 @@ private String normalizeRoom(String roomId) { private SessionContext readContext( org.springframework.data.redis.core.RedisOperations operations, String key) { - return (SessionContext) operations.opsForValue().get(key); + SessionContext context = (SessionContext) operations.opsForValue().get(key); + return context == null ? null : context.withoutJwt(); } private void addWatchKeys(LinkedHashSet watchKeys, SessionContext context) { @@ -185,23 +186,32 @@ private void deleteIndexes( private void writeContext( org.springframework.data.redis.core.RedisOperations operations, SessionContext context) { + SessionContext persistedContext = context.withoutJwt(); var ops = operations.opsForValue(); ops.set( - SessionContextRedisKeys.contextKey(context.tenantId(), context.sessionId()), - context, + SessionContextRedisKeys.contextKey( + persistedContext.tenantId(), persistedContext.sessionId()), + persistedContext, sessionTtl); - ops.set(SessionContextRedisKeys.sessionKey(context.sessionId()), context, sessionTtl); - if (context.hasGameplayIdentity()) { + ops.set( + SessionContextRedisKeys.sessionKey(persistedContext.sessionId()), + persistedContext, + sessionTtl); + if (persistedContext.hasGameplayIdentity()) { ops.set( SessionContextRedisKeys.identityKey( - context.tenantId(), context.gameInstanceId(), context.characterId()), - context, + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterId()), + persistedContext, sessionTtl); - if (hasGameplayName(context)) { + if (hasGameplayName(persistedContext)) { ops.set( SessionContextRedisKeys.nameKey( - context.tenantId(), context.gameInstanceId(), context.characterName()), - context, + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterName()), + persistedContext, sessionTtl); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index b7b8d502a8..ef48bccc22 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -34,6 +34,7 @@ public RedisSessionContextService( @Override public void save(SessionContext context) { + SessionContext persistedContext = context.withoutJwt(); for (int attempt = 0; attempt < MAX_SAVE_RETRIES; attempt++) { Boolean committed = redisTemplate.execute( @@ -41,30 +42,32 @@ public void save(SessionContext context) { @Override public Boolean execute( org.springframework.data.redis.core.RedisOperations operations) { - LinkedHashSet watchedKeys = new LinkedHashSet<>(watchKeys(context)); + LinkedHashSet watchedKeys = + new LinkedHashSet<>(watchKeys(persistedContext)); while (true) { operations.watch(watchedKeys); SessionContext existingContext = readContext( - operations, contextKey(context.tenantId(), context.sessionId())); + operations, + contextKey(persistedContext.tenantId(), persistedContext.sessionId())); SessionContext existingIdentityContext = - context.hasGameplayIdentity() + persistedContext.hasGameplayIdentity() ? readContext( operations, identityKey( - context.tenantId(), - context.gameInstanceId(), - context.characterId())) + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterId())) : null; SessionContext existingNameContext = - context.hasGameplayIdentity() - && StringUtils.hasText(context.characterName()) + persistedContext.hasGameplayIdentity() + && StringUtils.hasText(persistedContext.characterName()) ? readContext( operations, nameKey( - context.tenantId(), - context.gameInstanceId(), - context.characterName())) + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterName())) : null; LinkedHashSet additionalWatchKeys = new LinkedHashSet<>(); addWatchKeys(additionalWatchKeys, existingContext); @@ -80,7 +83,7 @@ public Boolean execute( deleteIndexes(operations, existingContext); deleteIndexes(operations, existingIdentityContext); deleteIndexes(operations, existingNameContext); - writeContext(operations, context); + writeContext(operations, persistedContext); return operations.exec() != null; } } @@ -94,22 +97,18 @@ public Boolean execute( @Override public Optional findBySessionId(long sessionId) { - return Optional.ofNullable( - (SessionContext) redisTemplate.opsForValue().get(sessionKey(sessionId))); + return readSessionContext(sessionKey(sessionId)); } @Override public Optional findByTenantAndSessionId(long tenantId, long sessionId) { - return Optional.ofNullable( - (SessionContext) redisTemplate.opsForValue().get(contextKey(tenantId, sessionId))); + return readSessionContext(contextKey(tenantId, sessionId)); } @Override public Optional findByGameplayIdentity( long tenantId, long gameInstanceId, long characterId) { - return Optional.ofNullable( - (SessionContext) - redisTemplate.opsForValue().get(identityKey(tenantId, gameInstanceId, characterId))); + return readSessionContext(identityKey(tenantId, gameInstanceId, characterId)); } @Override @@ -118,9 +117,7 @@ public Optional findByGameplayName( if (!StringUtils.hasText(characterName)) { return Optional.empty(); } - return Optional.ofNullable( - (SessionContext) - redisTemplate.opsForValue().get(nameKey(tenantId, gameInstanceId, characterName))); + return readSessionContext(nameKey(tenantId, gameInstanceId, characterName)); } @Override @@ -164,6 +161,11 @@ private String contextKey(long tenantId, long sessionId) { return SessionContextRedisKeys.contextKey(tenantId, sessionId); } + private Optional readSessionContext(String key) { + SessionContext context = (SessionContext) redisTemplate.opsForValue().get(key); + return Optional.ofNullable(context).map(SessionContext::withoutJwt); + } + private String sessionKey(long sessionId) { return SessionContextRedisKeys.sessionKey(sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java index 9354d34e66..fefba40fee 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java @@ -8,15 +8,10 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.gamesession.command.text.GameplayLoggingContext; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; -import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.DisconnectDeduplicationService; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PingService; -import net.firedevops.firemud.gamesession.service.SessionIdParsing; -import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectRequest; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectResponse; @@ -31,35 +26,28 @@ @GrpcService public final class TcpProxyServiceImpl extends TcpProxyServiceGrpc.TcpProxyServiceImplBase { private static final Logger logger = LoggingUtil.getLogger(TcpProxyServiceImpl.class); - private static final String SUSPENDED_STATUS = "SUSPENDED"; private static final String DUPLICATE_DISCONNECT_METRIC = "gamesession.notifydisconnect.duplicate"; private static final String MISSING_CONTEXT_METRIC = "gamesession.notifydisconnect.missing_context"; private final GameInstanceRepository repository; - private final SessionStateService sessionStateService; private final MeterRegistry meterRegistry; private final PingService pingService; private final DisconnectDeduplicationService disconnectDeduplicationService; - private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected repository/services are internal Spring collaborators") public TcpProxyServiceImpl( GameInstanceRepository repository, - SessionStateService sessionStateService, MeterRegistry meterRegistry, PingService pingService, - DisconnectDeduplicationService disconnectDeduplicationService, - GameplayPresenceLifecycleService gameplayPresenceLifecycleService) { + DisconnectDeduplicationService disconnectDeduplicationService) { this.repository = repository; - this.sessionStateService = sessionStateService; this.meterRegistry = meterRegistry; this.pingService = pingService; this.disconnectDeduplicationService = disconnectDeduplicationService; - this.gameplayPresenceLifecycleService = gameplayPresenceLifecycleService; } @Override @@ -102,55 +90,16 @@ private ErrorDetail handleNotifyDisconnect( } } - if (StringUtils.hasText(request.getSessionId())) { - SessionIdParsing.parse(request.getSessionId()) - .optionalValue() - .ifPresent( - sessionId -> - gameplayPresenceLifecycleService.recordDisconnected( - sessionId, AccountRecentPresenceDisposition.TRANSPORT_LOSS)); - } if (!StringUtils.hasText(gameInstanceIdText) || !StringUtils.hasText(request.getTenantId())) { meterRegistry.counter(MISSING_CONTEXT_METRIC).increment(); - return GrpcAppErrors.ok("Disconnect recorded (no proxy bootstrap metadata)"); + return GrpcAppErrors.ok("Disconnect hint accepted (no proxy bootstrap metadata)"); } SessionValidationResult validation = validateGameInstance(gameInstanceIdText, request.getTenantId()); if (validation.hasError()) { return validation.errorDetail(); } - GameInstance instance = validation.instance(); - GameInstanceDto suspendedState = - new GameInstanceDto( - instance.getId(), - instance.getTenantId(), - instance.getRuntimeVersion(), - instance.getScriptPatchVersion(), - instance.getScriptPatchBaseVersionId(), - instance.getScriptPinEpoch(), - instance.getScriptPatchPinnedControlPlaneRequestId(), - instance.getGameTemplateId(), - instance.getLaunchDescriptorId(), - instance.getVersionId(), - instance.getReleaseBundleId(), - instance.getVersionStateEpoch(), - instance.getGenerationConfigRevision(), - instance.getRemapSetId(), - instance.getOwnerAccountId(), - SUSPENDED_STATUS); - try { - sessionStateService.saveState(suspendedState); - return GrpcAppErrors.ok("Disconnect recorded"); - } catch (RuntimeException ex) { - logger.error( - "Failed to save suspended session state tenantId={} gameInstanceId={} proxyConnectionId={} disconnectSequence={}", - request.getTenantId(), - gameInstanceIdText, - request.getProxyConnectionId(), - request.getDisconnectSequence(), - ex); - return GrpcAppErrors.error(meterRegistry, "INTERNAL", "Failed to update session state"); - } + return GrpcAppErrors.ok("Disconnect hint accepted"); } private SessionValidationResult validateGameInstance( 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 a56d0f7104..489197bbfc 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 @@ -473,12 +473,11 @@ private void maybeRenderFreshReconnectLook( TextCommandInterpretationResult interpretation, Optional maybeContext) throws IOException { - boolean reconnectRestoreRequested = - interpretation.reconnectRedrawRecommended() - || StringUtils.hasText(resolveConnectContext(session)); + boolean reconnectRestoreRequested = interpretation.reconnectRedrawRecommended(); + boolean firstPartyPlay = "first_party_web".equals(resolveConnectionMode(session)); if (command.type() != TextCommandType.PLAY || !interpretation.commandResult().accepted() - || !reconnectRestoreRequested) { + || !reconnectRestoreRequested && !firstPartyPlay) { return; } maybeContext @@ -498,7 +497,8 @@ private void maybeRenderFreshReconnectLook( sendProjectedOutput( session, look, localeTag, effectivePresentation, "fresh LOOK"); } - if (effectivePresentation.prompt().emitAfterReconnectRestore()) { + if (effectivePresentation.prompt().enabled() + && effectivePresentation.prompt().emitAfterReconnectRestore()) { composePrompt(context) .ifPresent( prompt -> { diff --git a/services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql b/services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql new file mode 100644 index 0000000000..7ade62e22f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql @@ -0,0 +1,7 @@ +-- Admission-pointer rows are player-addressable realms. The partial index gives concurrent +-- producers an atomic at-most-one guard while excluding hidden and non-public realms. +-- Existing duplicates make index creation fail with PostgreSQL tenant-key evidence; no row is +-- rewritten or discarded. +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_visible_public_tenant + ON gameplay_admission_pointer (tenant_id) + WHERE visible AND public_production_realm; diff --git a/services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql b/services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql new file mode 100644 index 0000000000..be680b9d1b --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql @@ -0,0 +1,2 @@ +CREATE INDEX idx_gameplay_admission_pointer_event_tenant_world_realm_id + ON gameplay_admission_pointer_event USING btree (tenant_id, world_slug, realm_slug, id DESC); diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 14f0e68bd5..3d056250c5 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -17,7 +17,7 @@ error.logout.unavailable=Logout is temporarily unavailable. Please try again. error.play.invalid-argument=PLAY command requires a world selector. error.play.selection-required=Use WORLDS to browse available worlds, then PLAY [realm] [character]. error.play.realm-selection-required=Selection required. Use PLAY {worldSlug} [character] or browse REALMS first. -error.play.character-selection-required=Selection required. Use {playUsage} or browse {charsUsage} first. +error.play.character-selection-required=Selection required. Use {playUsage} with a known character; character browsing is currently unavailable. error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.selection-stale=That selection is stale. Run WORLDS or REALMS again, then retry PLAY. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index c76b86897d..611a174286 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -17,7 +17,7 @@ error.logout.unavailable=La déconnexion est temporairement indisponible. Veuill error.play.invalid-argument=La commande PLAY requiert un selecteur de monde. error.play.selection-required=Utilisez WORLDS pour parcourir les mondes disponibles, puis PLAY [realm] [character]. error.play.realm-selection-required=Sélection requise. Utilisez PLAY {worldSlug} [character] ou consultez REALMS d’abord. -error.play.character-selection-required=Selection requise. Utilisez {playUsage} ou consultez {charsUsage} dabord. +error.play.character-selection-required=Sélection requise. Utilisez {playUsage} avec un personnage connu ; la consultation des personnages n’est pas disponible actuellement. error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.selection-stale=Cette sélection a expiré. Relancez WORLDS ou REALMS, puis réessayez PLAY. diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 0a8cf4f2da..c254a871ee 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -38,6 +38,8 @@ class CommunicationWebSocketCrossServiceTest { private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; private static final String FIRST_PARTY_CONNECT_SECRET = "cross-service-connect-context-secret"; + private static final String SORA_EMAIL = "sora@example.com"; + private static final String NYX_EMAIL = "nyx@example.com"; @Container static final PostgreSQLContainer POSTGRES = @@ -74,6 +76,18 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { assertThat(responses).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(responses) .anyMatch(response -> response.contains(ChatTestFixtures.canonicalSayText())); + assertThat(entityStub().lastListCharactersByAccountRequest()) + .hasValueSatisfying( + request -> { + assertThat(request.getTenantId()).isEqualTo(Long.toString(TENANT_ID)); + assertThat(request.getAccountId()).isEqualTo(Long.toString(ACCOUNT_ID)); + assertThat(request.getGameInstanceId()) + .isEqualTo(Long.toString(DEMO_WORLD_INSTANCE_ID)); + assertThat(request.getPlayableStateScope()) + .isEqualTo( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED); + }); assertThat(socialStub().lastRequest()) .hasValueSatisfying( request -> { @@ -90,6 +104,54 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { 1.0); } + @Test + void websocketPlayReportsWorldAccessDeniedForActiveMembershipWithoutAdmission() throws Exception { + ensureTestServicesStarted(); + long sessionId = prepareGameInstance(); + STACK.accountStub().denyGameplayAdmission(); + + try (GameplayWebSocketScenarios.LoginThenPlayScenario scenario = + GameplayWebSocketScenarios.loginThenAttemptPlay( + GameplayWebSocketScenarios.proxyGatewayDriverFactory( + gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), + "account-denied-play-" + sessionId, + GameplayWebSocketScenarios.demoAdmission(READY_LOOK_TEXT), + client -> + client.awaitMatching( + response -> response.startsWith("ERROR WORLD_ACCESS_DENIED"), + "Active but non-admitting membership before Entity roster lookup"))) { + assertThat(scenario.driver().responses()) + .anyMatch(response -> response.startsWith("ERROR WORLD_ACCESS_DENIED")) + .noneMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")); + } + + assertThat(entityStub().lastListCharactersByAccountRequest()).isEmpty(); + } + + @Test + void websocketPlayRequiresJoinForFreshMissingMembershipBeforeEntityRosterRead() throws Exception { + ensureTestServicesStarted(); + long sessionId = prepareGameInstance(); + STACK.accountStub().setMembershipExists(false); + + try (GameplayWebSocketScenarios.LoginThenPlayScenario scenario = + GameplayWebSocketScenarios.loginThenAttemptPlay( + GameplayWebSocketScenarios.proxyGatewayDriverFactory( + gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), + "missing-membership-play-" + sessionId, + GameplayWebSocketScenarios.demoAdmission(READY_LOOK_TEXT), + client -> + client.awaitMatching( + response -> response.startsWith("ERROR JOIN_REQUIRED"), + "Fresh missing membership before Entity roster lookup"))) { + assertThat(scenario.driver().responses()) + .anyMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")) + .noneMatch(response -> response.startsWith("ERROR WORLD_ACCESS_DENIED")); + } + + assertThat(entityStub().lastListCharactersByAccountRequest()).isEmpty(); + } + @Test void websocketSayPushesRoomListenerViewToLiveRecipient() throws Exception { ensureTestServicesStarted(); @@ -102,8 +164,7 @@ void websocketSayPushesRoomListenerViewToLiveRecipient() throws Exception { "actor-say-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-say-conn", - GameplayWebSocketScenarios.demoAdmission( - "sora@example.com", "Sora", READY_LOOK_TEXT))) { + namedAdmission(SORA_EMAIL, "Sora"))) { scenario.actor().send("SAY hello travelers"); scenario.actor().awaitContains(ChatTestFixtures.canonicalSayText()); scenario.target().awaitContains(ChatTestFixtures.canonicalSayListenerText()); @@ -681,9 +742,9 @@ void websocketWhisperPushesTargetAndObserverViewsToLiveRecipients() throws Excep "actor-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-conn", - GameplayWebSocketScenarios.demoAdmission("sora@example.com", "Sora", READY_LOOK_TEXT), + namedAdmission(SORA_EMAIL, "Sora"), "observer-conn", - GameplayWebSocketScenarios.demoAdmission("nyx@example.com", "Nyx", READY_LOOK_TEXT))) { + namedAdmission(NYX_EMAIL, "Nyx"))) { scenario.actor().send("WHISPER Sora Keep quiet"); scenario.actor().awaitContains(ChatTestFixtures.canonicalWhisperText()); scenario.target().awaitContains(ChatTestFixtures.canonicalWhisperTargetText()); @@ -703,8 +764,7 @@ void websocketTellPushesTargetViewToLiveRecipient() throws Exception { "actor-tell-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-tell-conn", - GameplayWebSocketScenarios.demoAdmission( - "sora@example.com", "Sora", READY_LOOK_TEXT))) { + namedAdmission(SORA_EMAIL, "Sora"))) { scenario.actor().send("TELL Sora Meet me at the forge"); scenario.actor().awaitContains(ChatTestFixtures.canonicalTellText()); scenario.target().awaitContains(ChatTestFixtures.canonicalTellTargetText()); @@ -881,14 +941,29 @@ private static synchronized void ensureTestServicesStarted() throws Exception { } private long prepareGameInstance() { - return STACK.freshGameplayBaseline( - TENANT_ID, - DEMO_WORLD_INSTANCE_ID, - ACCOUNT_ID, - 7L, - ACCOUNT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + long sessionId = + STACK.freshGameplayBaseline( + TENANT_ID, + DEMO_WORLD_INSTANCE_ID, + ACCOUNT_ID, + 7L, + ACCOUNT_ID, + Long.parseLong(ChatTestFixtures.PLAYER_SORA), + Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + entityStub().resetCharacterRosterState(); + STACK.accountStub().mapAccountId(SORA_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_SORA)); + STACK.accountStub().mapAccountId(NYX_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + return sessionId; + } + + private static GameplayWebSocketScenarios.Admission namedAdmission( + String email, String characterName) { + return GameplayWebSocketScenarios.Admission.named( + email, + GameplayWebSocketScenarios.DEMO_PASSWORD, + GameplayWebSocketScenarios.DEMO_WORLD, + characterName, + READY_LOOK_TEXT); } private void seedLiveTargetSession() { diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index a0d3dd1f44..51e928c9ed 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -64,7 +64,7 @@ void websocketLookFlowReportsCanonicalTranscriptAndMetrics() throws Exception { assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses.get(0)).startsWith("OK WORLDS"); assertThat(responses.get(1).trim()) - .isEqualTo(GameplayTranscriptMatchers.canonicalLookWithPrompt()); + .isEqualTo(GameplayTranscriptMatchers.canonicalLook() + "\n\nEmberline>"); assertThat(responses.get(2)).startsWith("ERROR ROOM_NOT_FOUND"); GameplayAsyncAssertions.assertMetricEventually( @@ -280,7 +280,11 @@ void websocketReconnectAfterRevocationFailsClosed() throws Exception { List reconnectResponses = runPlayAfterReconnect(sessionId); assertThat(reconnectResponses).hasSizeGreaterThanOrEqualTo(2); assertThat(reconnectResponses).anyMatch(response -> response.startsWith("OK LOGIN")); - assertThat(reconnectResponses).anyMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")); + assertThat(reconnectResponses) + .anyMatch(response -> response.startsWith("ERROR WORLD_ACCESS_DENIED")) + .noneMatch( + response -> + response.contains("JOIN_REQUIRED") || response.contains("Run REALMS ")); } @Test @@ -457,8 +461,8 @@ private List runPlayAfterReconnect(long sessionId) throws Exception { READY_LOOK_TEXT, client -> client.awaitMatching( - response -> response.startsWith("ERROR JOIN_REQUIRED"), - "revoked membership admission denial"))) { + response -> response.startsWith("ERROR WORLD_ACCESS_DENIED"), + "active membership admission denial after revocation"))) { return scenario.responses(); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java new file mode 100644 index 0000000000..7d7624d623 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameplayAdmissionPointerCardinalityIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Test + void migrationRetainsDuplicateVisiblePublicPointersWhenUniqueIndexBuildFails() { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DataSource dataSource = dataSource(postgres); + migrateToVersion(dataSource, "6"); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + insertPointer(dsl, "demo", "production", 17L, 71L, true, true); + insertPointer(dsl, "sandbox", "production", 17L, 72L, true, true); + dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (" + + "id, world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id) " + + "VALUES (9001, 'legacy-world', 'legacy-realm', 'Legacy World', 'Legacy Realm', " + + "19, 91, 4, true, false, 'SHARED', 'ALLOW_NEW', 'unknown', " + + "'retained legacy event', 'legacy-request')"); + + assertThatThrownBy(() -> migrateToLatest(dataSource)) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("uq_gameplay_admission_pointer_visible_public_tenant") + .hasStackTraceContaining("tenant_id") + .hasStackTraceContaining("17"); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE tenant_id = 17 AND visible AND public_production_realm", + Long.class)) + .isEqualTo(2L); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM pg_indexes " + + "WHERE schemaname = 'public' " + + "AND indexname = 'uq_gameplay_admission_pointer_visible_public_tenant'", + Long.class)) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM gameplay_admission_pointer_event " + + "WHERE id = 9001 AND world_slug = 'legacy-world' AND tenant_id = 19 " + + "AND game_instance_id = 91 AND pointer_version = 4 " + + "AND catalog_revision IS NULL AND realm_id IS NULL " + + "AND playable_state_namespace_id IS NULL", + Long.class)) + .isEqualTo(1L); + } + } + + @Test + void concurrentVisiblePublicPointerWritersCannotBothCommitForOneTenant() throws Exception { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DataSource dataSource = dataSource(postgres); + migrateToLatest(dataSource); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit(() -> insertConcurrentPointer(dataSource, ready, start, "demo", 21L)); + Future second = + executor.submit( + () -> insertConcurrentPointer(dataSource, ready, start, "sandbox", 22L)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + int successfulWriters = + (first.get(15, TimeUnit.SECONDS) ? 1 : 0) + (second.get(15, TimeUnit.SECONDS) ? 1 : 0); + assertThat(successfulWriters).isEqualTo(1); + } + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + insertPointer(dsl, "hidden", "production", 17L, 23L, false, true); + insertPointer(dsl, "another-tenant", "production", 18L, 24L, true, true); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE tenant_id = 17 AND public_production_realm", + Long.class)) + .isEqualTo(2L); + } + } + + private static DataSource dataSource(PostgreSQLContainer postgres) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void migrateToVersion(DataSource dataSource, String version) { + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion(version)) + .load() + .migrate(); + } + + private static void migrateToLatest(DataSource dataSource) { + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + } + + private static void insertPointer( + DSLContext dsl, + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + boolean visible, + boolean publicProductionRealm) { + dsl.execute( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, 1, ?, false, 'SHARED', 'ALLOW_NEW', " + + "'integration-test', 'cardinality test', ?, ?, ?)", + worldSlug, + worldSlug, + realmSlug, + realmSlug, + tenantId, + gameInstanceId, + visible, + publicProductionRealm, + UUID.randomUUID(), + UUID.randomUUID()); + } + + private static boolean insertConcurrentPointer( + DataSource dataSource, + CountDownLatch ready, + CountDownLatch start, + String worldSlug, + long gameInstanceId) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent pointer start"); + } + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, 'production', 'Live Realm', 17, ?, 1, true, false, " + + "'SHARED', 'ALLOW_NEW', 'integration-test', 'concurrent cardinality test', " + + "true, ?, ?)")) { + statement.setString(1, worldSlug); + statement.setString(2, worldSlug); + statement.setLong(3, gameInstanceId); + statement.setObject(4, UUID.randomUUID()); + statement.setObject(5, UUID.randomUUID()); + statement.executeUpdate(); + return true; + } catch (SQLException exception) { + if ("23505".equals(exception.getSQLState())) { + return false; + } + throw exception; + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 2fe8fc23d2..aec616607d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -106,7 +106,7 @@ "firemud.gameplay.catalog.worlds[1].display-name=Builder Sandbox", "firemud.gameplay.catalog.worlds[1].realms[0].slug=production", "firemud.gameplay.catalog.worlds[1].realms[0].display-name=Live Realm", - "firemud.gameplay.catalog.worlds[1].realms[0].tenant-id=22", + "firemud.gameplay.catalog.worlds[1].realms[0].tenant-id=23", "firemud.gameplay.catalog.worlds[1].realms[0].game-instance-id=2", "firemud.gameplay.catalog.worlds[1].realms[0].pointer-version=1", "firemud.gameplay.catalog.worlds[1].realms[0].visible=true", @@ -184,8 +184,14 @@ void setUp() { redisSetStore.clear(); sessionContextService.deleteBySessionId(22L, 41L); sessionContextService.deleteBySessionId(22L, 42L); + sessionContextService.deleteBySessionId(22L, 43L); + sessionContextService.deleteBySessionId(22L, 44L); sessionContextService.deleteBySessionId(22L, 1L); sessionContextService.deleteBySessionId(22L, 2L); + sessionContextService.deleteBySessionId(23L, 43L); + sessionContextService.deleteBySessionId(23L, 44L); + sessionContextService.deleteBySessionId(23L, 41L); + sessionContextService.deleteBySessionId(23L, 2L); resetAdmissionPointers(); when(redisTemplate.opsForValue()).thenReturn(redisValueOperations); when(redisTemplate.opsForSet()).thenReturn(redisSetOperations); @@ -262,10 +268,10 @@ void setUp() { invocation -> GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId("123") - .setTenantId("22") + .setTenantId(invocation.getArgument(1)) .setMembershipExists(true) - .setMembershipLifecycleState("ACTIVE") .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") .setMembershipVersion(1L) .setMembershipAuthorityGeneration(1L) .setEvaluatedAt(java.time.Instant.now().toString()) @@ -278,7 +284,7 @@ void setUp() { org.mockito.Mockito.doAnswer( invocation -> GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(invocation.getArgument(0)) .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) @@ -304,8 +310,8 @@ void setUp() { .setTenantId("22") .setAccountId("123") .setName("Emberline") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(12) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() @@ -422,7 +428,7 @@ void setUp() { org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(1L); instance = new GameInstance(); instance.setId(2L); - instance.setTenantId(22L); + instance.setTenantId(23L); instance.setOwnerAccountId(123L); org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(2L); when(worldManagementClient.getWorldInstanceLifecycle( @@ -844,14 +850,14 @@ void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { } @Test - void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { + void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { List payloads; try (GameplayWebSocketDriver client = openGameplayDriver("41")) { client.login("demo@example.com", "swordfish"); client.send("REALMS demo"); client.awaitStartsWith("OK REALMS"); client.send("CHARS demo"); - client.awaitStartsWith("OK CHARS"); + client.awaitStartsWith("ERROR CHARACTER_LIST_UNAVAILABLE"); payloads = client.responses(); } @@ -862,21 +868,32 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { payload.startsWith("OK REALMS") && payload.contains("Live Realm (production) [shared, allow_new]")); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("OK CHARS") - && payload.contains("Emberline [lvl 12]") - && payload.contains("Sora [lvl 7]") - && payload.contains("Realm state: shared, creation: allow_new")); + .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); - verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + verify(accountClient) + .issueDirectTextConnectScope( + any(), + argThat( + target -> + "22".equals(target.tenantId()) + && "demo".equals(target.worldSlug()) + && "production".equals(target.realmSlug()) + && "SHARED".equals(target.playableStateScope()) + && "1".equals(target.gameInstanceId()) + && target.catalogRevision() > 0 + && target.pointerVersion() == 1L)); + verify(entityManagementClient, never()) + .listCharactersByAccount( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); } @Test - void websocketFirstPartyStructuredLobbyBrowseIncludesRealmAndCharacterViews() throws Exception { + void websocketFirstPartyStructuredLobbyBrowseFailsClosedForCharacters() throws Exception { List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "browse-1"))) { @@ -946,24 +963,14 @@ void websocketFirstPartyStructuredLobbyBrowseIncludesRealmAndCharacterViews() th .orElseThrow(); GameplayStructuredCommandAssertions.requireStructuredCommand( charsResult, "CHARS", "chars", "META", "WORLD_BROWSE", "UI"); - assertThat(charsResult.path("accepted").asBoolean()).isTrue(); - assertThat(charsResult.path("outputs").get(0).path("payloadType").asText()) - .isEqualTo("characters_view"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("realmSlug").asText()) - .isEqualTo("production"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("stateScope").asText()) - .isEqualTo("SHARED"); - assertThat( - charsResult - .path("outputs") - .get(0) - .path("payload") - .path("characterCreationPolicy") - .asText()) - .isEqualTo("ALLOW_NEW"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("characters")).hasSize(2); - verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(charsResult.path("accepted").asBoolean()).isFalse(); + assertThat(charsResult.path("errorCode").asText()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + verify(entityManagementClient, never()) + .listCharactersByAccount( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); } @Test @@ -1020,7 +1027,7 @@ void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { } @Test - void websocketFirstPartyReconnectSkipsPrivateContextAndKeepsFreshLookAfterPlay() + void websocketFirstPartyFreshPlayDoesNotReplayPrivateContextAndPerformsFreshLook() throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( @@ -1085,7 +1092,8 @@ && containsKind(json(payload), "PROMPT"), } @Test - void websocketFirstPartyLogoutDoesNotReplayRetainedContextForFreshReconnect() throws Exception { + void websocketFirstPartyLogoutRetainsButDoesNotReplayPrivateContextAfterFailClosedLogout() + throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( Optional.of( @@ -1131,7 +1139,12 @@ void websocketFirstPartyLogoutDoesNotReplayRetainedContextForFreshReconnect() th payload -> "player_output".equals(json(payload).path("eventType").asText()) && containsKind(json(payload), "VIEW"), - "fresh current view"); + "fresh view output"); + client.awaitMatching( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "PROMPT"), + "fresh prompt output"); secondPayloads = client.responses(); } @@ -1148,6 +1161,11 @@ && containsKind(json(payload), "VIEW"), payload -> "player_output".equals(json(payload).path("eventType").asText()) && containsKind(json(payload), "VIEW")); + assertThat(secondPayloads) + .anyMatch( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "PROMPT")); verify(screenBufferService, never()).get(22L, 1L, 123L); } @@ -1253,22 +1271,23 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() assertThat(pointerAfter.catalogRevision()).isEqualTo(pointerBefore.catalogRevision()); client.send("LOOK"); client.awaitStartsWith("ERROR PLAY_REQUIRED"); + clearInvocations(entityManagementClient); client.send("CHARS demo"); - client.awaitStartsWith("OK CHARS"); + client.awaitStartsWith("ERROR CHARACTER_LIST_UNAVAILABLE"); payloads = client.responses(); } assertThat(payloads).anyMatch(payload -> payload.startsWith("OK LOGIN")); assertThat(payloads).anyMatch(payload -> payload.startsWith("OK PLAY")); assertThat(payloads).anyMatch(payload -> payload.startsWith("ERROR PLAY_REQUIRED")); - assertThat(payloads).anyMatch(payload -> payload.startsWith("OK CHARS")); - assertThat(payloads).anyMatch(payload -> payload.contains("CutoverArrival")); - org.mockito.Mockito.verify(entityManagementClient) + assertThat(payloads) + .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); + verify(entityManagementClient, never()) .listCharactersByAccount( - "22", - "123", - Long.toString(CUTOVER_GAME_INSTANCE_ID), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); } @Test @@ -1295,7 +1314,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots "42", java.util.Map.of( "X-Game-Instance-Id", "2", - "X-Tenant-Id", "22", + "X-Tenant-Id", "23", "X-Firemud-Transport-Session-Id", "41", "X-World-Slug", "sandbox", "X-Realm-Slug", "production", @@ -1304,6 +1323,64 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots second.awaitStartsWith("ERROR LOGIN_REQUIRED"); second.login("demo@example.com", "swordfish"); second.awaitStartsWith("OK LOGIN"); + second.send("REALMS sandbox"); + second.awaitStartsWith("OK REALMS"); + payloads = second.responses(); + } + + assertThat(payloads).anyMatch(payload -> payload.startsWith("ERROR LOGIN_REQUIRED")); + assertThat(payloads).anyMatch(payload -> payload.startsWith("OK LOGIN")); + assertThat(payloads) + .anyMatch( + payload -> + payload.startsWith("OK REALMS") && payload.contains("Live Realm (production)")); + assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEmpty(); + assertThat(sessionContextService.findByTenantAndSessionId(23L, 41L)) + .hasValueSatisfying( + context -> { + assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.gameInstanceId()).isZero(); + assertThat(context.characterId()).isZero(); + assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); + assertThat(context.worldSlug()).isEqualTo("sandbox"); + assertThat(context.realmSlug()).isEqualTo("production"); + assertThat(context.pointerVersion()).isEqualTo(1L); + }); + assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); + } + + @Test + void websocketRouteChangeHidesPrivateOnlySandboxFromPublicWorldCommands() throws Exception { + try (GameplayWebSocketDriver first = + openGameplayDriver( + "43", + java.util.Map.of( + "X-Tenant-Id", "22", + "X-Firemud-Transport-Session-Id", "43", + "X-World-Slug", "demo", + "X-Realm-Slug", "production", + "X-Pointer-Version", "1"))) { + first.login("demo@example.com", "swordfish"); + first.play("demo", "Emberline"); + first.send("LOOK"); + first.awaitStartsWith("OK LOOK"); + } + + List payloads; + try (GameplayWebSocketDriver second = + openGameplayDriver( + "44", + java.util.Map.of( + "X-Game-Instance-Id", "2", + "X-Tenant-Id", "22", + "X-Firemud-Transport-Session-Id", "43", + "X-World-Slug", "sandbox", + "X-Realm-Slug", "production", + "X-Pointer-Version", "1"))) { + second.send("LOOK"); + second.awaitStartsWith("ERROR LOGIN_REQUIRED"); + second.login("demo@example.com", "swordfish"); + second.awaitStartsWith("OK LOGIN"); second.send("WORLDS"); second.awaitStartsWith("OK WORLDS"); second.send("REALMS sandbox"); @@ -1322,7 +1399,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots payload -> payload.startsWith("ERROR INVALID_ARGUMENT") && payload.contains("REALMS requires a valid world selector")); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) + assertThat(sessionContextService.findByTenantAndSessionId(22L, 43L)) .hasValueSatisfying( context -> { assertThat(context.accountId()).isEqualTo(123L); @@ -1333,7 +1410,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(context.realmSlug()).isEqualTo("production"); assertThat(context.pointerVersion()).isEqualTo(1L); }); - assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); + assertThat(gameplayPresenceService.findConnectedBySessionId(43L)).isEmpty(); } @Test @@ -1439,7 +1516,8 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog List payloads; try (GameplayWebSocketDriver second = - openFirstPartyDriver("2", firstPartyClaims("sandbox", "production", "2", "1", "route-b"))) { + openFirstPartyDriver( + "2", firstPartyClaimsForTenant("23", "sandbox", "production", "2", "1", "route-b"))) { second.send("LOGIN"); second.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); @@ -1490,7 +1568,8 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog assertThat(realmsRejected.path("accepted").asBoolean()).isFalse(); assertThat(realmsRejected.path("errorCode").asText()).isEqualTo("INVALID_ARGUMENT"); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) + assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)).isEmpty(); + assertThat(sessionContextService.findByTenantAndSessionId(23L, 2L)) .hasValueSatisfying( context -> { assertThat(context.accountId()).isEqualTo(123L); @@ -1643,11 +1722,22 @@ private java.util.Map firstPartyClaims( String gameInstanceId, String pointerVersion, String suffix) { + return firstPartyClaimsForTenant( + "22", worldSlug, realmSlug, gameInstanceId, pointerVersion, suffix); + } + + private java.util.Map firstPartyClaimsForTenant( + String tenantId, + String worldSlug, + String realmSlug, + String gameInstanceId, + String pointerVersion, + String suffix) { return java.util.Map.of( "accountId", "123", "tenantId", - "22", + tenantId, "worldSlug", worldSlug, "realmSlug", @@ -1745,7 +1835,7 @@ private void resetAdmissionPointers() { "Builder Sandbox", "production", "Live Realm", - 22L, + 23L, 2L, true, false, diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java index a425f43d3c..00c4b80613 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java @@ -9,23 +9,14 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; import org.springframework.util.StringUtils; /** Small process-local fake for command tests; production presence is Redis-backed. */ public final class FakeGameplayPresenceService implements GameplayPresenceService { - private static final Logger logger = LoggingUtil.getLogger(FakeGameplayPresenceService.class); private final ConcurrentMap presences = new ConcurrentHashMap<>(); - private final JwtUtil jwtUtil; - - public FakeGameplayPresenceService(JwtUtil jwtUtil) { - this.jwtUtil = jwtUtil; - } @Override public void registerConnected(SessionContext context) { @@ -47,7 +38,7 @@ public void registerConnected(SessionContext context) { StringUtils.hasText(context.characterName()) ? context.characterName().trim() : fallbackCharacterName(context), - GameplayPresenceRoleClassifier.classifyRole(context, jwtUtil, logger), + GameplayPresenceRoleClassifier.classifyRole(), System.currentTimeMillis(), null, null, diff --git a/services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java new file mode 100644 index 0000000000..dd0faa4821 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java @@ -0,0 +1,167 @@ +package db.migration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.net.JarURLConnection; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.jar.JarFile; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; + +class V12__enforce_tenant_public_realm_cardinalityTest { + private static final Pattern MIGRATION_FILE = Pattern.compile("^V([^_]+)__.*\\.sql$"); + + @Test + void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV13() + throws IOException, URISyntaxException { + var auditMigrationUrl = + getClass() + .getClassLoader() + .getResource("db/migration/V7__audit_gameplay_catalog_revision.sql"); + assertThat(auditMigrationUrl).isNotNull(); + + Map> namesByVersion = new TreeMap<>(); + for (String name : migrationNames(auditMigrationUrl)) { + Matcher matcher = MIGRATION_FILE.matcher(name); + assertThat(matcher.matches()).as("migration filename %s", name).isTrue(); + MigrationVersion version = MigrationVersion.fromVersion(matcher.group(1)); + namesByVersion.computeIfAbsent(version, ignored -> new java.util.ArrayList<>()).add(name); + } + + assertThat(namesByVersion.values()).allSatisfy(names -> assertThat(names).hasSize(1)); + List orderedMigrationNames = + namesByVersion.values().stream().flatMap(List::stream).toList(); + assertThat(orderedMigrationNames) + .containsSubsequence( + "V7__audit_gameplay_catalog_revision.sql", + "V8__repair_legacy_bootstrap_public_realm.sql", + "V9__initial_admission_bind_owner_ledger.sql", + "V10__run_owned_initial_launch_identity.sql", + "V11__gameplay_command_account_uuid.sql", + "V12__enforce_tenant_public_realm_cardinality.sql", + "V13__index_gameplay_admission_pointer_event_tenant_lookup.sql"); + + String v7 = readMigration("V7__audit_gameplay_catalog_revision.sql"); + String normalizedV7 = normalizeSql(v7); + assertThat(normalizedV7) + .contains( + "ADD COLUMN catalog_revision bigint", + "ADD COLUMN realm_id uuid", + "ADD COLUMN playable_state_namespace_id uuid", + "CHECK (catalog_revision IS NULL OR catalog_revision > 0)", + "CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL))"); + assertNoDataRewrite(normalizedV7); + + String v8Repair = normalizeSql(readMigration("V8__repair_legacy_bootstrap_public_realm.sql")); + // V8 repairs only a fully evidenced, unchanged bootstrap pair; it intentionally updates data. + assertThat(v8Repair) + .contains( + "demo.world_slug = 'demo'", + "demo.realm_slug = 'production'", + "sandbox.world_slug = 'sandbox'", + "sandbox.realm_slug = 'production'", + "demo.last_updated_by = 'system/bootstrap'", + "sandbox.last_updated_by = 'system/bootstrap'", + "public_pointer.public_production_realm = true", + "= 2", + "UPDATE gameplay_admission_pointer sandbox", + "SET public_production_realm = false", + "AND sandbox.catalog_revision = 1", + "migration:V8:repair-legacy-bootstrap-public-realm:"); + + String v9 = normalizeSql(readMigration("V9__initial_admission_bind_owner_ledger.sql")); + assertThat(v9).contains("CREATE TABLE gameplay_initial_admission_bind_catalog"); + assertNoDataRewrite(v9); + + String v10 = normalizeSql(readMigration("V10__run_owned_initial_launch_identity.sql")); + assertThat(v10).contains("run_owned_start_request_id"); + assertNoDataRewrite(v10); + + String v11 = normalizeSql(readMigration("V11__gameplay_command_account_uuid.sql")); + assertThat(v11) + .contains( + "ADD COLUMN account_uuid UUID", + "ADD CONSTRAINT chk_gameplay_command_account_uuid_non_nil", + "account_uuid IS NULL", + "account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID"); + assertNoDataRewrite(v11); + + String v12 = normalizeSql(readMigration("V12__enforce_tenant_public_realm_cardinality.sql")); + assertThat(v12) + .contains( + "CREATE UNIQUE INDEX uq_gameplay_admission_pointer_visible_public_tenant", + "ON gameplay_admission_pointer (tenant_id)", + "WHERE visible AND public_production_realm"); + assertNoDataRewrite(v12); + + String v13 = + normalizeSql( + readMigration("V13__index_gameplay_admission_pointer_event_tenant_lookup.sql")); + assertThat(v13) + .isEqualTo( + "CREATE INDEX idx_gameplay_admission_pointer_event_tenant_world_realm_id " + + "ON gameplay_admission_pointer_event USING btree " + + "(tenant_id, world_slug, realm_slug, id DESC);"); + assertNoDataRewrite(v13); + } + + private String readMigration(String name) throws IOException { + try (var stream = getClass().getClassLoader().getResourceAsStream("db/migration/" + name)) { + assertThat(stream).as("migration resource %s", name).isNotNull(); + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static List migrationNames(URL migrationResourceUrl) + throws IOException, URISyntaxException { + if ("file".equals(migrationResourceUrl.getProtocol())) { + try (var migrationFiles = Files.list(Path.of(migrationResourceUrl.toURI()).getParent())) { + return migrationFiles + .map(Path::getFileName) + .filter(Objects::nonNull) + .map(Path::toString) + .filter(name -> name.endsWith(".sql")) + .toList(); + } + } + + if ("jar".equals(migrationResourceUrl.getProtocol())) { + var connection = (JarURLConnection) migrationResourceUrl.openConnection(); + connection.setUseCaches(false); + String migrationDirectory = + connection.getEntryName().substring(0, connection.getEntryName().lastIndexOf('/') + 1); + try (JarFile jarFile = connection.getJarFile()) { + return jarFile.stream() + .map(entry -> entry.getName()) + .filter(name -> name.startsWith(migrationDirectory)) + .map(name -> name.substring(migrationDirectory.length())) + .filter(name -> !name.isEmpty() && !name.contains("/") && name.endsWith(".sql")) + .toList(); + } + } + + throw new IllegalStateException( + "Unsupported migration resource URL protocol: " + migrationResourceUrl.getProtocol()); + } + + private static String normalizeSql(String sql) { + return sql.replaceAll("\\s+", " ").trim(); + } + + private static void assertNoDataRewrite(String normalizedSql) { + assertThat(normalizedSql.toUpperCase(Locale.ROOT)) + .doesNotContain("UPDATE ", "DELETE ", "INSERT ", "TRUNCATE", "DROP TABLE", "DROP COLUMN"); + } +} 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 d135a4182a..6be3074ab3 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 @@ -704,13 +704,15 @@ void realmAccessGrantNormalizesExhaustedUnavailableToCanonicalUnavailable() thro verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); } - @Test - void runtimeMembershipNormalizesInitialInternalWithoutRetryOrChannelRebuild() throws Exception { + @ParameterizedTest + @ValueSource(strings = {"INTERNAL", "FAILED_PRECONDITION"}) + void runtimeMembershipNormalizesDeniedReadWithoutRetryOrChannelRebuild(String statusName) + throws Exception { AccountServiceGrpc.AccountServiceBlockingStub stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class))) - .thenThrow(new StatusRuntimeException(Status.INTERNAL)); + .thenThrow(new StatusRuntimeException(Status.fromCode(Status.Code.valueOf(statusName)))); GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); AccountClient client = newClient(stub, channelFactory); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java index 0816d86df9..ca9480694d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextOrdinalSelectionResolverTest.java @@ -72,6 +72,53 @@ void resolvesWorldAndRealmOrdinalsAgainstCurrentBoundSnapshots() { .isEqualTo(new DirectTextOrdinalSelectionResolver.UniqueWorldTenantId(22L)); } + @Test + void concreteRealmResolverKeepsNumericTargetFromExactResponseSubsetAfterReordering() { + RealmView preview = previewRealm(2L, 1L); + WorldView responseWorld = new WorldView("demo", "Demo", List.of(preview, realm)); + DirectTextConnectScopeSessionStore store = + storeWithRealmResponse(responseWorld, List.of(preview)); + WorldView currentWorld = new WorldView("demo", "Demo", List.of(realm, preview)); + GameplayWorldCatalog currentCatalog = GameplayWorldCatalog.forWorldViews(List.of(currentWorld)); + RealmDiscoverySnapshot publicSnapshot = currentCatalog.readRealmDiscoverySnapshot(currentWorld); + + assertThat(publicSnapshot.catalogFingerprint()) + .isNotEqualTo( + GameplayWorldCatalog.forWorldViews(List.of(responseWorld)) + .realmDiscoverySnapshot(responseWorld, List.of(preview)) + .catalogFingerprint()); + + var result = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", store, caller, 22L, currentWorld, NOW, () -> publicSnapshot, currentCatalog); + + assertThat(result.selectedValue()).contains(preview); + } + + @Test + void concreteRealmResolverRejectsChangedTargetInExactResponseSubset() { + RealmView preview = previewRealm(2L, 1L); + WorldView responseWorld = new WorldView("demo", "Demo", List.of(preview, realm)); + DirectTextConnectScopeSessionStore store = + storeWithRealmResponse(responseWorld, List.of(preview)); + RealmView reroutedPreview = previewRealm(3L, 2L); + WorldView currentWorld = new WorldView("demo", "Demo", List.of(realm, reroutedPreview)); + GameplayWorldCatalog currentCatalog = GameplayWorldCatalog.forWorldViews(List.of(currentWorld)); + + var result = + DirectTextOrdinalSelectionResolver.resolveRealmOrdinal( + "1", + store, + caller, + 22L, + currentWorld, + NOW, + () -> currentCatalog.readRealmDiscoverySnapshot(currentWorld), + currentCatalog); + + assertThat(result).isInstanceOf(DirectTextOrdinalSelectionResolver.SnapshotMismatch.class); + } + @Test void absentAndExpiredWorldSnapshotsRemainUnbound() { var absent = @@ -304,4 +351,40 @@ private DirectTextConnectScopeSessionStore.RealmsSnapshot currentRealmsSnapshot( NOW.plusSeconds(30), realms.ordinalTargets()); } + + private DirectTextConnectScopeSessionStore storeWithRealmResponse( + WorldView responseWorld, List responseRealms) { + GameplayWorldCatalog responseCatalog = + GameplayWorldCatalog.forWorldViews(List.of(responseWorld)); + RealmDiscoverySnapshot responseSnapshot = + responseCatalog.realmDiscoverySnapshot(responseWorld, responseRealms); + DirectTextConnectScopeSessionStore store = DirectTextConnectScopeSessionStore.inMemoryForTest(); + store.replaceRealmSnapshot( + caller, + "demo", + 22L, + "demo", + responseSnapshot.catalogFingerprint(), + responseSnapshot.ordinalTargets(), + List.of(), + NOW); + return store; + } + + private RealmView previewRealm(long gameInstanceId, long pointerVersion) { + return new RealmView( + "preview", + "Preview", + 22L, + gameInstanceId, + pointerVersion, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW", + 1L, + UUID.fromString("00000000-0000-0000-0000-000000000003"), + UUID.fromString("00000000-0000-0000-0000-000000000004")); + } } 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 262e7867d7..85297eab6b 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 @@ -13,6 +13,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; +import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -293,31 +294,24 @@ void visibleWorldsDropsAmbiguousRealmSelectorRows() { } @Test - void visibleWorldsKeepsSameWorldSlugSeparateAcrossTenants() { + void visibleWorldsKeepsDistinctWorldSlugsTenantQualifiedInOrdinalTargets() { when(authorityService.listPointers()) .thenReturn( List.of( pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), - pointer("DEMO", "Other Demo", "production", "Other Live", 2L, 21L, 8L))); + pointer( + "authority", "Authority World", "production", "Authority Live", 2L, 21L, 8L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); - assertThat(catalog.visibleWorlds()) - .extracting(GameplayWorldCatalog.WorldView::slug) - .containsExactly("demo", "DEMO"); - assertThat(catalog.resolveWorld("demo")).isEmpty(); GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.readDiscoverySnapshot(); assertThat(snapshot.output().worlds()) .extracting(WorldsViewOutput.WorldEntry::ordinal) .containsExactly(1, 2); - assertThat(snapshot.output().worlds()) - .extracting(WorldsViewOutput.WorldEntry::slug) - .containsExactly("demo", "DEMO"); assertThat(snapshot.ordinalTargets()) .extracting(DirectTextConnectScopeSessionStore.WorldOrdinalTarget::tenantId) .containsExactly(1L, 2L); assertThat(catalog.resolveSnapshotOrdinal(snapshot, snapshot.ordinalTargets().get(1))) - .hasValueSatisfying( - world -> assertThat(world.realms().getFirst().tenantId()).isEqualTo(2L)); + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("authority")); } @Test @@ -532,6 +526,9 @@ void authoritySnapshotSuppressesTenantWithMultiplePublicRealmsAndKeepsHealthyTen .containsExactly("healthy"); assertThat(catalog.resolveWorldFromAuthoritySnapshot("alpha")).isEmpty(); assertThat(catalog.resolveWorldFromAuthoritySnapshot("healthy")).isPresent(); + assertThatThrownBy(() -> catalog.resolvePublicWorldFromAuthoritySnapshot("alpha")) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class); + assertThat(catalog.resolvePublicWorldFromAuthoritySnapshot("healthy")).isPresent(); } @Test @@ -966,6 +963,17 @@ void browseViewUsesOneWorldSnapshotForDefaultRealmAndCardinalityChecks() { assertThat(supplierCalls).hasValue(1); } + @Test + void nullWorldSupplierResultBehavesAsAnEmptyCatalog() { + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(() -> null); + + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.ZERO); + } + @Test void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { GameplayWorldCatalog catalog = @@ -1101,15 +1109,25 @@ void realmSnapshotFingerprintsPublicCatalogAndPreservesVisibleResponseTargets() GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(List.of(reordered)); GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = originalCatalog.realmDiscoverySnapshot(original, List.of(production, preview)); + GameplayWorldCatalog.RealmDiscoverySnapshot publicSnapshot = + originalCatalog.readRealmDiscoverySnapshot(original); assertThat(snapshot.ordinalTargets()) .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) .containsExactly("production", "preview"); - assertThat(catalog.readRealmDiscoverySnapshot(reordered).catalogFingerprint()) - .isEqualTo(snapshot.catalogFingerprint()); - assertThat(catalog.readRealmDiscoverySnapshot(reordered).ordinalTargets()) + GameplayWorldCatalog.RealmDiscoverySnapshot reorderedPublicSnapshot = + catalog.readRealmDiscoverySnapshot(reordered); + assertThat(reorderedPublicSnapshot.catalogFingerprint()) + .isEqualTo(publicSnapshot.catalogFingerprint()) + .isNotEqualTo(snapshot.catalogFingerprint()); + assertThat(reorderedPublicSnapshot.ordinalTargets()) .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) .containsExactly("production"); + GameplayWorldCatalog.RealmDiscoverySnapshot reorderedResponseSnapshot = + catalog.realmDiscoverySnapshot(reordered, List.of(production, preview)); + assertThat(reorderedResponseSnapshot.catalogFingerprint()) + .isEqualTo(snapshot.catalogFingerprint()); + assertThat(reorderedResponseSnapshot.ordinalTargets()).isEqualTo(snapshot.ordinalTargets()); assertThat( catalog.resolveRealmSnapshotOrdinal( reordered, snapshot, snapshot.ordinalTargets().get(0))) @@ -1125,7 +1143,14 @@ void realmSnapshotFingerprintsPublicCatalogAndPreservesVisibleResponseTargets() changedPrivateCatalog .readRealmDiscoverySnapshot(changedPrivateAndReordered) .catalogFingerprint()) - .isEqualTo(snapshot.catalogFingerprint()); + .isEqualTo(publicSnapshot.catalogFingerprint()); + GameplayWorldCatalog.RealmDiscoverySnapshot changedResponseSnapshot = + changedPrivateCatalog + .revalidateRealmDiscoverySnapshot(changedPrivateAndReordered, snapshot.ordinalTargets()) + .orElseThrow(); + assertThat(changedResponseSnapshot.catalogFingerprint()) + .isNotEqualTo(snapshot.catalogFingerprint()); + assertThat(changedResponseSnapshot.ordinalTargets()).isNotEqualTo(snapshot.ordinalTargets()); assertThat( changedPrivateCatalog.resolveRealmSnapshotOrdinal( changedPrivateAndReordered, snapshot, snapshot.ordinalTargets().get(1))) @@ -1171,7 +1196,7 @@ void realmSnapshotFingerprintsPublicCatalogAndPreservesVisibleResponseTargets() GameplayWorldCatalog.forWorldViews(List.of(reroutedWorld)) .readRealmDiscoverySnapshot(reroutedWorld) .catalogFingerprint()) - .isNotEqualTo(snapshot.catalogFingerprint()); + .isNotEqualTo(publicSnapshot.catalogFingerprint()); GameplayWorldCatalog.RealmView noLongerPublic = new GameplayWorldCatalog.RealmView( @@ -1194,7 +1219,7 @@ void realmSnapshotFingerprintsPublicCatalogAndPreservesVisibleResponseTargets() GameplayWorldCatalog.forWorldViews(List.of(policyChangedWorld)) .readRealmDiscoverySnapshot(policyChangedWorld) .catalogFingerprint()) - .isNotEqualTo(snapshot.catalogFingerprint()); + .isNotEqualTo(publicSnapshot.catalogFingerprint()); GameplayWorldCatalog.RealmView otherTenantProduction = new GameplayWorldCatalog.RealmView( @@ -1222,6 +1247,95 @@ void realmSnapshotFingerprintsPublicCatalogAndPreservesVisibleResponseTargets() .containsExactly("other-live", "production"); } + @Test + void revalidatedRealmFingerprintIncludesOnlyTheOriginalResponseTargets() { + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(List.of()); + GameplayWorldCatalog.RealmView production = + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.RealmView deniedPrivateRealm = + new GameplayWorldCatalog.RealmView( + "preview", + "Preview Realm", + 7L, + 12L, + 4L, + true, + false, + false, + "SHARED", + "ALLOW_NEW", + 30L, + UUID.fromString("a11df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("b2a958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.WorldView responseWorld = + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(production, deniedPrivateRealm)); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + catalog.realmDiscoverySnapshot(responseWorld, List.of(production)); + GameplayWorldCatalog.RealmView changedDeniedPrivateRealm = + new GameplayWorldCatalog.RealmView( + "preview", + "Preview Realm", + 7L, + 98L, + 9L, + true, + false, + false, + "SHARED", + "ALLOW_NEW", + 31L, + deniedPrivateRealm.realmId(), + deniedPrivateRealm.playableStateNamespaceId()); + + GameplayWorldCatalog.RealmDiscoverySnapshot hiddenChange = + catalog + .revalidateRealmDiscoverySnapshot( + new GameplayWorldCatalog.WorldView( + "demo", "Demo", List.of(production, changedDeniedPrivateRealm)), + snapshot.ordinalTargets()) + .orElseThrow(); + + assertThat(hiddenChange.catalogFingerprint()).isEqualTo(snapshot.catalogFingerprint()); + assertThat(hiddenChange.ordinalTargets()).containsExactlyElementsOf(snapshot.ordinalTargets()); + + GameplayWorldCatalog.RealmView changedProduction = + new GameplayWorldCatalog.RealmView( + production.slug(), + production.displayName(), + production.tenantId(), + production.gameInstanceId(), + production.pointerVersion() + 1, + production.visible(), + production.publicProductionRealm(), + production.requiresCharacterSelection(), + production.stateScope(), + production.characterCreationPolicy(), + production.catalogRevision(), + production.realmId(), + production.playableStateNamespaceId()); + GameplayWorldCatalog.RealmDiscoverySnapshot visibleChange = + catalog + .revalidateRealmDiscoverySnapshot( + new GameplayWorldCatalog.WorldView( + "demo", "Demo", List.of(changedProduction, deniedPrivateRealm)), + snapshot.ordinalTargets()) + .orElseThrow(); + assertThat(visibleChange.catalogFingerprint()).isNotEqualTo(snapshot.catalogFingerprint()); + } + private static GameplayWorldCatalog.WorldView worldWithTargetRealm( String realmSlug, boolean visible) { return new GameplayWorldCatalog.WorldView( @@ -1652,4 +1766,403 @@ private static GameplayAdmissionPointerSnapshot copyAuthorityPointer( private static UUID stableId(String value) { return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); } + + @Test + void ambiguousPublicRealmSelectorSuppressesPublicDiscoveryButRetainsInternalCatalog() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + realm("production", true), + realm("PRODUCTION", false), + realm("event", false))))); + assertThat(catalog.publicVisibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isPresent(); + assertThat(catalog.resolveRealmTarget("demo", "production")).isEmpty(); + } + + @Test + void duplicateRealmSlugsCannotHideExtraVisiblePublicRealmRows() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + realm("production", true), + realm("event", true), + realm("EVENT", true), + realm("private", false))))); + + assertThat(catalog.publicVisibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); + } + + @Test + void eachTenantMayExposeOneVisiblePublicRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(realm("production", true))), + new GameplayWorldCatalog.WorldView( + "sandbox", + "Builder Sandbox", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 8L, + 12L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"))))); + + assertThat(catalog.browseView().worlds()).extracting("slug").containsExactly("demo", "sandbox"); + assertThat(catalog.resolveWorld("demo")).isPresent(); + assertThat(catalog.resolveWorld("sandbox")).isPresent(); + } + + @Test + void hiddenSecondPublicRealmDoesNotInvalidateOrAuthorizePublicSelection() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + realm("production", true), + new GameplayWorldCatalog.RealmView( + "hidden-production", + "Hidden Production", + 7L, + 12L, + 1L, + false, + true, + false, + "SHARED", + "ALLOW_NEW"))))); + + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("demo").orElseThrow(); + + assertThat(catalog.browseRealms("demo").orElseThrow().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + assertThat(catalog.resolveRealm(world, "hidden-production")).isEmpty(); + } + + @Test + void publicBrowseDropsCaseInsensitiveRealmSlugCollisions() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of(realm("production", true), realm("PRODUCTION", true))))); + + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.browseRealms("demo")).isEmpty(); + } + + @Test + void publicBrowseOmitsPrivateOnlyWorldsAndPrivateRealmMetadata() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 7L, + 17L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))), + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 7L, + 17L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + + assertThat(catalog.browseView().worlds()).extracting("slug").containsExactly("mixed-world"); + assertThat(catalog.browseRealms("mixed-world").orElseThrow().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + assertThat(catalog.browseRealms("private-world")).isEmpty(); + } + + @Test + void realmSelectionUsesPublicDefaultWhenVisiblePrivateRealmIsAlsoPresent() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "private", + "Private Realm", + 7L, + 17L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("mixed-world").orElseThrow(); + + assertThat(catalog.requiresExplicitRealmSelection(world)).isFalse(); + assertThat(catalog.resolveDefaultRealm(world)) + .map(GameplayWorldCatalog.RealmView::slug) + .contains("production"); + } + + @Test + void resolveWorldFailsClosedWhenNormalizedSlugMatchesMultipleWorldViews() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of(worldWithTargetRealm("preview", true), worldWithTargetRealm("preview", true))); + + assertThat(catalog.resolveWorld(" DeMo ")).isEmpty(); + assertThat(catalog.resolveRealmTarget(" DeMo ", "production")).isEmpty(); + } + + @Test + void sameTenantCannotExposeTwoVisiblePublicRealmsInOneWorld() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of(realm("production", true), realm("seasonal", true))))); + + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isPresent(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + } + + @Test + void sameTenantCannotExposeVisiblePublicRealmsAcrossDifferentWorlds() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(realm("production", true))), + new GameplayWorldCatalog.WorldView( + "sandbox", "Builder Sandbox", List.of(realm("production", true))))); + + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isPresent(); + assertThat(catalog.resolveWorld("sandbox")).isPresent(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.resolvePublicWorld("sandbox")).isEmpty(); + } + + @Test + void privateOnlyTenantIsHiddenFromPublicDiscoveryButRetainedForInternalResolution() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-only", + "Private Only", + List.of(realm("private-a", false), realm("private-b", false))))); + + assertThat(catalog.visibleWorlds()).hasSize(1); + assertThat(catalog.publicVisibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolvePublicWorld("private-only")).isEmpty(); + assertThat(catalog.resolveWorld("private-only")).isPresent(); + } + + @Test + void uniqueWorldRemainsVisibleAndResolvable() { + when(authorityService.listPointers()) + .thenReturn( + List.of(pointer("demo", "Demo World", "production", "Live Realm", 7L, 11L, 1L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).hasSize(1); + assertThat(catalog.browseView().worlds()).extracting("slug").containsExactly("demo"); + assertThat(catalog.resolveWorld("DEMO")).isPresent(); + } + + @Test + void visibleWorldsDropsCaseInsensitiveRealmSlugCollisions() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), + pointer("demo", "Demo World", "PRODUCTION", "Live Realm", 1L, 12L, 8L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + } + + @Test + void visibleWorldsSuppressesCaseInsensitiveWorldSlugCollisionsAcrossTenants() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 7L, 11L, 1L), + pointer("DEMO", "Other Demo World", "event", "Event Realm", 8L, 12L, 1L), + pointer( + "DEMO", "Other Demo World", "production", "Other Live Realm", 8L, 13L, 2L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.browseRealms("DEMO")).isEmpty(); + } + + @Test + void visibleWorldsSuppressesCaseInsensitiveWorldSlugCollisionsWithinTenant() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 7L, 11L, 1L), + pointer("DEMO", "Other Demo World", "event", "Event Realm", 7L, 12L, 1L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + } + + @Test + void authoritySnapshotResolvesDigitOnlyWorldSlugWithoutTreatingItAsAnOrdinal() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), + pointer("123", "Numeric World", "production", "Numeric Live", 2L, 21L, 8L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.resolveWorldFromAuthoritySnapshot("123")) + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("123")); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("2")).isEmpty(); + } + + @Test + void genericAuthorityResolverUsesStableSlugForWorldViewSuppliers() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews(List.of(worldWithRealm("123", "production", 7L, true))); + + assertThat(catalog.resolveWorldFromAuthoritySnapshot("123")) + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("123")); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("1")).isEmpty(); + } + + @Test + void numericWorldAliasUsesRetainedPublicMenuWhileExplicitSlugRetainsAdmissionResolution() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("private-world", "private", 7L, false), + worldWithRealm("public-world", "production", 7L, true))); + GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.readDiscoverySnapshot(); + + assertThat(snapshot.output().worlds()) + .extracting(WorldsViewOutput.WorldEntry::slug) + .containsExactly("public-world"); + assertThat(catalog.resolveSnapshotOrdinal(snapshot, snapshot.ordinalTargets().getFirst())) + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("public-world")); + assertThat(catalog.resolveStableWorld(snapshot, "private-world")) + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("private-world")); + } + + @Test + void numericPublicWorldSelectorIsRejectedBeforeReadingWorldAuthority() { + AtomicInteger supplierCalls = new AtomicInteger(); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + supplierCalls.incrementAndGet(); + throw new AssertionError("numeric selectors must not read world authority"); + }); + + assertThat(catalog.resolvePublicWorld("1")).isEmpty(); + assertThat(supplierCalls).hasValue(0); + } + + @Test + void resolvesWorldFromOneListSnapshotWithoutReinterpretingItsOrdinal() { + AtomicInteger supplierCalls = new AtomicInteger(); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + supplierCalls.incrementAndGet(); + return List.of(worldWithTargetRealm("demo", true)); + }); + + GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.readDiscoverySnapshot(); + assertThat(supplierCalls).hasValue(1); + assertThat(catalog.resolveSnapshotOrdinal(snapshot, snapshot.ordinalTargets().getFirst())) + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("demo")); + assertThat(supplierCalls).hasValue(1); + } + + private static GameplayWorldCatalog.RealmView realm(String slug, boolean publicProduction) { + return new GameplayWorldCatalog.RealmView( + slug, slug, 7L, 11L, 1L, true, publicProduction, false, "SHARED", "ALLOW_NEW"); + } } 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 ccaa28bfe0..710a4c6190 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 @@ -46,19 +46,35 @@ void helpWhoTopicExplainsGameplayOnlyScope() { .get(0) .text() .contains("List currently connected players in this game instance.")); - assertTrue(result.outputs().get(0).text().contains("Gods appear first, then players.")); + assertTrue( + result + .outputs() + .get(0) + .text() + .contains( + "Connected users are currently classified as players; " + + "gameplay-grant roles are not yet shown.")); assertTrue(result.outputs().get(0).text().contains("You must already be in-world with PLAY.")); } @Test - void characterHelpUsesNamesRatherThanUnsupportedListNumbers() { + void characterHelpMatchesCurrentBrowseAndSelectorSupport() { for (String topic : List.of("CHARS", "PLAY")) { TextCommandInterpretationResult result = handler.handle(new TextCommand(TextCommandType.HELP, List.of(topic), "HELP " + topic)); assertTrue(result.commandResult().accepted()); - assertTrue(result.outputs().get(0).text().contains("character name")); - assertTrue(result.outputs().get(0).text().contains("list number")); + String helpText = result.outputs().get(0).text(); + if (topic.equals("CHARS")) { + assertTrue(helpText.contains("Character browsing is currently unavailable.")); + assertTrue(helpText.contains("with a known character.")); + assertFalse(helpText.contains("list number")); + } else { + assertTrue(helpText.contains("Character browsing is currently unavailable")); + assertTrue(helpText.contains("use a known character name, not a list number")); + assertFalse(helpText.contains("shown by CHARS")); + assertFalse(helpText.contains("List visible characters")); + } } } @@ -85,6 +101,20 @@ void helpJoinExplainsTheExplicitPublicMembershipStep() { assertFalse(result.outputs().get(0).text().contains("CHARS and PLAY")); } + @Test + void characterSelectionHelpDoesNotAdvertiseUnavailableBrowsing() { + for (String topic : List.of("realms", "chars")) { + TextCommandInterpretationResult result = + handler.handle(new TextCommand(TextCommandType.HELP, List.of(topic), "HELP " + topic)); + + assertTrue(result.commandResult().accepted()); + assertTrue( + result.outputs().get(0).text().contains("Character browsing is currently unavailable")); + assertFalse(result.outputs().get(0).text().contains("List visible characters")); + assertTrue(result.outputs().get(0).text().contains("known character")); + } + } + @Test void helpFriendsTopicExplainsVisibilityReadAndWriteSurface() { TextCommandInterpretationResult result = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index e0bc1e530d..7db0e2094a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -1733,4 +1733,171 @@ private void stubSessionContext(SessionContext context) { when(sessionContextService.findByTenantAndSessionId(context.tenantId(), context.sessionId())) .thenReturn(Optional.of(context)); } + + @Test + void credentialLoginPreservesCurrentBootstrapTargetButDropsSubjectBoundConnectScope() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); + GameInstance instance = buildInstance(1L, 22L, 77L); + stubSessionContext( + new SessionContext( + 1L, + 22L, + 0L, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 3L, + "SHARED", + "subject-99-scope", + "subject-99-request")); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 3L))); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate("other@example.com", "swordfish")) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertTrue(result.commandResult().accepted()); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(captor.capture()); + SessionContext saved = captor.getValue(); + assertEquals(99L, saved.accountId()); + assertEquals(1L, saved.bootstrapGameInstanceId()); + assertEquals("demo", saved.worldSlug()); + assertEquals("production", saved.realmSlug()); + assertEquals(3L, saved.pointerVersion()); + assertEquals("SHARED", saved.playableStateScope()); + assertNull(saved.connectScopeId()); + assertNull(saved.connectRequestId()); + assertEquals(0L, saved.characterId()); + assertEquals(0L, saved.gameInstanceId()); + } + + @Test + void credentialLoginDropsStaleBootstrapTargetAndSubjectBoundConnectScope() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); + GameInstance instance = buildInstance(1L, 22L, 77L); + stubSessionContext( + new SessionContext( + 1L, + 22L, + 0L, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 3L, + "SHARED", + "subject-99-scope", + "subject-99-request")); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate("other@example.com", "swordfish")) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertTrue(result.commandResult().accepted()); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(captor.capture()); + SessionContext saved = captor.getValue(); + assertEquals(99L, saved.accountId()); + assertEquals(1L, saved.bootstrapGameInstanceId()); + assertNull(saved.worldSlug()); + assertNull(saved.realmSlug()); + assertEquals(0L, saved.pointerVersion()); + assertNull(saved.playableStateScope()); + assertNull(saved.connectScopeId()); + assertNull(saved.connectRequestId()); + assertEquals(0L, saved.characterId()); + assertEquals(0L, saved.gameInstanceId()); + } + + @Test + void verifiedConnectForDifferentTenantClearsPriorBindingWithoutReusingItsBootstrapState() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext prior = + new SessionContext( + 1L, + 33L, + 77L, + "old@example.com", + 88L, + "Sora", + 2L, + "R-2045", + "old-jwt", + "en-NZ", + 2L, + "old-world", + "old-realm", + 1L, + "SHARED", + "old-scope", + "old-request"); + stubSessionContext(prior); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) + .thenReturn(List.of(pointer("old-world", "old-realm", 33L, 2L, 1L))); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn( + Optional.of( + new FirstPartyConnectContext( + 77L, + 22L, + "demo", + "production", + 1L, + 1L, + "new-scope", + "jti-1", + "new-request", + "gateway-1"))); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 99L))); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertTrue(result.commandResult().accepted()); + ArgumentCaptor saved = ArgumentCaptor.forClass(SessionContext.class); + InOrder inOrder = Mockito.inOrder(gameplayPresenceLifecycleService, sessionContextService); + inOrder + .verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(prior, "LOGIN_TENANT_CHANGED"); + inOrder.verify(sessionContextService).save(saved.capture()); + assertEquals(22L, saved.getValue().tenantId()); + assertEquals(77L, saved.getValue().accountId()); + assertEquals("first-party:77", saved.getValue().loginName()); + assertNull(saved.getValue().jwt()); + assertEquals(0L, saved.getValue().characterId()); + assertEquals(0L, saved.getValue().gameInstanceId()); + assertEquals(1L, saved.getValue().bootstrapGameInstanceId()); + assertNull(saved.getValue().worldSlug()); + assertNull(saved.getValue().realmSlug()); + assertEquals(0L, saved.getValue().pointerVersion()); + assertNull(saved.getValue().playableStateScope()); + assertNull(saved.getValue().connectScopeId()); + assertNull(saved.getValue().connectRequestId()); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 02c5950e90..a61486b5d8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; +import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; @@ -44,6 +45,7 @@ import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -198,6 +200,7 @@ void playPromotesSessionIntoGameplay() { handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "play demo")); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isFalse(); assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); Mockito.verify(sessionContextService) .save( @@ -674,6 +677,125 @@ void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { scriptEventPublisher); } + @Test + void publicNumericPlayIgnoresPointerChangesToDeniedPrivateRealms() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) + .thenReturn(Optional.empty()); + GameplayCatalogProperties.World demoWorld = gameplayCatalogProperties.getWorlds().getFirst(); + GameplayCatalogProperties.Realm hiddenPrivateRealm = + realm("vault", "Private Vault", 22L, 99L, true, false); + hiddenPrivateRealm.setPublicProductionRealm(false); + List demoRealms = new ArrayList<>(demoWorld.getRealms()); + demoRealms.add(hiddenPrivateRealm); + demoWorld.setRealms(demoRealms); + GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); + List responseRealms = + world.realms().stream() + .filter(GameplayWorldCatalog.RealmView::publicProductionRealm) + .toList(); + retainRealmSnapshot(context, "demo", world, responseRealms); + + hiddenPrivateRealm.setPointerVersion(2L); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "1", "demo"), "PLAY demo 1 demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); + Mockito.verify(sessionContextService).save(Mockito.any()); + } + + @Test + void numericPlayRealmRejectsChangedTargetThatWasShownToTheCaller() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayCatalogProperties.World demoWorld = gameplayCatalogProperties.getWorlds().getFirst(); + GameplayCatalogProperties.Realm shownPrivateRealm = + realm("vault", "Private Vault", 22L, 99L, true, false); + shownPrivateRealm.setPublicProductionRealm(false); + List demoRealms = new ArrayList<>(demoWorld.getRealms()); + demoRealms.add(shownPrivateRealm); + demoWorld.setRealms(demoRealms); + GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); + retainRealmSnapshot(context, "demo", world, world.realms()); + shownPrivateRealm.setPointerVersion(2L); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "2", "demo"), "PLAY demo 2 demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("SELECTION_STALE"); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void numericPlayStillDeniesWhenSelectedPrivateGrantHasBeenRevoked() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayCatalogProperties.World demoWorld = gameplayCatalogProperties.getWorlds().getFirst(); + GameplayCatalogProperties.Realm privateRealm = + realm("preview", "Preview Realm", 22L, 99L, true, true); + List demoRealms = new ArrayList<>(demoWorld.getRealms()); + demoRealms.add(privateRealm); + demoWorld.setRealms(demoRealms); + GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); + retainRealmSnapshot( + context, + "demo", + world, + world.realms().stream().filter(realm -> realm.slug().equals("preview")).toList()); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("preview"), + Mockito.anyString())) + .thenReturn( + validGrant("123", "22", "demo", "preview").toBuilder().setGranted(false).build()); + + PlayCommandHandlingResult denied = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "1", "Emberline"), + "PLAY demo 1 Emberline", + null, + new TextCommandPayload.PlayRequest("demo", "1", "Emberline"))); + PlayCommandHandlingResult unknown = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "unlisted", "Emberline"), + "PLAY demo unlisted Emberline", + null, + new TextCommandPayload.PlayRequest("demo", "unlisted", "Emberline"))); + + assertHiddenRealmDenialMatchesUnknownSelection(denied, unknown, "preview"); + Mockito.verify(accountClient, Mockito.times(1)) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("demo"), + Mockito.eq("preview"), + Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + verifyNoGameplayBindingSideEffects(); + } + @Test void numericPlayRealmUsesTenantQualifiedSnapshotForDuplicateWorldSlug() { SessionContext context = @@ -2064,7 +2186,17 @@ void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); assertThat(result.commandResult().errorMessage()) .isEqualTo( - "Selection required. Use PLAY sandbox preview or browse CHARS sandbox preview first."); + "Selection required. Use PLAY sandbox preview with a known character; character browsing is currently unavailable."); + assertThat(result.commandResult().errorMessage()).doesNotContain("CHARS"); + TextPlayerOutputRenderer renderer = new TextPlayerOutputRenderer(new PresentationProperties()); + assertThat(renderer.render(result.outputs().getFirst(), "fr")) + .isEqualTo( + "ERROR PLAY_SELECTION_REQUIRED Sélection requise. Utilisez PLAY sandbox preview avec un personnage connu ; la consultation des personnages n’est pas disponible actuellement."); + String fallback = renderer.render(result.outputs().getFirst(), "de"); + assertThat(fallback) + .isEqualTo( + "ERROR PLAY_SELECTION_REQUIRED Selection required. Use PLAY sandbox preview with a known character; character browsing is currently unavailable."); + assertThat(fallback).doesNotContain("CHARS"); } @Test @@ -2725,8 +2857,9 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } - @Test - void playInvisibleRealmWithNonAuthorityGrantClearsBinding() { + @ParameterizedTest + @ValueSource(strings = {"PERMISSION_DENIED", "FAILED_PRECONDITION"}) + void playInvisibleRealmWithNonAuthorityGrantClearsBinding(String errorCode) { markPreviewRealmInvisible(); SessionContext context = previewRealmContext(); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -2740,7 +2873,7 @@ void playInvisibleRealmWithNonAuthorityGrantClearsBinding() { GetRealmAccessGrantForRuntimeResponse.newBuilder() .setError( net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("PERMISSION_DENIED") + .setCode(errorCode) .setMessage("grant denied") .build()) .build()); @@ -2808,6 +2941,35 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } + @Test + void playMembershipFailedPreconditionIsRetryableAndPreservesBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("caller/target authority unavailable") + .build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoin(false, "MISSING", 0L, 0L); @@ -3331,9 +3493,24 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { } @Test - void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { + void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "demo", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -3342,6 +3519,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isTrue(); assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); Mockito.verify(sessionContextService) .save( @@ -3368,7 +3546,10 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { "reason", "stale_or_missing_context") .count()) - .isEqualTo(0.0); + .isEqualTo(1.0); + Mockito.verify(sessionAuthenticationService).resolveByGameplayIdentity(22L, 1L, 7001L); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( @@ -3410,6 +3591,98 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { "play-spawn:1:1:7001:1"); } + @Test + void roomlessRetainedActorMissingFromRosterCannotBeSilentlyReplaced() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + } + + @Test + void roomlessRetainedActorMayChangeThroughExplicitCharacterSelection() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7002L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "production", "Sora"), + "PLAY demo production Sora")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isFalse(); + Mockito.verify(sessionContextService) + .save( + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7002L, + "Sora", + 1L, + gameLogicProperties.getDefaultRoomId(), + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED")); + } + private static String joinedOutputText(List outputs) { return outputs.stream() .map(PlayerOutput::text) @@ -3509,6 +3782,25 @@ private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } + private void retainRealmSnapshot( + SessionContext context, + String worldSelector, + GameplayWorldCatalog.WorldView world, + List responseRealms) { + long tenantId = world.realms().getFirst().tenantId(); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + worldCatalog.realmDiscoverySnapshot(world, responseRealms); + connectScopeSessionStore.replaceRealmSnapshot( + context, + worldSelector, + tenantId, + world.slug(), + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + List.of(), + Instant.now()); + } + private void addNonPublicRealmToPublicDemoWorld(boolean visible) { GameplayCatalogProperties.Realm hiddenRealm = realm("invite-only", "Invite-only Realm", 22L, 51L, visible, true); @@ -3689,8 +3981,7 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); WorldsCommandHandler worldsCommandHandler = - new WorldsCommandHandler( - worldCatalog, entityManagementClient, accountClient, connectScopeSessionStore); + new WorldsCommandHandler(worldCatalog, accountClient, connectScopeSessionStore); assertThat(worldsCommandHandler.browseRealms(resolvedContext, "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); WorldsTextCommandDispatchHandler worldsDispatchHandler = @@ -3795,7 +4086,7 @@ private void verifyNoGameplayBindingSideEffects() { private void assertDemoCharacterSelectionRequired(PlayCommandHandlingResult result) { String expectedMessage = - "Selection required. Use PLAY demo or browse CHARS demo first."; + "Selection required. Use PLAY demo with a known character; character browsing is currently unavailable."; assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); @@ -3806,10 +4097,8 @@ private void assertDemoCharacterSelectionRequired(PlayCommandHandlingResult resu assertThat(error.message()).isEqualTo(expectedMessage); assertThat(error.messageKey()).isEqualTo("error.play.character-selection-required"); assertThat(error.arguments()) - .containsEntry("worldSlug", "demo") - .containsEntry("realmSlug", "production") - .containsEntry("playUsage", "PLAY demo ") - .containsEntry("charsUsage", "CHARS demo"); + .containsOnlyKeys("playUsage") + .containsEntry("playUsage", "PLAY demo "); } private static GameplayCommand command(String commandId, String commandName, String commandText) { @@ -3819,4 +4108,351 @@ private static GameplayCommand command(String commandId, String commandName, Str gameplayCommand.setCommandText(commandText); return gameplayCommand; } + + @Test + void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { + GameplayCatalogProperties.Realm selectedRealm = + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(0); + selectedRealm.setTenantId(23L); + selectedRealm.setGameInstanceId(7001L); + selectedRealm.setPublicProductionRealm(true); + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setTenantId(23L); + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 2L, + "R-1", + "jwt-token", + null, + 2L, + "sandbox", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.eq("23"), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("23") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("INACTIVE") + .setMembershipVersion(2L) + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.eq("23"), Mockito.anyString())) + .thenReturn( + net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("23") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "production", "Emberline"), + "PLAY sandbox production Emberline")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + + @Test + void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Mockito.doReturn( + roster(actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED))) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "preview", "Emberline"), + "PLAY sandbox preview Emberline")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); + order + .verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + order + .verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("sandbox"), + Mockito.eq("preview"), + Mockito.anyString()); + order + .verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + order + .verify(entityManagementClient) + .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + @Test + void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertDemoCharacterSelectionRequired(result); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsAnotherAccountsActorEvenWhenNameMatches() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Character foreign = + actorForTenant("22", "7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .toBuilder() + .setAccountId("999") + .build(); + Mockito.doReturn(roster(foreign)) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "production", "Emberline"), + "PLAY sandbox production Emberline")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @Test + void playRejectsEntityRosterErrorWithoutBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Mockito.doReturn( + ListCharactersByAccountResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) + .build()) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @Test + void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertDemoCharacterSelectionRequired(result); + verifyNoGameplayBindingSideEffects(); + Mockito.verify(entityManagementClient, never()) + .findCharacterByName( + Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); + } + + @ParameterizedTest + @ValueSource(strings = {"tenant", "scope"}) + void playRejectsRosterRowsOutsideSelectedTenantOrScope(String mismatch) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Character valid = actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Character mismatched = + "tenant".equals(mismatch) + ? valid.toBuilder().setTenantId("23").build() + : valid.toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .build(); + stubOwnedRoster("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, mismatched); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @Test + void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-7", + "jwt-token", + null, + 0L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + Mockito.verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + } + + @Test + void playEntitlementCallerTargetPreconditionPreservesExistingBinding() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt-token", + "en", + 0L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage( + "This request cannot establish an authorized caller and target binding") + .build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_MESSAGE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.entitlement-unavailable"); + assertThat(context.hasGameplayBinding()).isTrue(); + assertThat(meterRegistry.find("gamesession.session.resume_denied").counters()).isEmpty(); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(moderationPolicyClient, never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong()); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verifyNoInteractions(scriptEventPublisher); + } + + private void assertIdentityUnavailableWithoutMutation(PlayCommandHandlingResult result) { + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, never()) + .publishCommandEvent(Mockito.any(), Mockito.any(GameplayCommand.class)); + Mockito.verify(scriptEventPublisher, never()) + .publishSpawnEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + } + + private void stubOwnedRoster( + String gameInstanceId, PlayableStateScope scope, Character... characters) { + Mockito.doReturn(roster(characters)) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", gameInstanceId, scope); + } + + private static ListCharactersByAccountResponse roster(Character... characters) { + return ListCharactersByAccountResponse.newBuilder() + .addAllCharacters(List.of(characters)) + .build(); + } + + private static Character actor(String id, String name, PlayableStateScope scope) { + return actorForTenant("22", id, name, scope); + } + + private static Character actorForTenant( + String tenantId, String id, String name, PlayableStateScope scope) { + return Character.newBuilder() + .setId(id) + .setTenantId(tenantId) + .setAccountId("123") + .setName(name) + .setPlayableStateScope(scope) + .build(); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index a39db7d5e3..cdb767c3b2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -60,6 +60,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceActivityResolver; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; @@ -127,8 +128,9 @@ class SessionResumptionFlowTest { private final HelpCommandHandler helpHandler = new HelpCommandHandler(); private final CommunicationCommandHandler communicationHandler = Mockito.mock(CommunicationCommandHandler.class); - private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L)); + private final JwtUtil gameplayJwtUtil = + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L); + private final GameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, @@ -297,7 +299,7 @@ void setUp() { connectScopeSessionStore); worldsHandler = new WorldsCommandHandler( - worldCatalog, entityManagementClient, accountClient, connectScopeSessionStore); + worldCatalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); interpreter = @@ -402,16 +404,8 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { verify(accountRecentPresenceService) .recordDisconnect(1L, AccountRecentPresenceDisposition.TAKEOVER); - verify(scriptEventPublisher) - .publishRegionExitEvent( - Mockito.argThat( - context -> - context.sessionId() == 1L - && context.gameInstanceId() == 1L - && context.characterId() == 7001L - && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("disconnect:takeover:1:1:7001"), - Mockito.eq("TAKEOVER")); + verify(scriptEventPublisher, Mockito.never()) + .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); assertEquals(1.0, meterRegistry.counter("gamesession.session.takeover").count()); assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); } @@ -422,6 +416,8 @@ void logoutFailsClosedWithoutChangingSessionOrPresence() { assertTrue(firstLogin.commandResult().accepted()); TextCommandInterpretationResult firstPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertTrue(firstPlay.commandResult().accepted()); + SessionContext sessionBeforeLogout = + sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow(); Mockito.clearInvocations(scriptEventPublisher); TextCommandInterpretationResult logout = interpreter.interpret("1", "LOGOUT", false); @@ -430,7 +426,8 @@ void logoutFailsClosedWithoutChangingSessionOrPresence() { assertEquals( "Logout is temporarily unavailable. Please try again.", logout.commandResult().errorMessage()); - assertTrue(sessionContextService.findByTenantAndSessionId(22L, 1L).isPresent()); + assertEquals( + sessionBeforeLogout, sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow()); assertTrue( gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() .anyMatch(presence -> presence.sessionId() == 1L)); @@ -442,6 +439,17 @@ void logoutFailsClosedWithoutChangingSessionOrPresence() { .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); Mockito.verify(firstPartyConnectContextRegistry, Mockito.never()).unregister(1L); Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); + + TextCommandInterpretationResult secondLogin = interpreter.interpret("2", LOGIN_PAYLOAD, false); + assertTrue(secondLogin.commandResult().accepted()); + assertEquals( + sessionBeforeLogout, sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow()); + assertTrue(sessionContextService.findByTenantAndSessionId(22L, 2L).isPresent()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(presence -> presence.sessionId() == 1L)); + assertEquals(0.0, meterRegistry.counter("gamesession.session.takeover").count()); + assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); } @Test @@ -574,9 +582,17 @@ void activeGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() { assertFalse(lookAfterCutover.commandResult().accepted()); assertEquals("PLAY_REQUIRED", lookAfterCutover.commandResult().errorCode()); + Mockito.clearInvocations(entityManagementClient); TextCommandInterpretationResult charsAfterCutover = interpreter.interpret("1", "CHARS demo", false); - assertTrue(charsAfterCutover.commandResult().accepted()); + assertFalse(charsAfterCutover.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", charsAfterCutover.commandResult().errorCode()); + verify(entityManagementClient, Mockito.never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.class)); } @Test @@ -771,4 +787,76 @@ private boolean hasGameplayIdentity(SessionContext context) { return context.gameInstanceId() > 0 && context.characterId() > 0; } } + + @Test + void reconnectPresenceRemainsPlayerForPriorTenantRoleClaims() { + String tenantAdminJwt = + gameplayJwtUtil.generateToken( + "77", + Map.of( + "accountId", + "77", + "scopedRoles", + Map.of("22", List.of("tenantAdmin", "moderator")))); + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAuthToken(tenantAdminJwt) + .setAccountId("77") + .build()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", LOOK_PAYLOAD, false).commandResult().accepted()); + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + assertEquals(1.0, meterRegistry.counter("gamesession.session.resume").count()); + } + + @Test + void unavailableAccountMembershipEvidenceLeavesReconnectPresenceAsPlayer() { + String tenantAdminJwt = + gameplayJwtUtil.generateToken( + "77", Map.of("accountId", "77", "scopedRoles", Map.of("22", List.of("tenantAdmin")))); + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAuthToken(tenantAdminJwt) + .setAccountId("77") + .build()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE") + .setMessage("runtime authority unavailable") + .build()) + .build()); + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + + TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); + + assertFalse(deniedPlay.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", deniedPlay.commandResult().errorCode()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .allMatch(presence -> presence.role() == GameplayPresenceRole.PLAYER)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index c638608314..4896349e6d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -28,7 +28,6 @@ import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomResponse; import net.firedevops.firemud.entitymanagement.v1.EquipmentItem; @@ -145,8 +144,7 @@ class TextCommandInterpreterTest { PresentationProperties.ColorMode.NONE, false, new PresentationProperties.Prompt(true, true, 150L))); - private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L)); + private final GameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, @@ -436,8 +434,7 @@ void setUp() { .build()) .build()); WorldsCommandHandler worldsHandler = - new WorldsCommandHandler( - worldCatalog, entityManagementClient, accountClient, connectScopeSessionStore); + new WorldsCommandHandler(worldCatalog, accountClient, connectScopeSessionStore); LookResult lookResult = LookResult.newBuilder() @@ -586,17 +583,24 @@ void realmsBrowseFailsClosedWhenScopeAuthorityIsUnavailable() { } @Test - void charsAreVisibleAfterLogin() { + void charsAreNotDisclosedWithoutTypedEntityRosterProof() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "CHARS demo", false); - assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("CHARS demo", interpretation).contains("1) demo [lvl 12]")); - assertTrue( + assertFalse(interpretation.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", interpretation.commandResult().errorCode()); + assertFalse(renderedResponse("CHARS demo", interpretation).contains("Live Realm")); + assertFalse( renderedResponse("CHARS demo", interpretation) .contains("Realm state: shared, creation: allow_new")); + verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 3e893d2545..486f601a38 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -26,7 +26,7 @@ class WhoCommandHandlerTest { @Test void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); @@ -49,20 +49,15 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { } @Test - void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + void whoPresentsJwtRoleClaimSessionsAsPlayersWithoutGrantEvidence() { + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); String godJwt = jwtUtil.generateToken( "1", java.util.Map.of( - "accountId", - "1", - "globalRoles", - java.util.List.of("platformAdmin"), - "scopedRoles", - java.util.Map.of())); + "accountId", "1", "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); gameplayPresenceService.registerConnected( new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt)); @@ -88,12 +83,12 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); assertThat(result.commandResult().accepted()).isTrue(); - assertThat(render(result)).isEqualTo("Gods [2]: Aster, Dara\nPlayers [2]: Ben, Cara"); + assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [4]: Aster, Ben, Cara, Dara"); } @Test void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); @@ -114,7 +109,7 @@ void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { @Test void whoAnnotatesExplicitAndAutoAfkPlayers() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); GameplayPresenceActivityResolver resolver = Mockito.mock(GameplayPresenceActivityResolver.class); WhoCommandHandler handler = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index d1616ae322..86a396a33e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2,10 +2,8 @@ import static org.assertj.core.api.Assertions.assertThat; -import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -18,11 +16,8 @@ import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; +import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; @@ -42,14 +37,13 @@ class WorldsCommandHandlerTest { UUID.fromString("00000000-0000-0000-0000-000000000001"); private static final UUID ADMISSION_NAMESPACE_ID = UUID.fromString("00000000-0000-0000-0000-000000000002"); - private final EntityManagementClient entityManagementClient = - Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); private final WorldsCommandHandler handler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); @BeforeEach void setUp() { @@ -90,6 +84,191 @@ void browseRealmsReturnsStructuredRealmList() { assertThat(response.realms().get(0).characterCreationPolicy()).isEqualTo("ALLOW_NEW"); } + @Test + void publicRealmSelectionsIgnorePointerChangesToDeniedPrivateRealms() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); + GameplayCatalogProperties.Realm privateRealm = + properties.getWorlds().getFirst().getRealms().get(1); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + privateRealm.setPointerVersion(2L); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", null)) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verify(accountClient, Mockito.times(1)) + .issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void numericRealmSnapshotRejectsChangedVisibleTarget() { + GameplayCatalogProperties properties = publicProductionProperties(); + GameplayCatalogProperties.Realm publicRealm = + properties.getWorlds().getFirst().getRealms().getFirst(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + publicRealm.setPointerVersion(2L); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); + } + + @Test + void privateRealmPointerChangeCannotEnterThePublicRealmSnapshot() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); + GameplayCatalogProperties.Realm privateRealm = + properties.getWorlds().getFirst().getRealms().get(1); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> { + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::ordinal) + .containsExactly(1); + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + }); + privateRealm.setPointerVersion(2L); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidRealm("demo")); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + @Test + void joinKeepsTheRetainedPublicScopeWhenDeniedPrivatePointerChanges() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); + GameplayCatalogProperties.Realm privateRealm = + properties.getWorlds().getFirst().getRealms().get(1); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + Mockito.when( + accountClient.joinPublicProductionMembership( + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) + .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + privateRealm.setPointerVersion(2L); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); + Mockito.verify(accountClient, Mockito.times(1)) + .issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.times(1)) + .joinPublicProductionMembership( + Mockito.any(), + Mockito.eq("scope-public"), + Mockito.anyString(), + Mockito.any(Instant.class)); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + @Test + void joinRejectsStaleRealmSnapshotBeforeCallingAccount() { + GameplayCatalogProperties properties = publicProductionProperties(); + GameplayCatalogProperties.Realm publicRealm = + properties.getWorlds().getFirst().getRealms().getFirst(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + publicRealm.setPointerVersion(2L); + Mockito.clearInvocations(accountClient); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient); + } + + @Test + void joinMapsRealmSnapshotRevalidationOutageToAuthUnavailableWithoutAccountCall() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot pointer = + new GameplayAdmissionPointerSnapshot( + "demo", + "demo", + "production", + "production", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.fromString("00000000-0000-0000-0000-000000000001"), + UUID.fromString("00000000-0000-0000-0000-000000000002")); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(pointer)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + GameplayWorldCatalog catalog = Mockito.spy(new GameplayWorldCatalog(authorityService)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + Mockito.doThrow( + new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "pointer authority unavailable")) + .when(catalog) + .revalidateRealmDiscoverySnapshot(Mockito.any(), Mockito.anyList()); + Mockito.clearInvocations(accountClient); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); + } + @Test void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { GameplayWorldCatalog.RealmView realmA = @@ -132,7 +311,6 @@ void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -141,20 +319,23 @@ void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { assertThat(localHandler.browseRealms("7", authenticatedSession(), "1")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test - void sameWorldSlugAcrossTenantsKeepsDistinctOrdinalsAndJoinTargets() { + void ambiguousWorldSlugRejectsBareSelectionWhileBoundOrdinalsKeepTenantTargets() { GameplayWorldCatalog.WorldView worldA = worldView("demo", "Tenant A", 22L, 1L); GameplayWorldCatalog.WorldView worldB = worldView("DEMO", "Tenant B", 33L, 2L); AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) - .thenReturn( - IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId("scope") - .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) - .build()); + .thenAnswer( + invocation -> { + DirectTextConnectScopeTarget target = invocation.getArgument(1); + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("scope-" + target.tenantId()) + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build(); + }); Mockito.when( accountClient.joinPublicProductionMembership( Mockito.any(), @@ -165,43 +346,60 @@ void sameWorldSlugAcrossTenantsKeepsDistinctOrdinalsAndJoinTargets() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldA, worldB)), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); - WorldsViewOutput worlds = localHandler.browseView("7", Optional.of(authenticatedSession())); - assertThat(worlds.worlds()) - .extracting(WorldsViewOutput.WorldEntry::ordinal) - .containsExactly(1, 2); - assertThat(worlds.worlds()) - .extracting(WorldsViewOutput.WorldEntry::slug) - .containsExactly("demo", "DEMO"); - assertThat(localHandler.browseRealms("7", authenticatedSession(), "1")) - .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - assertThat(localHandler.browseRealms("7", authenticatedSession(), "2")) - .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + WorldsViewOutput worldSnapshot = + localHandler.browseView("7", Optional.of(authenticatedSession())); + assertThat(worldSnapshot.worlds()) + .extracting(WorldsViewOutput.WorldEntry::displayName) + .containsExactly("Tenant A", "Tenant B"); - Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); Mockito.verifyNoInteractions(accountClient); + WorldsCommandHandler.RealmBrowseResult tenantARealms = + localHandler.browseRealms("7", authenticatedSession(), "1"); + WorldsCommandHandler.RealmBrowseResult tenantBRealms = + localHandler.browseRealms("7", authenticatedSession(), "2"); + assertThat(tenantARealms).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(tenantBRealms).isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "1")) .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "2")) .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); + Mockito.verify(accountClient) + .issueDirectTextConnectScope( + Mockito.argThat(context -> context.getTenantId().equals("22")), + Mockito.argThat( + target -> + target.tenantId().equals("22") + && target.worldSlug().equals("demo") + && target.realmSlug().equals("production") + && target.gameInstanceId().equals("1"))); + Mockito.verify(accountClient) + .issueDirectTextConnectScope( + Mockito.argThat(context -> context.getTenantId().equals("33")), + Mockito.argThat( + target -> + target.tenantId().equals("33") + && target.worldSlug().equals("DEMO") + && target.realmSlug().equals("production") + && target.gameInstanceId().equals("2"))); Mockito.verify(accountClient) .joinPublicProductionMembership( Mockito.argThat(context -> context.getTenantId().equals("22")), - Mockito.eq("scope"), + Mockito.eq("scope-22"), Mockito.anyString(), Mockito.any(Instant.class)); Mockito.verify(accountClient) .joinPublicProductionMembership( Mockito.argThat(context -> context.getTenantId().equals("33")), - Mockito.eq("scope"), + Mockito.eq("scope-33"), Mockito.anyString(), Mockito.any(Instant.class)); } @@ -218,7 +416,6 @@ void joinRejectsUnboundOrdinalBeforeCallingAccount() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -251,7 +448,6 @@ void joinForwardsTheRetainedAccountScopeExpiry() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -316,7 +512,6 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -336,7 +531,7 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { } @Test - void numericRealmSnapshotIgnoresPrivateReorderingButRejectsPublicRoutingChanges() { + void numericRealmSnapshotIgnoresPrivateReorderingAndRejectsPublicRoutingChanges() { GameplayWorldCatalog.RealmView production = new GameplayWorldCatalog.RealmView( "production", @@ -382,46 +577,34 @@ void numericRealmSnapshotIgnoresPrivateReorderingButRejectsPublicRoutingChanges( accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = new WorldsCommandHandler( - GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, - accountClient, - scopeStore); + GameplayWorldCatalog.forWorldSupplier(worlds::get), accountClient, scopeStore); assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) .isInstanceOfSatisfying( WorldsCommandHandler.RealmBrowseResult.Success.class, - success -> - assertThat(success.output().realms()) - .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) - .containsExactly("production")); - Mockito.clearInvocations(accountClient, entityManagementClient); + success -> { + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::ordinal) + .containsExactly(1); + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + }); + Mockito.clearInvocations(accountClient); worlds.set( List.of( new GameplayWorldCatalog.WorldView( "demo", "Demo World", List.of(preview, production)))); assertThat(localHandler.browseCharacters("7", authenticatedSession(), "demo", "1")) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient); - Mockito.clearInvocations(accountClient, entityManagementClient); + Mockito.clearInvocations(accountClient); GameplayWorldCatalog.RealmView reroutedProduction = new GameplayWorldCatalog.RealmView( production.slug(), @@ -444,12 +627,18 @@ void numericRealmSnapshotIgnoresPrivateReorderingButRejectsPublicRoutingChanges( assertThat(localHandler.browseCharacters("7", authenticatedSession(), "demo", "1")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test void browseRealmsToleratesNullRealmEnums() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); gameplayCatalogProperties .getWorlds() @@ -460,7 +649,8 @@ void browseRealmsToleratesNullRealmEnums() { WorldsCommandHandler localHandler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); RealmBrowseViewOutput response = localHandler.browseRealms("demo").orElseThrow(); @@ -469,50 +659,16 @@ void browseRealmsToleratesNullRealmEnums() { } @Test - void browseCharactersReturnsStructuredCharacterList() { - gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + void browseCharactersFailsClosedForPublicRealmBeforeRosterPolicyProof() { + gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); gameplayCatalogProperties .getWorlds() .getFirst() .getRealms() .getFirst() .setPublicProductionRealm(true); - gameplayCatalogProperties - .getWorlds() - .get(1) - .getRealms() - .getFirst() - .setPublicProductionRealm(false); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) - .thenReturn( - IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId("public-scope") - .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) - .build()); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId("123") - .setName("Emberline") - .setLevel(12) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .build()) - .build()); + stubPublicConnectScope(accountClient, "scope-public"); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = @@ -525,54 +681,13 @@ void browseCharactersReturnsStructuredCharacterList() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(session, "demo", null); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.worldSlug()).isEqualTo("demo"); - assertThat(output.realmSlug()).isEqualTo("production"); - assertThat(output.stateScope()).isEqualTo("SHARED"); - assertThat(output.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); - assertThat(output.characters()).hasSize(1); - assertThat(output.characters().get(0).characterName()).isEqualTo("Emberline"); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - } - - @Test - void browseCharactersFailsClosedWhenNamespaceQualifiedRosterAuthorityIsUnavailable() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .setError( - ErrorDetail.newBuilder() - .setCode("CHARACTER_LIST_UNAVAILABLE") - .setMessage("Character list unavailable")) - .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verifyNoMoreInteractions(accountClient); } @Test - void browseCharactersUsesIsolatedStateRealmRoster() { + void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); gameplayCatalogProperties .getWorlds() @@ -593,362 +708,66 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .getFirst() .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); - addPublicProductionAuthority(gameplayCatalogProperties); AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); - GameplayWorldCatalog catalog = - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); - GameplayWorldCatalog.WorldView selectedWorld = catalog.resolveWorld("demo").orElseThrow(); - GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = - catalog.realmDiscoverySnapshot(selectedWorld, catalog.visibleRealms(selectedWorld)); - DirectTextConnectScopeSessionStore scopeStore = - DirectTextConnectScopeSessionStore.inMemoryForTest(); - scopeStore.replaceRealmSnapshot( - session, - "demo", - 22L, - "demo", - snapshot.catalogFingerprint(), - snapshot.ordinalTargets(), - List.of(), - Instant.now()); - WorldsCommandHandler localHandler = - new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore); - WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(session, "demo", "production"); - assertThat(result) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); - } - - @Test - void browseCharactersRejectsMismatchedOrDuplicateEntityRows() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - net.firedevops.firemud.entitymanagement.v1.Character valid = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId("123") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setName("Emberline") - .build(); - for (net.firedevops.firemud.entitymanagement.v1.Character invalid : - List.of( - valid.toBuilder().setTenantId("23").build(), - valid.toBuilder().setAccountId("456").build(), - valid.toBuilder() - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) - .build(), - valid.toBuilder().clearId().build(), - valid.toBuilder().setId("not-a-number").build(), - valid.toBuilder().setId("0").build(), - valid.toBuilder().setId("-1").build(), - valid.toBuilder().setId("9223372036854775808").build(), - valid.toBuilder().setId("-9223372036854775809").build(), - valid.toBuilder().clearName().build())) { - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder().addCharacters(invalid).build()); - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - } - - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters(valid) - .addCharacters(valid.toBuilder().setId("07001").build()) - .addCharacters(valid.toBuilder().setId("+7001").build()) - .build()); - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient); } @Test void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); - addPublicProductionAuthority(gameplayCatalogProperties); AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), - "demo", - "production"); - - assertThat(result) - .isEqualTo( - WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); - } - - @Test - void browseCharactersReturnsJoinRequiredForPublicNonMemberWithoutReadingEntityRoster() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("JOIN_REQUIRED")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void browseCharactersReturnsJoinRequiredForPublicInactiveMemberWithoutReadingEntityRoster() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(true, false, 3L, 4L, "INACTIVE")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("JOIN_REQUIRED")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void browseCharactersUsesInjectedClockForFreshCallerBoundAuthorityEvidence() { - Instant authorityNow = Instant.parse("2030-05-06T07:08:09Z"); - Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - WorldsCommandHandler localHandler = - authenticatedHandler(properties, accountClient, authorityClock); - List evaluatedAtValues = - List.of( - authorityNow, - authorityNow.minusSeconds(15), - authorityNow.minusSeconds(15).minusNanos(1), - authorityNow.plusNanos(1)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); - - for (int index = 0; index < evaluatedAtValues.size(); index++) { - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - activeMembership().toBuilder() - .setEvaluatedAt(evaluatedAtValues.get(index).toString()) - .build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime( - Mockito.anyString(), Mockito.anyString())) - .thenReturn( - publicEntitlement(true).toBuilder().setEvaluatedAt(authorityNow.toString()).build()); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - if (index < 2) { - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - } else { - assertThat(result) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); - } - } - - for (int index = 0; index < evaluatedAtValues.size(); index++) { - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - activeMembership().toBuilder().setEvaluatedAt(authorityNow.toString()).build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime( - Mockito.anyString(), Mockito.anyString())) - .thenReturn( - publicEntitlement(true).toBuilder() - .setEvaluatedAt(evaluatedAtValues.get(index).toString()) - .build()); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - if (index < 2) { - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - } else { - assertThat(result) - .isEqualTo( - WorldsCommandHandler.CharacterBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); - } - } - } - - @Test - void browseCharactersMapsMalformedRealmDiscoveryPointerToAdmissionPointerUnavailable() { - GameplayCatalogProperties properties = publicProductionProperties(); - GameplayWorldCatalog baseCatalog = TestGameplayWorldCatalogs.fromProperties(properties); - GameplayWorldCatalog.DiscoverySnapshot snapshot = baseCatalog.readDiscoverySnapshot(); - GameplayWorldCatalog catalog = Mockito.spy(baseCatalog); - Mockito.doReturn(snapshot).when(catalog).readDiscoverySnapshot(); - Mockito.doThrow(new GameplayWorldCatalog.AuthorityPointerUnavailableException("malformed")) - .when(catalog) - .readRealmDiscoverySnapshot(Mockito.any(GameplayWorldCatalog.WorldView.class)); - WorldsCommandHandler localHandler = - new WorldsCommandHandler( - catalog, - entityManagementClient, - Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo( - WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); - } - - @Test - void browseCharactersFailsClosedForUnknownPublicMembershipLifecycleWithoutReadingEntityRoster() { - assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "UNKNOWN")); - } - - @Test - void browseCharactersDeniesActivePublicMembershipWithoutAdmissionWithoutReadingEntityRoster() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(true, false, 1L, 1L, "ACTIVE")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo( - WorldsCommandHandler.CharacterBrowseResult.failure( - "PUBLIC_PRODUCTION_ADMISSION_DENIED")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void - browseCharactersFailsClosedForAbsentPublicMembershipWithActiveLifecycleWithoutReadingEntityRoster() { - assertPublicMembershipFailsClosed(publicMembership(false, false, 0L, 0L, "ACTIVE")); - } - - @Test - void - browseCharactersFailsClosedForInactivePublicMembershipWithAdmissionWithoutReadingEntityRoster() { - assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "INACTIVE")); - } - - @Test - void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEntityRoster() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + "demo", + "production"); assertThat(result) .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "PUBLIC_PRODUCTION_ADMISSION_DENIED")); - Mockito.verifyNoInteractions(entityManagementClient); + WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); } @Test - void browseCharactersReturnsUnavailableEntitlementBeforeReadingPublicEntityRoster() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("ENTITLEMENT_UNAVAILABLE") - .setMessage("Entitlement authority unavailable") - .build()) - .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + void browseCharactersMapsMalformedRealmDiscoveryPointerToAdmissionPointerUnavailable() { + GameplayCatalogProperties properties = publicProductionProperties(); + GameplayWorldCatalog baseCatalog = TestGameplayWorldCatalogs.fromProperties(properties); + GameplayWorldCatalog.DiscoverySnapshot snapshot = baseCatalog.readDiscoverySnapshot(); + GameplayWorldCatalog catalog = Mockito.spy(baseCatalog); + Mockito.doReturn(snapshot).when(catalog).readDiscoverySnapshot(); + Mockito.doThrow(new GameplayWorldCatalog.AuthorityPointerUnavailableException("malformed")) + .when(catalog) + .readRealmDiscoverySnapshot(Mockito.any(GameplayWorldCatalog.WorldView.class)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", "production"); assertThat(result) .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure("ENTITLEMENT_UNAVAILABLE")); - Mockito.verifyNoInteractions(entityManagementClient); + WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); } @Test @@ -958,21 +777,13 @@ void privateOnlyCharacterSelectionMatchesUnknownWithoutLegacyAuthorizationReads( properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); addPublicProductionAuthority(properties); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1033,7 +844,7 @@ void legacyAuthorityVariantsNeverExposePrivateOnlyRealm() { .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } } @@ -1041,14 +852,6 @@ void legacyAuthorityVariantsNeverExposePrivateOnlyRealm() { void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString())) - .thenReturn(grant("demo", "playtest", true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult unknownRealm = @@ -1058,11 +861,11 @@ void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) .isEqualTo(unknownRealm); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test - void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoster() { + void browseCharactersRedactsPrivateRealmWithoutAccountOrEntityReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); @@ -1074,11 +877,11 @@ void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoste localHandler.browseCharacters(authenticatedSession(), "preview", "production"); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test - void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { + void browseCharactersRedactsPrivateOnlyWorldWithoutPublicProductionRealm() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); @@ -1091,7 +894,7 @@ void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = - new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore); + new WorldsCommandHandler(catalog, accountClient, scopeStore); assertThat(localHandler.browseCharacters(session, "preview", "unknown")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); @@ -1108,15 +911,12 @@ void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(session, "preview", "production"); - assertThat(result) - .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "ADMISSION_POINTER_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient); } @Test - void browseCharactersRejectsMultiplePublicProductionCardinalityWithExplicitRealm() { + void browseCharactersRedactsNonPublicWorldWithAmbiguousPublicProductionCardinality() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds( List.of(world("demo", 22L, 1L, false), world("alternate", 22L, 2L, false))); @@ -1126,11 +926,8 @@ void browseCharactersRejectsMultiplePublicProductionCardinalityWithExplicitRealm WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - assertThat(result) - .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "ADMISSION_POINTER_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1140,18 +937,23 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads GameplayAdmissionPointerSnapshot pointerA = admissionPointer(1L); GameplayAdmissionPointerSnapshot pointerB = admissionPointer(2L); AtomicInteger pointerReads = new AtomicInteger(); - Mockito.when(authorityService.listPointers()).thenReturn(List.of(pointerA)); + Mockito.when(authorityService.listPointers()) + .thenAnswer( + invocation -> { + pointerReads.incrementAndGet(); + return List.of(pointerA); + }); Mockito.when(authorityService.listPointersByTenant(22L)) .thenAnswer( invocation -> { pointerReads.incrementAndGet(); return List.of(pointerB); }); + AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - entityManagementClient, - Mockito.mock(AccountClient.class), + accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); WorldsCommandHandler.CharacterBrowseResult result = @@ -1160,8 +962,8 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads assertThat(result) .isEqualTo( WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); - assertThat(pointerReads).hasValue(1); - Mockito.verifyNoInteractions(entityManagementClient); + assertThat(pointerReads).hasValue(2); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1232,7 +1034,6 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(incomplete)))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1240,59 +1041,27 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() .isEqualTo( WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); } - Mockito.verifyNoInteractions(accountClient, entityManagementClient); - } - - @Test - void browseCharactersRejectsIncompleteOrStaleEntitlementBeforeReadingRoster() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - GetTenantEntitlementsForRuntimeResponse valid = publicEntitlement(true); - for (GetTenantEntitlementsForRuntimeResponse invalid : - List.of( - valid.toBuilder().setEntitlementVersion(0L).build(), - valid.toBuilder().setTenantBillingSequence(0L).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().minusSeconds(16).toString()).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().plusSeconds(30).toString()).build())) { - Mockito.when( - accountClient.getTenantEntitlementsForRuntime( - Mockito.anyString(), Mockito.anyString())) - .thenReturn(invalid); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); - } - Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test - void browseCharactersRejectsInvalidPublicMembershipBeforeReadingRoster() { + void browseRealmsAndCharactersRedactPrivateOnlySelectorsBeforeAccountReads() { + GameplayCatalogProperties properties = new GameplayCatalogProperties(); + properties.setWorlds(List.of(world("preview", 22L, 2L, false))); + properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); + addPublicProductionAuthority(properties); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - - for (String evaluatedAt : invalidEvaluationTimes()) { - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership().toBuilder().setEvaluatedAt(evaluatedAt).build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); - } - Mockito.verifyNoInteractions(entityManagementClient); + assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient); } @Test - void freshBoundSnapshotKeepsPrivateSelectionRetryableWithoutLegacyAuthority() { + void freshBoundPrivateSelectionFailsClosedWithAuthUnavailableBeforeAccountAccess() { GameplayWorldCatalog.WorldView world = mixedWorld(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); GameplayWorldCatalog catalog = snapshotCatalog(world); @@ -1310,20 +1079,12 @@ void freshBoundSnapshotKeepsPrivateSelectionRetryableWithoutLegacyAuthority() { List.of(), Instant.now()); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant("demo", "preview", true)); WorldsCommandHandler localHandler = - new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore); + new WorldsCommandHandler(catalog, accountClient, scopeStore); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "preview")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1368,13 +1129,12 @@ void staleOrExpiredPrivateSnapshotCannotBindCurrentSameSlugTarget() { Mockito.anyString())) .thenReturn(grant("demo", "preview", true)); WorldsCommandHandler localHandler = - new WorldsCommandHandler( - changingCatalog, entityManagementClient, accountClient, scopeStore); + new WorldsCommandHandler(changingCatalog, accountClient, scopeStore); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "preview")) .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.InvalidRealm("demo")); if (expireSnapshot) { - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } else { Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( @@ -1421,44 +1181,23 @@ void staleOrExpiredPrivateSnapshotCannotBindCurrentSameSlugTarget() { Mockito.anyString()); Mockito.verify(accountClient, Mockito.never()) .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); - Mockito.verifyNoInteractions(entityManagementClient); } } } @Test - void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRoster() { + void browseCharactersWithExplicitPublicRealmFailsClosedBeforeAuthorityOrRosterReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("demo", 22L, 1L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(false) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1501,10 +1240,7 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(properties), - entityManagementClient, - accountClient, - scopeStore); + TestGameplayWorldCatalogs.fromProperties(properties), accountClient, scopeStore); assertThat(localHandler.browseRealms(authenticatedSession(), "public")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -1518,7 +1254,6 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); assertThat(scopeStore.realmsSnapshot(authenticatedSession(), 22L, "public", Instant.now())) .hasValue(publicSnapshot.orElseThrow()); - Mockito.verifyNoInteractions(entityManagementClient); Mockito.verify(accountClient, Mockito.times(1)) .issueDirectTextConnectScope(Mockito.any(), Mockito.any()); Mockito.verify(accountClient, Mockito.never()) @@ -1531,24 +1266,16 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { } @Test - void privateOnlyCharacterSelectorMatchesUnknownDespitePositiveLegacyGrantFixture() { + void privateOnlyCharacterSelectorMatchesUnknownWithoutAccountAuthority() { GameplayCatalogProperties properties = privateOnlyWorldProperties(); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("private-only"), - Mockito.eq("preview"), - Mockito.anyString())) - .thenReturn(grant("private-only", "preview", true)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "preview")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); assertThat(localHandler.browseCharacters(authenticatedSession(), "unknown", "preview")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1575,7 +1302,7 @@ void privateOnlyUnknownAmbiguousAndUnboundRealmSelectorsMatchUnknownWorld() { .isEqualTo(unknownWorld); assertThat(localHandler.browseCharacters(authenticatedSession(), "PRIVATE-ONLY", "1")) .isEqualTo(unknownWorld); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1586,42 +1313,21 @@ void unboundPublicRealmOrdinalRemainsConnectScopeMismatch() { assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test void omittedCharactersIgnoreHiddenPrivateRealmCardinalityForPublicDefault() { AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = authenticatedHandler(publicWorldWithPrivateRealm(), accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", null); - assertThat(result) - .isInstanceOfSatisfying( - WorldsCommandHandler.CharacterBrowseResult.Success.class, - success -> assertThat(success.output().realmSlug()).isEqualTo("production")); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + // The public default does not reveal hidden cardinality, but actor authority remains closed. + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1632,10 +1338,7 @@ void omittedCharactersInPrivateOnlyWorldRemainIndistinguishableFromUnknown() { DirectTextConnectScopeSessionStore.inMemoryForTest(); WorldsCommandHandler localHandler = new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(properties), - entityManagementClient, - accountClient, - scopeStore); + TestGameplayWorldCatalogs.fromProperties(properties), accountClient, scopeStore); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); @@ -1643,7 +1346,7 @@ void omittedCharactersInPrivateOnlyWorldRemainIndistinguishableFromUnknown() { .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "1")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1651,13 +1354,6 @@ void mixedRealmDiscoveryAndOmittedCharacterSelectionKeepOnlyPublicProductionTarg AccountClient accountClient = Mockito.mock(AccountClient.class); DirectTextConnectScopeSessionStore scopeStore = DirectTextConnectScopeSessionStore.inMemoryForTest(); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() @@ -1667,7 +1363,6 @@ void mixedRealmDiscoveryAndOmittedCharacterSelectionKeepOnlyPublicProductionTarg WorldsCommandHandler localHandler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(publicWorldWithPrivateRealm()), - entityManagementClient, accountClient, scopeStore); @@ -1678,25 +1373,10 @@ void mixedRealmDiscoveryAndOmittedCharacterSelectionKeepOnlyPublicProductionTarg assertThat(success.output().realms()) .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) .containsExactly("production")); - Mockito.clearInvocations(accountClient, entityManagementClient); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); - + Mockito.clearInvocations(accountClient); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", null)) - .isInstanceOfSatisfying( - WorldsCommandHandler.CharacterBrowseResult.Success.class, - success -> assertThat(success.output().realmSlug()).isEqualTo("production")); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1800,7 +1480,6 @@ void authenticatedBrowseKeepsPublicScopeAndOrdinalWhileOmittingPrivateMetadata() List.of( new GameplayWorldCatalog.WorldView( "demo", "Demo", List.of(realm, privateRealm)))), - entityManagementClient, accountClient, scopeStore); @@ -1870,7 +1549,6 @@ void authenticatedBrowseCarriesGeneratedRequestIdIntoPublicScopeContext() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1909,7 +1587,6 @@ void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySucces new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1976,10 +1653,7 @@ void joinRejectsRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); localHandler.browseView("7", Optional.of(authenticatedSession())); assertThat(localHandler.browseRealms(authenticatedSession(), "1")) @@ -1993,7 +1667,6 @@ void joinRejectsRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { assertThat(join) .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); Mockito.verifyNoInteractions(accountClient); - Mockito.verifyNoInteractions(entityManagementClient); } @Test @@ -2042,7 +1715,6 @@ void joinRejectsRetainedScopeWhenTenantPublicRealmBecomesAmbiguous() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -2094,7 +1766,7 @@ void authenticatedBrowseFailsClosedWhenPublicProductionRealmIsDuplicatedAcrossWo } @Test - void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { + void crossTenantCollisionSuppressesValidSlugWhenOtherTenantHasAmbiguousPublicCardinality() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); List initialPointers = @@ -2113,10 +1785,7 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -2129,9 +1798,11 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { assertThat(catalog.publicProductionRealmCardinality(22L)) .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); - assertThat(catalog.readDiscoverySnapshot().output().worlds()) - .extracting(WorldsViewOutput.WorldEntry::slug) - .containsExactly("DEMO"); + assertThat(catalog.publicProductionRealmCardinality(33L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.resolvePublicWorldFromAuthoritySnapshot("demo")).isEmpty(); Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "other")) @@ -2141,7 +1812,6 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); Mockito.verifyNoInteractions(accountClient); - Mockito.verifyNoInteractions(entityManagementClient); } @Test @@ -2167,13 +1837,12 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti WorldsCommandHandler localHandler = new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); - Mockito.clearInvocations(accountClient, entityManagementClient); + Mockito.clearInvocations(accountClient); unavailable.set(true); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) @@ -2182,48 +1851,192 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("AUTH_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); Mockito.doReturn(null).when(authorityService).listPointers(); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("AUTH_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); Mockito.doReturn(List.of(authorityPointer("demo", "production", 0L, 1L, true))) .when(authorityService) .listPointers(); - Mockito.clearInvocations(accountClient, entityManagementClient); + Mockito.clearInvocations(accountClient); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) .isEqualTo( WorldsCommandHandler.JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); - Mockito.clearInvocations(accountClient, entityManagementClient); + Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) .isEqualTo( WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verifyNoInteractions(accountClient); + } + + @Test + void publicBrowseDoesNotExposePrivateWorldOrRealmMetadata() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))), + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + AccountClient localAccount = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, localAccount, DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseView().worlds()) + .extracting("slug") + .containsExactly("mixed-world"); + assertThat(localHandler.browseRealms("mixed-world").orElseThrow().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + assertThat(localHandler.browseRealms("private-world")).isEmpty(); + Mockito.verifyNoInteractions(localAccount); + } + + @Test + void charsPrivateOnlyWorldFailsBeforeEntityRead() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + AccountClient localAccount = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, localAccount, DirectTextConnectScopeSessionStore.inMemoryForTest()); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters( + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + "private-world", + null); + + assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); + Mockito.verifyNoInteractions(localAccount); + } + + @Test + void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + ADMISSION_REALM_ID, + ADMISSION_NAMESPACE_ID), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + AccountClient localAccount = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, localAccount, DirectTextConnectScopeSessionStore.inMemoryForTest()); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + + assertThat(localHandler.browseCharacters(context, "mixed-world", "secret")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); + assertThat(localHandler.browseCharacters(context, "mixed-world", "nonexistent")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); + assertThat(localHandler.browseCharacters(context, "mixed-world", "production")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + Mockito.verifyNoInteractions(localAccount); } private WorldsCommandHandler authenticatedHandler( GameplayCatalogProperties properties, AccountClient accountClient) { return new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(properties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); } - private WorldsCommandHandler authenticatedHandler( - GameplayCatalogProperties properties, AccountClient accountClient, Clock clock) { - return new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(properties), - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest(), - clock); + private void stubPublicConnectScope(AccountClient accountClient, String scopeId) { + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scopeId) + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); } private GameplayAdmissionPointerSnapshot authorityPointer( @@ -2352,23 +2165,6 @@ private GameplayCatalogProperties publicWorldWithPrivateRealm() { return properties; } - private void assertPublicMembershipFailsClosed(GetTenantMembershipForRuntimeResponse membership) { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(membership); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("AUTH_UNAVAILABLE")); - Mockito.verifyNoInteractions(entityManagementClient); - } - private void addPublicProductionAuthority(GameplayCatalogProperties properties) { GameplayCatalogProperties.World authority = world("production-authority", 22L, 1L, false); authority.getRealms().getFirst().setPublicProductionRealm(true); @@ -2414,14 +2210,6 @@ private GetTenantEntitlementsForRuntimeResponse publicEntitlement(boolean allowP .build(); } - private GetRealmAccessGrantForRuntimeResponse grant(boolean granted) { - return grant("preview", granted); - } - - private GetRealmAccessGrantForRuntimeResponse grant(String worldSlug, boolean granted) { - return grant(worldSlug, "production", granted); - } - private GetRealmAccessGrantForRuntimeResponse grant( String worldSlug, String realmSlug, boolean granted) { return GetRealmAccessGrantForRuntimeResponse.newBuilder() @@ -2445,13 +2233,6 @@ private GameplayCatalogProperties privateOnlyWorldProperties() { return properties; } - private List invalidEvaluationTimes() { - return List.of( - Instant.now().minusSeconds(16).toString(), - Instant.now().plusSeconds(30).toString(), - "not-an-instant"); - } - private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); @@ -2470,4 +2251,45 @@ private static GameplayCatalogProperties.World world( world.setRealms(List.of(realm)); return world; } + + @Test + void charsDoesNotResolveHiddenRealmByDirectSlug() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + false, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "mixed-world", "secret")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidRealm("mixed-world")); + Mockito.verifyNoInteractions(accountClient); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 460747f0dd..5ebf078594 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 @@ -10,17 +10,11 @@ import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; -import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; -import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -39,8 +33,6 @@ import org.mockito.Mockito; class WorldsTextCommandDispatchHandlerTest { - private final EntityManagementClient entityManagementClient = - Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); private final ScriptEventPublisher scriptEventPublisher = @@ -49,7 +41,6 @@ class WorldsTextCommandDispatchHandlerTest { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, Mockito.mock(AccountClient.class), DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -113,7 +104,6 @@ void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -130,7 +120,7 @@ void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { assertThat(outageResult.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); assertThat(malformedResult.commandResult().errorCode()) .isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); - Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @ParameterizedTest @@ -145,7 +135,6 @@ void worldsRejectsInvalidTransportSessionIdBeforeCatalogStoreOrEventDispatch( new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - entityManagementClient, Mockito.mock(AccountClient.class), store), scriptEventPublisher); @@ -154,8 +143,7 @@ void worldsRejectsInvalidTransportSessionIdBeforeCatalogStoreOrEventDispatch( scopedHandler.handle(worldsRequest(transportSessionId)); assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); - Mockito.verifyNoInteractions( - authorityService, store, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(authorityService, store, scriptEventPublisher); } @Test @@ -169,7 +157,6 @@ void worldsDoesNotTranslateCatalogIllegalArgumentExceptionToInvalidArgument() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( catalog, - entityManagementClient, Mockito.mock(AccountClient.class), DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -196,7 +183,6 @@ void worldsDoesNotTranslateStoreIllegalArgumentExceptionToInvalidArgument() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of()), - entityManagementClient, Mockito.mock(AccountClient.class), store), scriptEventPublisher); @@ -250,10 +236,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); SessionContext context = new SessionContext( @@ -289,7 +272,6 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { Mockito.anyString()); Mockito.verify(accountClient, Mockito.never()) .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); - Mockito.verifyNoInteractions(entityManagementClient); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), @@ -326,7 +308,6 @@ void privateRealmsBrowseDoesNotPublishDespitePositiveLegacyGrant() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -346,11 +327,11 @@ void privateRealmsBrowseDoesNotPublishDespitePositiveLegacyGrant() { assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(result.outputs()) .noneMatch(output -> output.payload() instanceof RealmBrowseViewOutput); - Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test - void publishesCommandEventForGameplayScopedCharsBrowse() { + void closesPublicCharsBrowseBeforeAuthorityOrRosterReads() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); gameplayCatalogProperties .getWorlds() @@ -359,42 +340,6 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .getFirst() .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setMembershipLifecycleState("ACTIVE") - .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId("123") - .setName("Emberline") - .setLevel(12) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .build()) - .build()); SessionContext context = new SessionContext( 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); @@ -403,7 +348,6 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -415,20 +359,9 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { false, Optional.of(context))); - assertThat(result.commandResult().accepted()).isTrue(); - assertThat(result.outputs()) - .singleElement() - .extracting(output -> output.payload()) - .isInstanceOf(CharacterBrowseViewOutput.class); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - Mockito.verify(scriptEventPublisher) - .publishCommandEvent( - Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "CHARS".equals(gameplayCommand.getCommandName()) - && "CHARS demo".equals(gameplayCommand.getCommandText()))); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test @@ -444,57 +377,10 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { gameplayCatalogProperties.setWorlds(List.of(world)); AccountClient accountClient = Mockito.mock(AccountClient.class); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build(), - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(1L) - .setMembershipAuthorityGeneration(1L) - .setMembershipLifecycleState("INACTIVE") - .setEvaluatedAt(Instant.now().toString()) - .build(), - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setMembershipAuthorityGeneration(1L) - .setMembershipLifecycleState("ACTIVE") - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString())) - .thenReturn( - GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setWorldSlug("demo") - .setRealmSlug("playtest") - .setGranted(false) - .setEvaluatedAt(Instant.now().toString()) - .build()); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -520,11 +406,11 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { assertThat(deniedRealm.outputs()).isEqualTo(unknownRealm.outputs()); } - Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test - void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity() { + void routesExplicitPublicCharsBrowseToUnavailableBeforeAuthorityOrRosterReads() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); gameplayCatalogProperties .getWorlds() @@ -533,34 +419,10 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( .getFirst() .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -578,9 +440,9 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( Optional.of(context))); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("JOIN_REQUIRED"); + assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); assertThat(result.outputs()).singleElement().extracting(output -> output.payload()).isNotNull(); - Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test @@ -627,8 +489,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { namespaceId))))); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( - new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore), - scriptEventPublisher); + new WorldsCommandHandler(catalog, accountClient, scopeStore), scriptEventPublisher); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() @@ -778,10 +639,7 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( @@ -864,7 +722,6 @@ void joinMissingSelectorRendersLocalizedErrorWithoutCallingAccount() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -929,11 +786,17 @@ void joinDispatchOutputsRenderLocalizedGuidanceAndEnglishFallback( : "ERROR " + expectedCode + " " + expectedEnglish); assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "fr")) .isEqualTo(expectedFrench); - assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "de")) + String fallback = renderer.renderAll(command, result.commandResult(), result.outputs(), "de"); + assertThat(fallback) .isEqualTo( success ? "OK JOIN " + expectedEnglish : "ERROR " + expectedCode + " " + expectedEnglish); + if (success) { + assertThat(expectedEnglish).doesNotContain("CHARS"); + assertThat(expectedFrench).doesNotContain("CHARS"); + assertThat(fallback).doesNotContain("CHARS"); + } } private static Stream joinPresentationCases() { @@ -1047,10 +910,7 @@ private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); SessionContext context = new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); @@ -1095,4 +955,47 @@ private TextCommandDispatchRequest charsRequest(String realmSelector, SessionCon false, Optional.of(context)); } + + @Test + void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { + gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 22L, 2L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE") + .build()) + .build()); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); + SessionContext context = + new SessionContext( + 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + + TextCommandInterpretationResult result = + scopedHandler.handle( + new TextCommandDispatchRequest( + "7", + new TextCommand(TextCommandType.REALMS, List.of("sandbox"), "REALMS sandbox"), + false, + Optional.of(context))); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verifyNoInteractions(scriptEventPublisher); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index cd05a5c705..269fcaf867 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -8,8 +8,12 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Arrays; import java.util.List; +import java.util.Map; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import org.junit.jupiter.api.BeforeEach; @@ -18,6 +22,12 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mock.env.MockEnvironment; import org.springframework.stereotype.Component; @ExtendWith(MockitoExtension.class) @@ -58,6 +68,75 @@ void defaultEffectiveBootstrapSeedsHaveOneVisiblePublicProductionRealmPerTenant( assertFalse(pointers.get(1).isPublicProductionRealm()); } + @Test + void shippedYamlBindsPublicDemoAndPrivateSandboxToTheSameTenantWithoutPersistingSeeds() + throws Exception { + ShippedBootstrapConfiguration shipped = loadShippedConfiguration(Map.of()); + List pointers = + shipped.gameSession().getPointers(); + + assertEquals(1L, pointers.get(0).getTenantId()); + assertEquals(1L, pointers.get(0).getGameInstanceId()); + assertTrue(pointers.get(0).isPublicProductionRealm()); + assertEquals(1L, pointers.get(1).getTenantId()); + assertEquals(2L, pointers.get(1).getGameInstanceId()); + assertFalse(pointers.get(1).isPublicProductionRealm()); + assertTrue(pointers.get(1).isRequiresCharacterSelection()); + assertSmokeRuntimeTargets(shipped.worldManagementTargets(), 1L, 1L, 1L, 2L); + + when(pointerRepository.count()).thenReturn(0L); + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + initializer.run(new DefaultApplicationArguments(new String[] {})); + + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @Test + void shippedYamlTenantOverridesKeepGameSessionAndWorldTargetsAligned() throws Exception { + ShippedBootstrapConfiguration shipped = + loadShippedConfiguration( + Map.of( + "FIREMUD_BOOTSTRAP_DEMO_TENANT_ID", "7", + "FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID", "7", + "FIREMUD_BOOTSTRAP_DEMO_GAME_INSTANCE_ID", "101", + "FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID", "202")); + + assertEquals(7L, shipped.gameSession().getPointers().get(0).getTenantId()); + assertEquals(101L, shipped.gameSession().getPointers().get(0).getGameInstanceId()); + assertEquals(7L, shipped.gameSession().getPointers().get(1).getTenantId()); + assertEquals(202L, shipped.gameSession().getPointers().get(1).getGameInstanceId()); + assertFalse(shipped.gameSession().getPointers().get(1).isPublicProductionRealm()); + assertSmokeRuntimeTargets(shipped.worldManagementTargets(), 7L, 101L, 7L, 202L); + + when(pointerRepository.count()).thenReturn(0L); + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + initializer.run(new DefaultApplicationArguments(new String[] {})); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @Test + void shippedYamlPrivateSandboxOverrideToAnotherTenantFailsBeforeMutation() throws Exception { + ShippedBootstrapConfiguration shipped = + loadShippedConfiguration(Map.of("FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID", "2")); + when(pointerRepository.count()).thenReturn(0L); + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + assertTrue( + failure.getMessage().contains("exactly one visible public production realm for tenant 2")); + + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + @Test void runPreservesExistingPointerAuthorityOnRestart() throws Exception { when(pointerRepository.count()).thenReturn(3L); @@ -235,6 +314,116 @@ private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSe return pointerSeed; } + private static ShippedBootstrapConfiguration loadShippedConfiguration( + Map environmentOverrides) throws IOException { + MockEnvironment environment = new MockEnvironment(); + environment + .getPropertySources() + .addFirst(new MapPropertySource("bootstrap-test-overrides", environmentOverrides)); + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + // Read source YAML directly to avoid test-resource shadowing; this is not packaged or live-boot + // proof. + addYamlPropertySources( + environment, + loader, + "game-session-application-prod", + "services/game-session-service/src/main/resources/application-prod.yml"); + addYamlPropertySources( + environment, + loader, + "game-session-application-test", + "services/game-session-service/src/main/resources/application-test.yml"); + addYamlPropertySources( + environment, + loader, + "game-session-application", + "services/game-session-service/src/main/resources/application.yml"); + addYamlPropertySources( + environment, + loader, + "world-management-application-prod", + "services/world-management-service/src/main/resources/application-prod.yml"); + addYamlPropertySources( + environment, + loader, + "world-management-application", + "services/world-management-service/src/main/resources/application.yml"); + + Binder binder = Binder.get(environment); + GameplayAdmissionPointerBootstrapProperties gameSession = + binder + .bind( + "firemud.gameplay.pointer-bootstrap", + Bindable.of(GameplayAdmissionPointerBootstrapProperties.class)) + .orElseThrow(() -> new IllegalStateException("Missing Game Session bootstrap YAML")); + List worldManagementTargets = + binder + .bind( + "firemud.smoke.seed-demo-runtime.targets", + Bindable.listOf(SmokeRuntimeTarget.class)) + .orElseThrow(() -> new IllegalStateException("Missing World runtime-target YAML")); + return new ShippedBootstrapConfiguration(gameSession, worldManagementTargets); + } + + private static void addYamlPropertySources( + MockEnvironment environment, + YamlPropertySourceLoader loader, + String name, + String relativePath) + throws IOException { + loader + .load(name, new FileSystemResource(repositoryFile(relativePath))) + .forEach(environment.getPropertySources()::addLast); + } + + private static Path repositoryFile(String relativePath) { + Path directory = Path.of("").toAbsolutePath(); + while (directory != null) { + Path candidate = directory.resolve(relativePath); + if (Files.isRegularFile(candidate)) { + return candidate; + } + directory = directory.getParent(); + } + throw new IllegalStateException("Cannot locate repository file " + relativePath); + } + + private static void assertSmokeRuntimeTargets( + List actualTargets, long... expectedTenantAndInstanceIds) { + assertEquals(expectedTenantAndInstanceIds.length / 2, actualTargets.size()); + for (int index = 0; index < actualTargets.size(); index++) { + assertEquals(expectedTenantAndInstanceIds[index * 2], actualTargets.get(index).getTenantId()); + assertEquals( + expectedTenantAndInstanceIds[index * 2 + 1], + actualTargets.get(index).getGameInstanceId()); + } + } + + private record ShippedBootstrapConfiguration( + GameplayAdmissionPointerBootstrapProperties gameSession, + List worldManagementTargets) {} + + public static class SmokeRuntimeTarget { + private long tenantId; + private long gameInstanceId; + + public long getTenantId() { + return tenantId; + } + + public void setTenantId(long tenantId) { + this.tenantId = tenantId; + } + + public long getGameInstanceId() { + return gameInstanceId; + } + + public void setGameInstanceId(long gameInstanceId) { + this.gameInstanceId = gameInstanceId; + } + } + private void assertRejectedBeforeMutation( List pointers, String expectedMessage) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index 29b751ed25..d817622c13 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -41,7 +42,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, - "readiness-probe")); + null)); }); GameplayLocalPathReadinessProbe probe = @@ -56,9 +57,40 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { SessionContext savedContext = contextCaptor.getValue(); assertTrue(savedContext.sessionId() > PROBE_SESSION_ID_BASE); assertTrue(savedContext.roomInstanceId().startsWith("readiness-room-")); + assertEquals("readiness-probe", savedContext.jwt()); verify(sessionContextService).deleteBySessionId(0L, savedContext.sessionId()); } + @Test + void sessionContextProbeRejectsStoredSecret() { + SessionContextService sessionContextService = mock(SessionContextService.class); + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = mock(RedisTemplate.class); + when(sessionContextService.findByTenantAndSessionId(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + long sessionId = invocation.getArgument(1, Long.class); + return Optional.of( + new SessionContext( + sessionId, + 0L, + PROBE_ACCOUNT_ID, + PROBE_CHARACTER_ID, + 0L, + "readiness-room-" + (sessionId - PROBE_SESSION_ID_BASE), + "readiness-probe")); + }); + + GameplayLocalPathReadinessProbe probe = + new GameplayLocalPathReadinessProbe(sessionContextService, redisTemplate); + + ProbeResult result = probe.probeSessionContextStore(); + + assertEquals(false, result.ready()); + assertEquals("stored session context did not round-trip", result.detail()); + verify(sessionContextService).deleteBySessionId(eq(0L), anyLong()); + } + @Test void commandQueueProbeReturnsUpWhenQueueWriteRoundTrips() { SessionContextService sessionContextService = mock(SessionContextService.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java index 814797a0f9..72d832d5da 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.jsonwebtoken.Claims; @@ -13,6 +14,18 @@ class FirstPartyConnectContextServiceTest { + @Test + void parseRejectsContextWhenVerifierSecretIsNotConfigured() { + FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); + JwtUtil jwtUtil = mock(JwtUtil.class); + + FirstPartyConnectContextService service = + new FirstPartyConnectContextService(properties, jwtUtil); + + assertTrue(service.parse("signed-context").isEmpty()); + verifyNoInteractions(jwtUtil); + } + @Test void parseReadsJwtClaimsThroughInjectedUtil() { FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index c1a716266d..41b3a138aa 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -517,6 +517,8 @@ void listPointerAuditPreservesCatalogIdentityAndHistoricalAbsence() { void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { java.util.concurrent.atomic.AtomicReference currentPointer = new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference> storedRevisions = + new java.util.concurrent.atomic.AtomicReference<>(); when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( 7L, "demo", "production")) .thenAnswer(invocation -> Optional.ofNullable(currentPointer.get())); @@ -528,12 +530,22 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { pointer.setId(11L); } currentPointer.set(pointer); + storedRevisions.set( + List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); return pointer; }); when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) .thenAnswer( invocation -> { GameplayAdmissionPointer pointer = invocation.getArgument(0); + Long expectedPointerVersion = invocation.getArgument(1); + Long expectedCatalogRevision = invocation.getArgument(2); + if (!List.of(expectedPointerVersion, expectedCatalogRevision) + .equals(storedRevisions.get())) { + throw new IllegalStateException("Admission pointer CAS predicate did not match"); + } + storedRevisions.set( + List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); currentPointer.set(pointer); return pointer; }); @@ -553,6 +565,8 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { assertEquals(1L, policyChanged.pointerVersion()); assertEquals(2L, routeChanged.catalogRevision()); assertEquals(2L, routeChanged.pointerVersion()); + verify(pointerRepository).updateExisting(any(GameplayAdmissionPointer.class), eq(1L), eq(1L)); + verify(pointerRepository).updateExisting(any(GameplayAdmissionPointer.class), eq(1L), eq(2L)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java index 5ec7026256..b6df308271 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java @@ -117,6 +117,22 @@ void recordDisconnectedPreservesCanonicalLogoutEventId() { verify(scriptEventPublisher).publishRegionExitEvent(context, "logout:41:1:7001", "LOGOUT"); } + @Test + void takeoverRemovesDisplacedSessionWithoutPublishingCharacterRegionExit() { + SessionContext context = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + whenGameplayContextPresent(context); + + service.recordDisconnected(41L, AccountRecentPresenceDisposition.TAKEOVER); + + verify(scriptEventPublisher, never()) + .publishRegionExitEvent(Mockito.any(SessionContext.class), anyString(), anyString()); + verify(accountRecentPresenceService) + .recordDisconnect(41L, AccountRecentPresenceDisposition.TAKEOVER); + verify(gameplayPresenceService).removeBySessionId(41L); + } + @Test void recordDisconnectedSkipsLifecycleEventWithoutGameplayRegionBinding() { whenGameplayContextPresent( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 7050d596dd..554caf3b06 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -59,9 +59,11 @@ import net.firedevops.firemud.gamesession.v1.TickStatus; import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagResponse; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; class GameSessionGrpcServiceTest { @AfterEach @@ -539,6 +541,37 @@ void listGameplayWorldsBuildsVisibleWorldsFromOneAuthoritySnapshot() { Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); } + @Test + void listGameplayWorldsReturnsAuthUnavailableWhenPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new DataAccessException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + } + + @Test + void listGameplayWorldsReturnsAuthUnavailableWhenSpringPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new DataAccessResourceFailureException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()).upsertPointer(Mockito.any()); + } + @Test void publicGrpcDiscoveryOmitsVisiblePrivateAndPrivateOnlyRealms() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -696,14 +729,49 @@ void gameplayDiscoverySuppressesTenantWithPublicRealmsAcrossDifferentWorlds() { Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); } + @Test + void listGameplayRealmsTreatsNumericWorldSlugAsExactSlugNotMenuOrdinal() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("demo", "live", 7L, 44L, true, true), + authorityPointer("123", "production", 8L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayRealmsResponse exactNumericSlug = listGameplayRealms(service, "123"); + ListGameplayRealmsResponse wouldBeMenuOrdinal = listGameplayRealms(service, "2"); + + assertFalse(exactNumericSlug.hasError()); + assertEquals(1, exactNumericSlug.getRealmsCount()); + assertEquals("production", exactNumericSlug.getRealms(0).getRealmSlug()); + assertEquals("INVALID_ARGUMENT", wouldBeMenuOrdinal.getError().getCode()); + assertEquals(0, wouldBeMenuOrdinal.getRealmsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); + } + + @Test + void listGameplayRealmsReturnsAuthUnavailableWhenPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new DataAccessException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "demo"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + } + @Test void publicAdmissionRejectsNonUniqueTenantGlobalPublicRealm() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot selectedPublicRealm = authorityPointer("alpha", "live", 7L, 44L, true, true); - Mockito.when(pointerAuthorityService.findPointer(7L, "alpha", "live")) - .thenReturn(java.util.Optional.of(selectedPublicRealm)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn( List.of(selectedPublicRealm, authorityPointer("beta", "live", 7L, 55L, true, true))); @@ -735,6 +803,8 @@ public void onCompleted() {} assertFalse(response.get().hasAdmissionPointer()); Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test @@ -745,8 +815,6 @@ void getAdmissionPointerRejectsFoldedVisiblePrivateRealmAlias() { authorityPointer("demo", "live", 7L, 44L, true, true); GameplayAdmissionPointerSnapshot privateAlias = authorityPointer("demo", "LIVE", 7L, 45L, true, false); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "live")) - .thenReturn(java.util.Optional.of(publicRealm)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(publicRealm, privateAlias)); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -776,22 +844,217 @@ public void onCompleted() {} assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); assertFalse(response.get().hasAdmissionPointer()); Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test - void privateAdmissionRequiresAndUsesHealthyTenantCatalog() { + void privateAdmissionAllowsOnePublicRealmInAnotherWorld() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot privateRealm = authorityPointer("private", "preview", 7L, 66L, true, false); - GameplayAdmissionPointerSnapshot publicRealm = - authorityPointer("demo", "live", 7L, 44L, true, true); - Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) - .thenReturn(java.util.Optional.of(privateRealm)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) - .thenReturn(List.of(privateRealm, publicRealm)); + .thenReturn( + List.of(privateRealm, authorityPointer("public-world", "live", 7L, 44L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); + + assertFalse(response.hasError()); + assertEquals("66", response.getAdmissionPointer().getGameInstanceId()); + assertEquals(privateRealm.realmId().toString(), response.getAdmissionPointer().getRealmId()); + assertEquals( + privateRealm.playableStateNamespaceId().toString(), + response.getAdmissionPointer().getPlayableStateNamespaceId()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void getAdmissionPointerReturnsAuthUnavailableWhenPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenThrow(new DataAccessException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void getAdmissionPointerReturnsAuthUnavailableWhenSpringTenantPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenThrow(new DataAccessResourceFailureException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).upsertPointer(Mockito.any()); + } + + @Test + void getAdmissionPointerReturnsAuthUnavailableWhenTenantSnapshotIsNull() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)).thenReturn(null); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + } + + @Test + void getAdmissionPointerRejectsForeignTenantRowsInTenantSnapshot() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(authorityPointer("demo", "production", 8L, 44L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + } + + @Test + void privateAdmissionRejectsMultipleVisiblePublicRealmsForSelectedTenant() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn( + List.of( + authorityPointer("private", "preview", 7L, 66L, true, false), + authorityPointer("alpha", "live", 7L, 44L, true, true), + authorityPointer("beta", "live", 7L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionRejectsTenantWithNoPublicRealm() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(authorityPointer("private", "preview", 7L, 66L, true, false))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionDoesNotCountHiddenPublicRealmForSelectedTenant() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn( + List.of( + authorityPointer("private", "preview", 7L, 66L, true, false), + authorityPointer("hidden", "live", 7L, 44L, false, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionDoesNotUsePublicRealmFromAnotherTenantToSatisfyCardinality() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(pointerAuthorityService.listPointers()) - .thenReturn(List.of(publicRealm, authorityPointer("beta", "live", 8L, 55L, true, true))); + .thenReturn( + List.of( + authorityPointer("private", "preview", 7L, 66L, true, false), + authorityPointer("public-world", "live", 8L, 44L, true, true))); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(authorityPointer("private", "preview", 7L, 66L, true, false))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionRejectsWhenPublicRealmBecomesHiddenAndCatalogRedactsPrivateOnlyWorld() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot privateRealm = + authorityPointer("private", "preview", 7L, 66L, true, false); + GameplayAdmissionPointerSnapshot hiddenPublicRealm = + authorityPointer("public-world", "live", 7L, 44L, false, true); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(privateRealm, hiddenPublicRealm)); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(privateRealm, hiddenPublicRealm)); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayRealmsResponse catalogResponse = listGameplayRealms(service, "private"); + GetAdmissionPointerResponse pointerResponse = + getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", catalogResponse.getError().getCode()); + assertEquals(0, catalogResponse.getRealmsCount()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.getError().getCode()); + assertFalse(pointerResponse.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionRejectsDuplicateExactRowsInCurrentPointerSnapshot() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot privateRealm = + authorityPointer("private", "preview", 7L, 66L, true, false); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(privateRealm, privateRealm)); GameSessionGrpcService service = catalogService(pointerAuthorityService); AtomicReference response = new AtomicReference<>(); @@ -816,20 +1079,22 @@ public void onError(Throwable t) { public void onCompleted() {} }); - assertFalse(response.get().hasError()); - assertEquals("66", response.get().getAdmissionPointer().getGameInstanceId()); - Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); - Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test - void getAdmissionPointerReturnsHiddenMetadataWithoutPublicCardinalityAuthorization() { + void getAdmissionPointerReturnsHiddenMetadataFromAuthoritativeTenantSnapshot() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot hiddenRealm = - authorityPointer("private", "preview", 7L, 66L, false, true); - Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) - .thenReturn(java.util.Optional.of(hiddenRealm)); + authorityPointer("private", "preview", 7L, 66L, false, false); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn( + List.of(hiddenRealm, authorityPointer("public-world", "live", 7L, 44L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); AtomicReference response = new AtomicReference<>(); @@ -856,7 +1121,7 @@ public void onCompleted() {} assertFalse(response.get().hasError()); assertFalse(response.get().getAdmissionPointer().getVisible()); - assertEquals(true, response.get().getAdmissionPointer().getPublicProductionRealm()); + assertFalse(response.get().getAdmissionPointer().getPublicProductionRealm()); assertEquals( hiddenRealm.catalogRevision(), response.get().getAdmissionPointer().getCatalogRevision()); assertEquals( @@ -864,8 +1129,9 @@ public void onCompleted() {} assertEquals( hiddenRealm.playableStateNamespaceId().toString(), response.get().getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService).findPointer(7L, "private", "preview"); - Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test @@ -900,8 +1166,6 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(authoritativeSnapshot)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -944,6 +1208,7 @@ public void onCompleted() {} realmsRef.get().getRealms(0).getPlayableStateNamespaceId()); Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.clearInvocations(pointerAuthorityService); AtomicReference pointerRef = new AtomicReference<>(); service.getAdmissionPointer( GetAdmissionPointerRequest.newBuilder() @@ -975,7 +1240,10 @@ public void onCompleted() {} assertEquals( "2ea958e0-13a2-41d0-9c39-59a96cf31412", pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService).findPointer(7L, "demo", "production"); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test @@ -1064,8 +1332,6 @@ void missingCatalogRevisionIsSuppressedFromBrowseButPointerReadFailsClosed() { Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(missingRevision)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(missingRevision)); GameSessionGrpcService service = newService( pingService, @@ -1148,6 +1414,32 @@ public void onCompleted() {} return response.get(); } + private static GetAdmissionPointerResponse getAdmissionPointer( + GameSessionGrpcService service, String tenantId, String worldSlug, String realmSlug) { + AtomicReference response = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId(tenantId) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + private static GameplayAdmissionPointerSnapshot catalogPointer( String worldSlug, String realmSlug, @@ -1216,8 +1508,6 @@ void missingStableRealmIdentityIsSuppressedFromBrowseButPointerReadFailsClosed() Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(missingIdentity)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(missingIdentity)); GameSessionGrpcService service = newService( Mockito.mock(PingService.class), @@ -1300,6 +1590,7 @@ void unknownNamedWorldReturnsInvalidArgument() { assertEquals("INVALID_ARGUMENT", response.getError().getCode()); assertEquals(0, response.getRealmsCount()); + Mockito.verify(pointerAuthorityService).listPointers(); } @Test @@ -1387,6 +1678,137 @@ public void onCompleted() { assertEquals(0, response.get().getRealmsCount()); } + @Test + void getAdmissionPointerFailsClosedWhenTenantHasNoVisiblePublicProductionRealm() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)).thenReturn(List.of()); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + TestGameplayWorldCatalogs.fromProperties(new GameplayCatalogProperties()), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void getAdmissionPointerFailsClosedWhenTenantHasMultipleVisiblePublicProductionRealms() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot firstPublicRealm = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayAdmissionPointerSnapshot secondPublicRealm = + new GameplayAdmissionPointerSnapshot( + "demo-two", + "Demo World Two", + "production", + "Live Realm", + 7L, + 45L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 4L, + java.util.UUID.fromString("e9f2f6e7-8173-46df-a1a0-f2a079d09ebd"), + java.util.UUID.fromString("7b1fdb12-9f98-4b0f-87f2-0adf4bde7e2e")); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(firstPublicRealm, secondPublicRealm)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + TestGameplayWorldCatalogs.fromProperties(new GameplayCatalogProperties()), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + @Test void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -1399,7 +1821,7 @@ void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenThrow(new IllegalStateException("pointer store unavailable")); GameSessionGrpcService service = newService( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java index dcc166d305..195ca5e0e2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java @@ -1,127 +1,13 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; -import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.Test; -import org.slf4j.Logger; class GameplayPresenceRoleClassifierTest { - private static final JwtUtil JWT_UTIL = new JwtUtil("mysecretkey123456789012345678901", 30_000L); - - @Test - void classifyRoleReturnsPlayerWhenJwtParserThrowsIllegalArgumentException() { - JwtUtil jwtUtil = mock(JwtUtil.class); - Logger logger = mock(Logger.class); - when(jwtUtil.parseToken("boom-token")).thenThrow(new IllegalArgumentException("bad jwt")); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "boom-token"), - jwtUtil, - logger); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleReturnsModeratorForScopedModeratorRole() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "scopedRoles", - java.util.Map.of("22", java.util.List.of("moderator")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.MODERATOR, role); - } - - @Test - void classifyRoleReturnsGodForGlobalGodRole() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - "202", java.util.Map.of("accountId", "202", "globalRoles", java.util.List.of("god"))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.GOD, role); - } - - @Test - void classifyRoleReturnsAdminForTenantAdminRole() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "scopedRoles", - java.util.Map.of("22", java.util.List.of("tenantAdmin")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.ADMIN, role); - } - @Test - void classifyRoleUsesTheHighestAvailableGameplayRole() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "globalRoles", - java.util.List.of("moderator", "god"), - "scopedRoles", - java.util.Map.of("22", java.util.List.of("tenantAdmin")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.GOD, role); - } - - @Test - void classifyRoleReturnsPlayerWhenScopedRolesClaimIsMalformed() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken("202", java.util.Map.of("accountId", "202", "scopedRoles", "bad")); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.PLAYER, role); + void classifyRoleReturnsPlayerUntilFreshGameplayGrantEvidenceIsModeled() { + assertEquals(GameplayPresenceRole.PLAYER, GameplayPresenceRoleClassifier.classifyRole()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 2d391f44db..c115235856 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -35,7 +36,7 @@ class RedisGameplayPresenceServiceTest { void setUp() { when(redisTemplate.opsForValue()).thenReturn(valueOperations); when(redisTemplate.opsForSet()).thenReturn(setOperations); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis()); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis()); } @Test @@ -82,21 +83,35 @@ void registerConnectedClassifiesInvalidJwtAsPlayer() { } @Test - void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { - String godJwt = + void registerConnectedDoesNotElevateTenantRoleClaimsWithoutGrantEvidence() { + String tenantAdminJwt = jwtUtil.generateToken( - "1", + "102", Map.of( "accountId", - "1", - "globalRoles", - List.of("platformAdmin"), + "102", "scopedRoles", - Map.of())); - SessionContext godContext = - new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); - service.registerConnected(godContext); + Map.of("22", List.of("tenantAdmin", "moderator")))); + SessionContext context = + new SessionContext( + 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", tenantAdminJwt); + + service.registerConnected(context); + verify(valueOperations) + .set( + org.mockito.Mockito.eq("gameplaypresence:session:1"), + argThat( + value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), + org.mockito.Mockito.eq(TTL)); + } + + @Test + void listConnectedByGameInstanceDemotesCachedElevationAndPrunesMissingSessions() { when(setOperations.members("gameplaypresence:22:7:sessions")) .thenReturn(new LinkedHashSet<>(List.of("1", "2"))); when(valueOperations.get("gameplaypresence:session:1")) @@ -105,24 +120,35 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { 1L, 22L, 7L, + "ISOLATED", "demo", "production", + 17L, 1L, 101L, "Aster", GameplayPresenceRole.GOD, 70L, - null, - null, - null)); + 50L, + 60L, + 65L)); when(valueOperations.get("gameplaypresence:session:2")).thenReturn(null); var result = service.listConnectedByGameInstance(22L, 7L); assertEquals(1, result.size()); - assertEquals(GameplayPresenceRole.GOD, result.get(0).role()); + assertEquals(GameplayPresenceRole.PLAYER, result.get(0).role()); assertEquals("Aster", result.get(0).characterName()); + assertEquals("ISOLATED", result.get(0).playableStateScope()); + assertEquals(17L, result.get(0).pointerVersion()); + assertEquals(50L, result.get(0).explicitAfkSinceEpochMs()); + assertEquals(60L, result.get(0).lastAcceptedCommandAtEpochMs()); + assertEquals(65L, result.get(0).lastMeaningfulActivityAtEpochMs()); verify(setOperations).remove("gameplaypresence:22:7:sessions", "2"); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test @@ -140,7 +166,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { 1L, 101L, "Aster", - GameplayPresenceRole.GOD, + GameplayPresenceRole.PLAYER, 70L, null, null, @@ -180,34 +206,47 @@ void removeBySessionIdRemovesValueAndSetMembership() { } @Test - void findConnectedBySessionIdReadsPresenceRecordDirectly() { + void findConnectedBySessionIdDemotesCachedElevationWithoutWritingOrRefreshingTtl() { when(valueOperations.get("gameplaypresence:session:4")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( 4L, 22L, 7L, + "ISOLATED", "demo", "production", - 2L, + 17L, 102L, + 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 70L, - null, - null, - null)); + 50L, + 60L, + 65L)); var presence = service.findConnectedBySessionId(4L); - assertEquals(true, presence.isPresent()); + assertTrue(presence.isPresent()); assertEquals(4L, presence.get().sessionId()); + assertEquals(GameplayPresenceRole.PLAYER, presence.get().role()); + assertEquals("ISOLATED", presence.get().playableStateScope()); + assertEquals(17L, presence.get().pointerVersion()); + assertEquals(70L, presence.get().connectedAtEpochMs()); + assertEquals(50L, presence.get().explicitAfkSinceEpochMs()); + assertEquals(60L, presence.get().lastAcceptedCommandAtEpochMs()); + assertEquals(65L, presence.get().lastMeaningfulActivityAtEpochMs()); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequested() { AtomicLong now = new AtomicLong(100L); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis(), now::get); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis(), now::get); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( @@ -219,11 +258,11 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 80L, - null, - null, - null)); + 95L, + 99L, + 90L)); now.set(125L); service.recordCommandActivity(3L, false); @@ -241,7 +280,10 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest .lastAcceptedCommandAtEpochMs()) && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) .lastMeaningfulActivityAtEpochMs() - == null), + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); @@ -250,7 +292,7 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest @Test void setExplicitAfkRefreshesPresenceRecord() { AtomicLong now = new AtomicLong(100L); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis(), now::get); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis(), now::get); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( @@ -262,11 +304,11 @@ void setExplicitAfkRefreshesPresenceRecord() { 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.MODERATOR, 80L, - null, - null, - null)); + 85L, + 90L, + 95L)); now.set(145L); service.setExplicitAfk(3L, true); @@ -281,7 +323,16 @@ void setExplicitAfkRefreshesPresenceRecord() { .equals( ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .explicitAfkSinceEpochMs())), + .explicitAfkSinceEpochMs()) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastAcceptedCommandAtEpochMs() + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastMeaningfulActivityAtEpochMs() + == 95L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); @@ -304,7 +355,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 80L, null, 100L, @@ -322,7 +373,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.GOD, 90L, null, 110L, @@ -332,8 +383,15 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { assertEquals(1, result.size()); assertEquals(2, result.get(102L).size()); + assertTrue( + result.get(102L).stream() + .allMatch(presence -> presence.role() == GameplayPresenceRole.PLAYER)); assertEquals(4L, result.get(102L).get(0).sessionId()); assertEquals(3L, result.get(102L).get(1).sessionId()); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index 8af487c378..3d331b77d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -1,9 +1,13 @@ package net.firedevops.firemud.gamesession.service.impl; +import static net.firedevops.firemud.gamesession.service.impl.SessionContextSerializationTestSupport.serialize; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -15,6 +19,7 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -24,6 +29,7 @@ @SuppressWarnings("unchecked") class RedisMovementEffectIdempotencyServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String DISTINCTIVE_JWT = "distinctive-raw-backend-jwt-for-test"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -44,7 +50,7 @@ void setUp() { } @Test - void applyPreservesRoutingBundleWhenUpdatingRoom() { + void applyPreservesRoutingBundleWhenUpdatingRoom() throws Exception { SessionContext current = new SessionContext( 41L, @@ -55,7 +61,7 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { "demo", 1L, "R-1021", - "jwt-token", + DISTINCTIVE_JWT, "en-NZ", 1L, "demo", @@ -75,11 +81,19 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { assertEquals("production", updated.realmSlug()); assertEquals(7L, updated.pointerVersion()); assertEquals("SHARED", updated.playableStateScope()); + assertNull(updated.jwt()); verify(valueOperations).set("sessionctx:22:41:context", updated, TTL); verify(valueOperations).set("sessionctx:session:41:context", updated, TTL); verify(valueOperations).set("sessionctx:22:identity:1:7001:context", updated, TTL); verify(valueOperations).set("sessionctx:22:identity:1:name:demo:context", updated, TTL); verify(valueOperations).set("sessionctx:22:41:movement-effect:tfx-1", updated, TTL); + + ArgumentCaptor storedContexts = ArgumentCaptor.forClass(SessionContext.class); + verify(valueOperations, Mockito.times(5)).set(anyString(), storedContexts.capture(), eq(TTL)); + for (SessionContext stored : storedContexts.getAllValues()) { + assertNull(stored.jwt()); + assertFalse(serialize(stored).contains(DISTINCTIVE_JWT)); + } } @Test @@ -90,7 +104,8 @@ void applyReturnsConflictWhenGameplayIdentityMismatch() { MoveEffectApplyResult result = service.apply("tfx-1", withAccountId(current, 999L), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(current, result.context()); + assertEquals(current.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); verify(redisTemplate, never()).delete(anyString()); } @@ -105,7 +120,8 @@ void applyReturnsReplayedContextWhenReplayAlreadyStored() { MoveEffectApplyResult result = service.apply("tfx-1", current, "R-2045"); assertEquals(MoveEffectApplyStatus.REPLAYED, result.status()); - assertEquals(replayed, result.context()); + assertEquals(replayed.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); verify(redisTemplate, never()).delete(anyString()); } @@ -129,7 +145,8 @@ void applyRejectsLegacyStoredCurrentRoomBeforeWrite() { MoveEffectApplyResult result = service.apply("tfx-1", baselineContext(), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(legacyCurrent, result.context()); + assertEquals(legacyCurrent.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); } @@ -143,7 +160,8 @@ void applyRejectsLegacyReplayedRoomBeforeReturningReplay() { MoveEffectApplyResult result = service.apply("tfx-1", current, "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(legacyReplay, result.context()); + assertEquals(legacyReplay.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); } @@ -157,7 +175,7 @@ private SessionContext baselineContext() { "demo", 1L, "R-1021", - "jwt-token", + DISTINCTIVE_JWT, "en-NZ", 1L, "demo", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 4c8ae9403c..1b07e3d701 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -1,6 +1,11 @@ package net.firedevops.firemud.gamesession.service.impl; +import static net.firedevops.firemud.gamesession.service.impl.SessionContextSerializationTestSupport.serialize; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -10,6 +15,7 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -19,6 +25,7 @@ @SuppressWarnings("unchecked") class RedisSessionContextServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String DISTINCTIVE_JWT = "distinctive-raw-backend-jwt-for-test"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -39,15 +46,24 @@ void setUp() { } @Test - void saveStoresContextInSessionAndIdentityKeys() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + void saveStoresContextInSessionAndIdentityKeys() throws Exception { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); service.save(context); verify(redisTemplate).multi(); verify(redisTemplate).exec(); - verify(valueOperations).set("sessionctx:10:1:context", context, TTL); - verify(valueOperations).set("sessionctx:10:identity:40:30:context", context, TTL); + SessionContext persisted = context.withoutJwt(); + verify(valueOperations).set("sessionctx:10:1:context", persisted, TTL); + verify(valueOperations).set("sessionctx:session:1:context", persisted, TTL); + verify(valueOperations).set("sessionctx:10:identity:40:30:context", persisted, TTL); + + ArgumentCaptor storedContexts = ArgumentCaptor.forClass(SessionContext.class); + verify(valueOperations, Mockito.times(3)).set(anyString(), storedContexts.capture(), eq(TTL)); + for (SessionContext stored : storedContexts.getAllValues()) { + assertNull(stored.jwt()); + assertFalse(serialize(stored).contains(DISTINCTIVE_JWT)); + } } @Test @@ -59,28 +75,69 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { service.save(replacement); verify(redisTemplate).delete("sessionctx:10:1:context"); - verify(valueOperations).set("sessionctx:10:2:context", replacement, TTL); - verify(valueOperations).set("sessionctx:10:identity:40:30:context", replacement, TTL); + SessionContext persisted = replacement.withoutJwt(); + verify(valueOperations).set("sessionctx:10:2:context", persisted, TTL); + verify(valueOperations).set("sessionctx:10:identity:40:30:context", persisted, TTL); } @Test - void findByTenantAndSessionIdReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + void findByTenantAndSessionIdProjectsLegacyJwtOut() { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); Optional result = service.findByTenantAndSessionId(10L, 1L); - assertEquals(Optional.of(context), result); + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); } @Test - void findByGameplayIdentityReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + void findBySessionIdProjectsLegacyJwtOut() { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(context); + + Optional result = service.findBySessionId(1L); + + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); + } + + @Test + void findByGameplayIdentityProjectsLegacyJwtOut() { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(context); Optional result = service.findByGameplayIdentity(10L, 40L, 30L); - assertEquals(Optional.of(context), result); + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); + } + + @Test + void findByGameplayNameProjectsLegacyJwtOut() { + SessionContext context = + new SessionContext( + 1L, + 10L, + 20L, + "demo", + 30L, + "Hero", + 40L, + "R-1", + DISTINCTIVE_JWT, + "en", + 40L, + "world", + "realm", + 1L, + "SHARED"); + when(valueOperations.get("sessionctx:10:identity:40:name:hero:context")).thenReturn(context); + + Optional result = service.findByGameplayName(10L, 40L, "Hero"); + + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); } @Test @@ -103,7 +160,7 @@ void savePreservesLocaleTagInStoredContext() { service.save(context); - verify(valueOperations).set("sessionctx:10:1:context", context, TTL); + verify(valueOperations).set("sessionctx:10:1:context", context.withoutJwt(), TTL); assertEquals("fr", context.localeTag()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java new file mode 100644 index 0000000000..ad38c89311 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.io.ByteArrayOutputStream; +import java.io.ObjectOutputStream; +import java.nio.charset.StandardCharsets; +import net.firedevops.firemud.gamesession.service.SessionContext; + +final class SessionContextSerializationTestSupport { + private SessionContextSerializationTestSupport() {} + + static String serialize(SessionContext context) throws Exception { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ObjectOutputStream objectOutput = new ObjectOutputStream(output)) { + objectOutput.writeObject(context); + } + return output.toString(StandardCharsets.ISO_8859_1); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java index 8eda087830..bf181bbe57 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java @@ -8,18 +8,14 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.DisconnectDeduplicationService; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PingService; -import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectRequest; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.slf4j.MDC; import org.springframework.boot.test.system.CapturedOutput; @@ -28,13 +24,10 @@ @ExtendWith(OutputCaptureExtension.class) class TcpProxyServiceImplTest { @Test - void notifyDisconnectSavesSuspendedState() { + void notifyDisconnectWithUnprovedBindingLeavesLifecycleStateUnchanged() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -45,12 +38,7 @@ void notifyDisconnectSavesSuspendedState() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -75,22 +63,16 @@ public void onCompleted() {} }); assertEquals("OK", ref.get().getError().getCode()); - ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(GameInstanceDto.class); - Mockito.verify(sessionStateService).saveState(stateCaptor.capture()); - assertEquals("SUSPENDED", stateCaptor.getValue().status()); - assertEquals("patch", stateCaptor.getValue().scriptPatchVersion()); - assertEquals(3L, stateCaptor.getValue().scriptPinEpoch()); - assertEquals("pin-request-3", stateCaptor.getValue().scriptPinControlPlaneRequestId()); + assertEquals("RUNNING", entity.getStatus()); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); } @Test void notifyDisconnectAddsGameplayLoggingContext() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -103,19 +85,14 @@ void notifyDisconnectAddsGameplayLoggingContext() { assertEquals("7", MDC.get("tenantId")); assertEquals("12", MDC.get("gameInstanceId")); assertEquals(null, MDC.get("characterId")); - return null; + return Optional.of(entity); }) - .when(sessionStateService) - .saveState(Mockito.any()); + .when(repository) + .findById(12L); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -135,11 +112,8 @@ void notifyDisconnectAddsGameplayLoggingContext() { @Test void notifyDisconnectRejectsInvalidTenant(CapturedOutput output) { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -147,12 +121,7 @@ void notifyDisconnectRejectsInvalidTenant(CapturedOutput output) { .thenReturn(true); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -183,18 +152,14 @@ public void onCompleted() {} org.assertj.core.api.Assertions.assertThat(output) .contains( "NotifyDisconnect returned app error INVALID_ARGUMENT: tenantId must be a number"); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test void notifyDisconnectRejectsZeroGameInstanceId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -202,12 +167,7 @@ void notifyDisconnectRejectsZeroGameInstanceId() { .thenReturn(true); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -222,18 +182,14 @@ void notifyDisconnectRejectsZeroGameInstanceId() { assertEquals("gameInstanceId must be positive", ref.get().getError().getMessage()); assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test void notifyDisconnectRejectsZeroTenantId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -241,12 +197,7 @@ void notifyDisconnectRejectsZeroTenantId() { .thenReturn(true); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -261,18 +212,14 @@ void notifyDisconnectRejectsZeroTenantId() { assertEquals("tenantId must be positive", ref.get().getError().getMessage()); assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test void duplicateDisconnectHintsAreIgnoredAndMetered() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -283,12 +230,7 @@ void duplicateDisconnectHintsAreIgnoredAndMetered() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); NotifyDisconnectRequest request = NotifyDisconnectRequest.newBuilder() @@ -308,17 +250,13 @@ void duplicateDisconnectHintsAreIgnoredAndMetered() { assertEquals("OK", second.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verify(sessionStateService, Mockito.times(1)).saveState(Mockito.any()); } @Test void lateDisconnectHintsAreIgnoredAndMetered() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -329,12 +267,7 @@ void lateDisconnectHintsAreIgnoredAndMetered() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); NotifyDisconnectRequest firstRequest = NotifyDisconnectRequest.newBuilder() @@ -361,17 +294,13 @@ void lateDisconnectHintsAreIgnoredAndMetered() { assertEquals("OK", second.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verify(sessionStateService, Mockito.times(1)).saveState(Mockito.any()); } @Test void disconnectWithoutBootstrapMetadataIsMetered() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -380,12 +309,7 @@ void disconnectWithoutBootstrapMetadataIsMetered() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect(NotifyDisconnectRequest.newBuilder().build(), observerFor(ref)); @@ -393,17 +317,13 @@ void disconnectWithoutBootstrapMetadataIsMetered() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); } @Test void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -412,12 +332,7 @@ void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -432,23 +347,14 @@ void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verify(gameplayPresenceLifecycleService) - .recordDisconnected( - 12L, - net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition - .TRANSPORT_LOSS); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test void disconnectWithoutGameInstanceMetadataIgnoresZeroSessionId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -457,12 +363,7 @@ void disconnectWithoutGameInstanceMetadataIgnoresZeroSessionId() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -477,19 +378,14 @@ void disconnectWithoutGameInstanceMetadataIgnoresZeroSessionId() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test void disconnectWithoutGameInstanceMetadataIgnoresNegativeSessionId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -498,12 +394,7 @@ void disconnectWithoutGameInstanceMetadataIgnoresNegativeSessionId() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -518,8 +409,6 @@ void disconnectWithoutGameInstanceMetadataIgnoresNegativeSessionId() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } 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 bd8fc38812..93b57639d8 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 @@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -40,6 +41,8 @@ import net.firedevops.firemud.gamesession.service.SessionContextService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mockito; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; @@ -1049,6 +1052,168 @@ void handleMessageDoesNotReplayReconnectBufferForPartialGameplayIdentityShell() verify(screenBufferService, never()).get(any(Long.class), any(Long.class), any(Long.class)); } + @Test + void freshFirstPartyPlayDoesNotReplayRetainedBufferFromAnEarlierLogout() throws Exception { + TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); + SessionContext freshBinding = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, + "first_party_web", + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, + "fresh-connect-token")); + when(parser.parse("PLAY demo")).thenReturn(command); + when(interpreter.interpret("41", command, false)) + .thenReturn( + new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(), false, false)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(freshBinding)); + when(promptBurstCoordinator.applyPromptWindow( + eq("41"), eq(freshBinding), eq(List.of()), eq(false))) + .thenReturn(List.of()); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + eq("en-NZ"), + any(PresentationProperties.class), + any())) + .thenReturn("OK PLAY"); + + handler.handleMessage(session, new TextMessage("PLAY demo")); + + verify(screenBufferService, never()).get(any(Long.class), any(Long.class), any(Long.class)); + verify(lookHandler) + .describePlayerOutput( + "41", + true, + net.firedevops.firemud.gamesession.presentation.LookViewOutput.RefreshReason + .RECONNECT_REFRESH); + } + + @Test + void genericReconnectPlayEmitsFreshLookAndConfiguredPromptWithoutRetainedBufferReads() + throws Exception { + TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); + SessionContext binding = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + PresentationProperties presentation = + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L)); + PlayerOutput freshLook = PlayerOutput.message("Fresh room view"); + PlayerOutput prompt = PlayerOutput.prompt("fresh prompt"); + when(parser.parse("PLAY demo")).thenReturn(command); + when(interpreter.interpret("41", command, false)) + .thenReturn( + new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(), true, false)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(binding)); + when(promptBurstCoordinator.applyPromptWindow(eq("41"), eq(binding), eq(List.of()), eq(false))) + .thenReturn(List.of()); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + eq("en-NZ"), + eq(presentation), + any())) + .thenReturn("OK PLAY"); + when(settingsResolver.presentation(binding)).thenReturn(presentation); + when(lookHandler.describePlayerOutput( + "41", + true, + net.firedevops.firemud.gamesession.presentation.LookViewOutput.RefreshReason + .RECONNECT_REFRESH)) + .thenReturn(freshLook); + when(promptComposer.compose(binding)).thenReturn(Optional.of(prompt)); + when(outputProjector.projectPlayerOutput(session, freshLook, "en-NZ", presentation)) + .thenReturn("Fresh room view"); + when(outputProjector.projectPlayerOutput(session, prompt, "en-NZ", presentation)) + .thenReturn("fresh prompt"); + + handler.handleMessage(session, new TextMessage("PLAY demo")); + + verify(lookHandler) + .describePlayerOutput( + "41", + true, + net.firedevops.firemud.gamesession.presentation.LookViewOutput.RefreshReason + .RECONNECT_REFRESH); + verify(outputProjector).projectPlayerOutput(session, freshLook, "en-NZ", presentation); + verify(promptComposer).compose(binding); + verify(outputProjector).projectPlayerOutput(session, prompt, "en-NZ", presentation); + verify(promptBurstCoordinator).recordPromptEmission("41"); + verify(session).sendMessage(new TextMessage("Fresh room view")); + verify(session).sendMessage(new TextMessage("fresh prompt")); + Mockito.verifyNoInteractions(screenBufferService); + } + + @ParameterizedTest + @CsvSource({"true,true,1", "true,false,0", "false,true,0", "false,false,0"}) + void reconnectPlayEmitsPromptOnlyWhenBothPromptSettingsAreEnabled( + boolean promptEnabled, boolean emitAfterReconnectRestore, int expectedPromptEmissions) + throws Exception { + TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); + SessionContext binding = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + PresentationProperties presentation = + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(promptEnabled, emitAfterReconnectRestore, 150L)); + PlayerOutput prompt = PlayerOutput.prompt("fresh prompt"); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, + "first_party_web")); + when(parser.parse("PLAY demo")).thenReturn(command); + when(interpreter.interpret("41", command, false)) + .thenReturn( + new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(), true, false)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(binding)); + when(promptBurstCoordinator.applyPromptWindow(eq("41"), eq(binding), eq(List.of()), eq(false))) + .thenReturn(List.of()); + when(settingsResolver.presentation(binding)).thenReturn(presentation); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + eq("en-NZ"), + eq(presentation), + eq(binding))) + .thenReturn("OK PLAY"); + when(promptComposer.compose(binding)).thenReturn(Optional.of(prompt)); + + handler.handleMessage(session, new TextMessage("PLAY demo")); + + verify(promptComposer, times(expectedPromptEmissions)).compose(binding); + verify(outputProjector, times(expectedPromptEmissions)) + .projectPlayerOutput(eq(session), eq(prompt), eq("en-NZ"), eq(presentation)); + verify(promptBurstCoordinator, times(expectedPromptEmissions)).recordPromptEmission("41"); + Mockito.verifyNoInteractions(screenBufferService); + } + @Test void handleMessageUsesTenantScopedSessionContextWhenTenantAttributePresent() throws Exception { when(session.getAttributes()) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java index 8c4f50a040..c93a05d1cb 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java @@ -66,6 +66,8 @@ public final class EntityManagementStubServer implements AutoCloseable { new AtomicReference<>(defaultCharacters()); private final AtomicReference roomEntities = new AtomicReference<>(LookTestFixtures.sampleEntities()); + private final AtomicReference lastListCharactersByAccountRequest = + new AtomicReference<>(); private final AtomicReference actorState = new AtomicReference<>(QueryActorStateResponse.getDefaultInstance()); private boolean torchOnGround = true; @@ -113,6 +115,7 @@ public void findCharacterByName( public void listCharactersByAccount( ListCharactersByAccountRequest request, StreamObserver responseObserver) { + lastListCharactersByAccountRequest.set(request); ListCharactersByAccountResponse.Builder response = ListCharactersByAccountResponse.newBuilder(); if (request.getPlayableStateScope() @@ -262,6 +265,14 @@ public void resetActorState() { actorState.set(QueryActorStateResponse.getDefaultInstance()); } + public void resetCharacterRosterState() { + lastListCharactersByAccountRequest.set(null); + } + + public Optional lastListCharactersByAccountRequest() { + return Optional.ofNullable(lastListCharactersByAccountRequest.get()); + } + private static List defaultCharacters() { return List.of("Emberline", "Sora", "Nyx").stream() .map(ChatTestFixtures::characterByName) diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index f7d8149ad0..9fbc959640 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -67,7 +67,9 @@ class TelnetGatewayGameSessionAccountCrossServiceIntegrationTest { "stub-secret-key-for-tests-1234567890"; private static final long TENANT_ID = 1L; private static final long ACCOUNT_ID = 7L; + private static final String SORA_EMAIL = "sora@example.com"; private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + private static final String NYX_EMAIL = "nyx@example.com"; private static final long NYX_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; @@ -175,18 +177,15 @@ void telnetReconnectAfterRevocationFailsPlayAdmission() throws Exception { this::openTelnetClient, GameplayTelnetScenarios.demoAdmission(READY_LOOK_TEXT), client -> - assertThat(client.readLineContaining("ERROR JOIN_REQUIRED")) - .contains("ERROR JOIN_REQUIRED") - .contains( - "Membership is required before PLAY. " - + "Run REALMS first, then JOIN ."))) { + assertThat(client.readLineContaining("ERROR WORLD_ACCESS_DENIED")) + .contains("ERROR WORLD_ACCESS_DENIED") + .doesNotContain("JOIN_REQUIRED") + .doesNotContain("Run REALMS "))) { assertThat(scenario.responses()) - .anyMatch(response -> response.contains("ERROR JOIN_REQUIRED")) - .anyMatch( + .anyMatch(response -> response.contains("ERROR WORLD_ACCESS_DENIED")) + .noneMatch( response -> - response.contains( - "Membership is required before PLAY. " - + "Run REALMS first, then JOIN .")); + response.contains("JOIN_REQUIRED") || response.contains("Run REALMS ")); } } @@ -227,7 +226,7 @@ void telnetAndGatewayWebSocketCanMoveNorthOnSharedRuntime() throws Exception { this::openTelnetClient, GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT)); GameplayWebSocketDriver webSocketClient = - openReadyGatewayWebSocketClient("sora@example.com", "Sora", "gateway-sora")) { + openReadyGatewayWebSocketClient(SORA_EMAIL, "Sora", "gateway-sora")) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); telnetClient.sendLine("MOVE north"); @@ -497,10 +496,15 @@ void telnetReconnectAfterRevocationFailsClosed() throws Exception { this::openTelnetClient, READY_LOOK_TEXT, client -> - assertThat(client.readLineContaining("ERROR JOIN_REQUIRED")) - .contains("ERROR JOIN_REQUIRED"))) { + assertThat(client.readLineContaining("ERROR WORLD_ACCESS_DENIED")) + .contains("ERROR WORLD_ACCESS_DENIED") + .doesNotContain("JOIN_REQUIRED") + .doesNotContain("Run REALMS "))) { assertThat(scenario.responses()) - .anyMatch(response -> response.contains("ERROR JOIN_REQUIRED")); + .anyMatch(response -> response.contains("ERROR WORLD_ACCESS_DENIED")) + .noneMatch( + response -> + response.contains("JOIN_REQUIRED") || response.contains("Run REALMS ")); } } @@ -609,8 +613,8 @@ void telnetWhisperDeliversTargetAndObserverViews() throws Exception { GameplayTelnetScenarios.openReadyTrio( this::openTelnetClient, characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), - characterAdmission("sora@example.com", "Sora"), - characterAdmission("nyx@example.com", "Nyx"))) { + characterAdmission(SORA_EMAIL, "Sora"), + characterAdmission(NYX_EMAIL, "Nyx"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -656,7 +660,7 @@ void telnetSayDeliversRoomListenerView() throws Exception { GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), - characterAdmission("sora@example.com", "Sora"))) { + characterAdmission(SORA_EMAIL, "Sora"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -689,7 +693,7 @@ void telnetTellDeliversTargetView() throws Exception { GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), - characterAdmission("sora@example.com", "Sora"))) { + characterAdmission(SORA_EMAIL, "Sora"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -723,8 +727,8 @@ private static synchronized void ensureTestServicesStarted() { try { stack = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) - .mapAccountId("sora@example.com", SORA_ACCOUNT_ID) - .mapAccountId("nyx@example.com", NYX_ACCOUNT_ID) + .mapAccountId(SORA_EMAIL, SORA_ACCOUNT_ID) + .mapAccountId(NYX_EMAIL, NYX_ACCOUNT_ID) .withSocialEnabled(true) .withGameLogicProps( Map.of(