diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8ffe77bb8f..15afae6f35 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: @@ -1256,7 +1255,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/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index aa1c520159..731f973640 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,15 +10,15 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- The management-owner UUID candidate adds `game_instances.owner_account_uuid` for the exact canonical Account identity and keeps every retained `owner_account_id` BIGINT unchanged as internal historical evidence. Unmapped retained rows have no canonical owner and cannot satisfy owner-self checks; no UUID is derived from a numeric value. New owner requests reject numeric, nil or noncanonical Account selectors before dependency calls or mutation. Inside the owner transaction, `StartSession` locks tenant rows with no canonical UUID and any status other than exact `STOPPED`, then fails with `OWNER_ACCOUNT_IDENTITY_UNAVAILABLE` if such active or uncertain legacy-owner evidence exists; this conservative refusal does not assert that a row belongs to the requesting Account. `RestartSession` rejects a missing or noncanonical owner UUID before changing the row or Redis runtime state. Stop, readback, and pre-termination compensation remain available and preserve raw numeric evidence. This is app-layer containment, not owner mapping or activation: V10.1 still permits an older binary to insert numeric-only rows or reactivate retained rows, so deployment must quiesce or otherwise fence every pre-UUID numeric-owner writer before this path is enabled. Enablement also remains gated on the owner-run deployed migration-history inventory and exact retained-owner readback recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). UUID owner storage and DTO/readback convergence do not supply the missing Account operator authorization-reference, mutation-digest or durable operator-result contracts. The separate gameplay session/presence carrier remains unpublished, and runtime catalog, membership and credential activation remain held back. The focused service and repository unit classes passed with 55 and 4 cases; both Docker-backed PostgreSQL cases were skipped locally, so guard execution, row preservation and lock behavior remain unverified against PostgreSQL. +- The management-owner UUID candidate adds `game_instances.owner_account_uuid` for the exact canonical Account identity and keeps every retained `owner_account_id` BIGINT unchanged as internal historical evidence. Unmapped retained rows have no canonical owner and cannot satisfy owner-self checks; no UUID is derived from a numeric value. New owner requests reject numeric, nil or noncanonical Account selectors before dependency calls or mutation. Inside the owner transaction, `StartSession` locks tenant rows with no canonical UUID and any status other than exact `STOPPED`, then fails with `OWNER_ACCOUNT_IDENTITY_UNAVAILABLE` if such active or uncertain legacy-owner evidence exists; this conservative refusal does not assert that a row belongs to the requesting Account. `RestartSession` rejects a missing or noncanonical owner UUID before changing the row or Redis runtime state. Stop, readback, and pre-termination compensation remain available and preserve raw numeric evidence. This is app-layer containment, not owner mapping or activation: V10.1 still permits an older binary to insert numeric-only rows or reactivate retained rows, so deployment must quiesce or otherwise fence every pre-UUID numeric-owner writer before this path is enabled. Enablement also remains gated on the owner-run deployed migration-history inventory and exact retained-owner readback recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). UUID owner storage and DTO/readback convergence do not supply the missing Account operator authorization-reference, mutation-digest or durable operator-result contracts. Runtime catalog, membership and credential activation remain held back. The focused service and repository unit classes passed with 55 and 4 cases; both Docker-backed PostgreSQL cases were skipped locally, so guard execution, row preservation and lock behavior remain unverified against PostgreSQL. -- V9.1 adds a nullable, non-nil `gameplay_command.account_uuid` storage slot and exact repository readback for a verified producer's canonical Account identity. It preserves the complete existing row and numeric `account_id` evidence without deriving or backfilling a UUID. The current command ingress still uses its older carrier until the consumer correction is integrated; retained rows without authenticated mapping cannot become canonical UUID evidence. Storage availability alone does not prove caller authorization, retained-command replay, or activation of the denied credential and membership paths. +- The published [#2932 gameplay carrier](https://github.com/benhook1013/FireMUD/pull/2932) carries the canonical Account UUID unchanged into V9.1's `gameplay_command.account_uuid` slot. It preserves complete existing command rows and numeric `account_id` evidence without deriving or backfilling UUIDs; retained rows without authenticated mapping cannot become canonical identity evidence. This carrier and storage do not prove retained-command replay, complete owner/consumer handoff, or caller authorization, and do not activate the denied credential and membership paths. Component implementation and proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). - The current Game Session migration order preserves the parent's V7 catalog-revision audit, V8 legacy-bootstrap repair, and V9 initial-admission ledger; this candidate's authored-world source intake, retained tenant association, and command UUID storage are V7.1, V8.1, and V9.1 respectively. The parent V10 run-owned launch ledger is preserved, followed by this child's byte-identical owner UUID migration at V10.1. These filename changes resolve source-tree version collisions only and do not establish any deployed Flyway history. Before dependent catalog or command paths activate, verify the exact deployed Game Session history and owner-readback of retained source, snapshot, association, and command rows. Preserve all rows and evidence; unknown provenance remains unresolved. Do not use Flyway repair, out-of-order execution, identity casting, or data cleanup to reconcile prior history. No deployed-history or retained-row readback proof is claimed here. - The shared Gateway connect-context codec now declares and verifies the complete signed-context shape and has local vectors, but first-party runtime parsing remains fail-closed. It does not admit the target context until the independent Gateway Ed25519 verification key is published, Account-to-tenant UUID mapping is available, and the real Account exchange/source-evidence path is proved. Codec and vector presence is not a live issuer/consumer handoff or gameplay-admission proof. -- The Account membership client rejects noncanonical, nil or numeric Account/tenant selectors before stub/channel use and preserves exact UUID request echoes. This is boundary validation, not Account authorization. The current numeric session/catalog carriers still lack the proved canonical UUID handoff required by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions); numeric stringification cannot satisfy that handoff. The complete signed-context parser, Account runtime RPC and credential producer remain denied; component and runtime proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). +- Game Session's Account carriers validate and preserve canonical non-nil UUIDs under the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions), including sessions, Account-qualified client requests and presence. Unreadable older session/presence records fail closed without deleting their retained values. This is boundary validation, not Account authorization or an authenticated retained-row mapping. Tenant/catalog carriers, cross-owner UUID support and complete signed-context proof remain unfinished; the Account runtime RPC and first-party credential paths remain denied. Component and runtime proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). - The unwired Game Session tenant-source client and authored-world intake implementation are packaged in successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923); the prerequisite producer remains in #2915. They consume the separate [Game Design tenant-source read](../game-design-service/api-contracts.md#runtime-tenant-identity-read-for-game-session), requiring file-backed workload mTLS and exact namespace, request and canonical UUID echoes before returning typed provenance. That source read proves neither a retained Game Session numeric-key association nor catalog enrollment, a realm/namespace, a runtime target or admission. Game Session remains the sole persister of its resolved catalog and pointer; canonical UUID intake and propagation into those current numeric carriers remain required before the denied first-party paths can activate. Exact proof and activation limits remain in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.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 8bc0f84aba..b2e1365e14 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,16 +6,34 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The shared-auth successor to #2929 carries the exact canonical non-nil Account UUID through ordinary JWT `sub`/`accountId` matching, session identity helpers and delegated gRPC context. Numeric, nil, noncanonical, whitespace-normalized and non-string identities are rejected; tenant, private-row, character and session identifiers retain their separate declared types. A genuinely account-free internal workload omits `accountId`; an internal flag cannot discard a present malformed identity. The focused Common Security full check passed 34 tasks with all 122 unit cases executed and no failures or skips, including callback-context cleanup and malformed internal-identity denial. This is local helper/interceptor proof, not fresh-image or live authentication proof. Game Session's legacy numeric presence-viewer self-service cannot establish Account UUID authority and is unavailable; its existing tenant-role boundary remains. Interim Social numeric self-service and sender-bound mail likewise remain unavailable pending the approved complete Social UUID storage/API/consumer child after [#2932](https://github.com/benhook1013/FireMUD/pull/2932). No retained rows or published migrations are rewritten, and this correction does not complete #2932's gameplay carriers or enable admission. +Current reconciliation of [#2932](https://github.com/benhook1013/FireMUD/pull/2932) normally incorporates [#2969](https://github.com/benhook1013/FireMUD/pull/2969) at exact head `783dd1ea6bcd3b76cae474a032f0a551066a00ee`. All 116 preserved carrier paths remain: 69 are byte-identical and the other 47 changed only where the incoming parent overlaps. Six necessary parent runtime or fixture adaptations bring the unique composed delta to 122 files; Overseer approved this exact alignment-only scope, without waiving provider limits or authorizing new capability. The base/head hashes and runner evidence below remain historical source checkpoints, not proof for this composed state. +The corrected composed Account, Game Session, TCP Proxy, Common Test Support and Common Security checks, three service JAR builds, formatting/static analysis and documentation passed in 1 minute 16 seconds (232 tasks: 28 executed, 204 up-to-date). Game Session newly executed 2,256 unit, 18 integration and one cross-service cases without failures or errors; 17 unit, 155 integration and 35 cross-service cases skipped. Account's 662 unit, Common Test Support's 51 unit, Common Security's 122 unit and TCP's 194 unit, seven integration and three cross-service clean results were up-to-date in this final invocation, not new executions. All 178 Account integration cases and 14 TCP cross-service cases skipped without native Docker. The reconciliation preserves current-pointer/lifecycle/JOIN/CAS/expiry checks and mutation-free unavailable `LOGOUT`; explicit UUID fixtures and complete LEFT evidence replace malformed legacy assertions, not the production guards. No skipped case, historical runner result or synthetic tenant fixture establishes current-head PostgreSQL, retained-Redis, fresh-image, authenticated cross-owner or enabled admission proof. Runtime paths and the Account ring mount remain denied or unpublished. + +The gameplay Account-UUID carrier is published as [#2932](https://github.com/benhook1013/FireMUD/pull/2932), based on #2929 `67dd8be6b3ef9d886e4b1dd26ec719cf9e29e4b3`. Exact-head [CI 36933819297](https://github.com/benhook1013/FireMUD/actions/runs/36933819297) on `05313dc921aafe4b09b9c2b2649b2097bdc9892d` passed the full Account job and executed 124 listed strict Account cases without skips, failures or errors. Six early Game Session PostgreSQL gates executed 24 cases cleanly; its wider job was canceled after 15 Communication WebSocket cross-service failures, and TCP cross-service logged 13 failures with its database verifier skipped. TCP artifacts show successful LOGIN followed by PLAY denial: Game Session supplies its numeric catalog tenant key where the Account client requires a canonical tenant UUID, so the call fails before the RPC. Resolving the owner-backed UUID association and carrying it through the complete request/response predicates remains required work; no inferred mapping or relaxed guard is permitted. These are component proofs, not complete gameplay admission or transport proof. The independent whole-carrier review accepted and corrected two retained-Redis defects: unreadable presence is preserved by removal, re-registration and index pruning, and unreadable first-party context produces controlled invalid-context denial without persisted-context fallback. All 172 focused presence/LOGIN/PLAY unit cases executed with zero skips, failures or errors; formatting, Checkstyle, SpotBugs and documentation checks passed. Corrected-head CI, retained-Redis runtime and complete transport proof remain open. Game Logic/Social numeric sender/storage, Entity actor ownership, moderation consumers, complete Account authority and authenticated admission remain required owner work; no numeric aliases are inferred. Runtime activation, the membership RPC and Account ring mount remain denied. + +The canonical profile/management-owner front is based on exact #2923 `699a25e022c9224d24b7a491ee4ab1d4a67f22f2`. Game Session owner requests, storage, readback and owner-self comparison use canonical UUIDs while V10.1 retains numeric owner evidence unchanged and unmapped. The closed version-2 retained-tenant snapshot binds both truthful owner slots; source locks, exact approval and immutable association readback remain required. Before enablement, the owner must inventory deployed migration history and read back the exact retained numeric and UUID owner slots; deployed-history provenance and readback are not established here. Demo seeding no longer invents an Account owner without an authoritative source. This does not activate catalog enrollment, the membership RPC or credentials, nor implement Account operator-reference/digest authorization. The shared-JWT successor and published [#2932 gameplay session/presence carriers](https://github.com/benhook1013/FireMUD/pull/2932) remain distinct proof boundaries; publication and overlapping paths do not prove end-to-end admission. + +The shared-auth successor to #2929 carries the exact canonical non-nil Account UUID through JWT `sub`/`accountId` matching, session identity helpers and delegated gRPC context. It rejects numeric, nil, noncanonical, whitespace-normalized and non-string identities while preserving the declared types of tenant, private-row, character and session identifiers. Account-free internal workloads omit `accountId`, and an internal flag cannot discard a malformed present identity. The focused Common Security check executed all 122 unit cases without failures or skips; this is helper/interceptor proof, not fresh-image or live authentication proof. Game Session's legacy numeric presence-viewer self-service and interim Social numeric self-service/sender-bound mail remain unavailable pending their UUID owner work. No retained rows or published migrations are rewritten, and this successor does not prove end-to-end admission or enable runtime paths. + +### Earlier Checkpoint Evidence + +The unpublished Game Session Account-UUID carrier now incorporates #2929's reconciled grant-containment checkpoint `67dd8be6b3ef9d886e4b1dd26ec719cf9e29e4b3` through normal ancestry. Its corrected fake Account and Entity services preserve explicit Account UUIDs; synthetic load actors use registered UUID-to-character associations, not numeric Account aliases. FRIENDS direct selectors are UUIDs while roster ordinals and character/session/tenant selectors stay distinct. Negative fixture tests reject numeric, noncanonical, nil and null Account selectors without changing valid profile readback. The unique scope is115files and remains unpublished pending cap treatment. The earlier corrected-fixture shared-support/Game Session/TCP checks and both affected JARs passed189tasks(64executed/125up-to-date). Shared44unit and TCP194unit/7integration/3cross-service cases executed cleanly; Game Session18non-PostgreSQL integration and1cross-service executed cleanly, while its1,773unit results were up-to-date from the preceding same-code run. Game Session skipped17unit/135integration/33cross-service cases; TCP skipped14cross-service cases without Docker. No skipped case proves positive cross-service admission. The existing synthetic numeric tenant fixture is not owner provenance or a complete authenticated snapshot. Production Game Logic/Social numeric sender authority/storage and Entity's numeric actor-owner lookup are separate remaining consumer/data boundaries, not fixed by these fixtures. Runtime activation and section completion remain denied. Final composed Account/Game Session/TCP/shared-support checks, all three service JARs and docs passed218tasks(27executed/4from-cache/187up-to-date). Account517unit cases newly executed cleanly, while all161Account PostgreSQL cases skipped and other modules' test tasks were up-to-date. Stable patch ID `3c1e7ccb70b1f8256a70044afbcb90e2a7acd885` is unchanged for the entire unique services/protos patch across the parent merge; only the seven incoming correction paths change from the preceding carrier. Earlier merge/proof reports below are historical checkpoints. + +The local gameplay Account-UUID carrier now normally incorporates corrected published #2929 `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6`, including the username-bound and typed JDBC UUID fixture corrections. Composed Account/Game Session/shared-support checks, both JARs and documentation passed163tasks(18executed/145up-to-date). The preceding same-code Game Session executions remain1,773unit,18non-PostgreSQL integration and1cross-service without failures/errors; final test tasks were up-to-date rather than new executions. Account PostgreSQL and Game Session PostgreSQL/cross-service skips remain explicit. The exact corrected parent runner proof is pending. The child remains108unique files and unpublished; neither reconciliation nor cached/up-to-date results establish runtime activation or section completion. The following earlier parent merges and proof reports are chronological history. +The shared-auth successor to #2929 carries the exact canonical non-nil Account UUID through ordinary JWT `sub`/`accountId` matching, session identity helpers and delegated gRPC context. Numeric, nil, noncanonical, whitespace-normalized and non-string identities are rejected; tenant, private-row, character and session identifiers retain their separate declared types. A genuinely account-free internal workload omits `accountId`; an internal flag cannot discard a present malformed identity. The focused Common Security full check passed 34 tasks with all 122 unit cases executed and no failures or skips, including callback-context cleanup and malformed internal-identity denial. This is local helper/interceptor proof, not fresh-image or live authentication proof. Game Session's legacy numeric presence-viewer self-service cannot establish Account UUID authority and is unavailable; its existing tenant-role boundary remains. Interim Social numeric self-service and sender-bound mail likewise remain unavailable pending the approved complete Social UUID storage/API/consumer child after [#2932](https://github.com/benhook1013/FireMUD/pull/2932). No retained rows or published migrations are rewritten, and this correction does not prove end-to-end admission or enable runtime paths. The known legacy realm-grant mutation boundary now fails closed: otherwise-valid authenticated privileged POST/DELETE requests return `AUTH_UNAVAILABLE` before service dispatch, and direct grant/revoke service calls reject before repository access. Malformed and unauthorized requests retain their existing denial checks. This preserves retained four-field grant rows rather than revising them without lifecycle authority or hard-deleting their history. On owning #2923, the Account full check, formatting/static analysis, service JAR and documentation passed70tasks(23executed/47up-to-date), with511unit cases executed without skips/failures/errors. Strict readback confirms the two HTTP and two direct-service denial cases each executed once, including changed payload under the same request ID and both verbs' unauthenticated/nonprivileged denial. All159PostgreSQL cases skipped without local Docker; this is unit/no-dispatch proof, not database or deployed runtime proof. It does not implement ADR 0138's lifecycle-qualified authorization, bounded expiry, idempotent mutation, tombstones, event delivery or active-binding ejection; those remain required pre-v1 owner work. No runtime path or Account ring mount is enabled. The normally composed management child passed full Account/Game Session/shared-support checks, both service JARs and docs164tasks(29executed/135up-to-date), with517Account unit cases newly executed without skips/failures/errors; Game Session and shared-support test tasks were up-to-date. All161Account PostgreSQL cases skipped locally. The following source-head reports retain their historical attribution, not current-head runner or activation proof. Exact corrected #2929 source `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6` [CI36912843232](https://github.com/benhook1013/FireMUD/actions/runs/36912843232) completed aggregate FAILURE but strictly passed the V10 migration, changed-owner snapshot and two Account profile cases, each executed once with zero skips/failures/errors. The Account UUID suite14, snapshot suite4 and owner migration suite1 were clean. This proves the corrected PostgreSQL component behavior and recovery from the fixture username/binding failures below. Wider Game Session reached16CommunicationWebSocket behavioral assertions before cancellation; expected/actual values were absent from emitted logs and remain under bounded artifact diagnosis, not presumed fixed by the unpublished108-file carrier. Other aggregate jobs remain red; runtime activation and merge readiness are not established. See the dated runner readback and artifact-download safety follow-up in [AI observations](../ai-observations.md). -Exact #2929 source `73e19d7f8e74f8fa684c56ca0139ddac0751d31e` [CI36909989685](https://github.com/benhook1013/FireMUD/actions/runs/36909989685) completed aggregate FAILURE. The new management-owner migration case executed once and passed strict PostgreSQL verification, as did the four-case retained snapshot suite including exact changed-owner digest binding. Both new Account profile cases executed but failed during creation because their generated usernames exceeded `accounts.username VARCHAR(50)`; the artifact proves that constraint violation, not an identity/readback assertion failure. The longer Game Session cross-service task failed34of35cases during shared fixture setup because PostgreSQL rejected a string JDBC bind for the UUID owner column. Those fixtures now keep the full random suffix with shorter usernames and use a typed UUID bind with a focused assertion. The affected full Account/Game Session/shared-support checks and both JARs passed162tasks(36executed/126up-to-date); local PostgreSQL cases remain skipped, so corrected-head runner recovery proof is still required. Python, shared dev-tool and other module failures remain separately open, and none of these results enables runtime paths. See the dated [JDBC UUID observation](../ai-observations.md). +The local gameplay Account-UUID child normally incorporates published [#2929](https://github.com/benhook1013/FireMUD/pull/2929) `73e19d7f8e74f8fa684c56ca0139ddac0751d31e`. Both gameplay carriers and the new profile/management-owner correction are retained; the resulting unique patch remains108files and unpublished pending cap treatment. Composed Account/Game Session/shared-support checks, both JARs, formatting/static analysis and docs passed165tasks(50executed/8from-cache/107up-to-date). Game Session executed1,773unit,18non-PostgreSQL integration and1cross-service cases without failures/errors;17unit/135integration/33cross-service skipped. Account514unit and161skipped PostgreSQL results were reused from cache, not newly executed. A deterministic path/content comparison found no changes outside the incoming parent's file set relative to the preserved carrier head, and no unique child path outside its existing file set relative to #2929; the six actual overlapping code/document resolutions were inspected. Normal ancestry retains both original implementations, not a replacement patch or rewritten history. All runtime activation, PostgreSQL execution and live handoff gates remain open; no oversized candidate is published. The two preceding runs below are historical component proof, not execution evidence for this changed composed state. -The canonical profile/management-owner front is based on exact #2923 `699a25e022c9224d24b7a491ee4ab1d4a67f22f2`. Game Session owner requests, storage, readback and owner-self comparison use canonical UUIDs while V10.1 retains numeric owner evidence unchanged and unmapped. The closed version-2 retained-tenant snapshot binds both truthful owner slots; source locks, exact approval and immutable association readback remain required. Before enablement, the owner must inventory deployed migration history and read back the exact retained numeric and UUID owner slots; deployed-history provenance and readback are not established here. Demo seeding no longer invents an Account owner without an authoritative source. This does not activate catalog enrollment, the membership RPC or credentials, nor implement Account operator-reference/digest authorization. The shared-JWT successor and separate published [#2932 gameplay session/presence carriers](https://github.com/benhook1013/FireMUD/pull/2932) remain distinct proof boundaries; publication and overlapping paths do not prove end-to-end admission. +The preserved local Game Session UUID child normally incorporates published Account parent `b93efaedbaec8a36294a594a946a010641e345b4` at `5c12cd690929b935a7169fed456e50e028a1d284`. Its two newly imported availability tests now use the existing exact canonical Account UUID fixture rather than a numeric Account selector; tenant/lifecycle/no-mutation predicates are unchanged. Composed Account/Game Session/Common Test Support checks, both JARs, formatting/static analysis and docs passed164tasks(82executed/29from-cache/53up-to-date). Game Session executed1,767unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors, while17unit/133integration/33cross-service cases skipped. Account508unit and159skipped PostgreSQL results and Common Test Support43unit results came from cache, not new execution. Normal ancestry retains the original carrier preservation commit and exact corrected parent; only the parent's availability and port-fixture changes and the two required UUID test adaptations alter the preceding Game Session subtree. The child remains108unique files and unpublished pending cap treatment. All activation and live producer/consumer gates remain closed. +The local Game Session Account-UUID carrier candidate normally incorporates published Account parent `91c062f6b43159ee57a3d53c82e940014728047f` at `b26efb3fdcc6b4ed095353fb6eca189a0c9923a7`, preserving all preceding Game Session service hunks. Composed Account/Game Session full checks and JARs, links and Markdown passed154tasks(79executed/13from-cache/62up-to-date). Game Session executed1,752unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors;17unit,133integration and33cross-service cases skipped. Account's508unit and159skipped PostgreSQL results were restored from cache, not newly executed in that composed run. All PostgreSQL proof limits remain explicit. The candidate has108unique files, including its required owner/status documents, and remains unpublished pending cap treatment. + +The canonical Account-identity correction in #2929 is based on exact #2923 `b93efaedbaec8a36294a594a946a010641e345b4`. Game Session owner requests, storage, readback and owner-self comparison use canonical UUIDs while V10 retains numeric owner evidence unchanged and unmapped. The closed version-2 retained-tenant snapshot binds both truthful owner slots; source locks, exact approval and immutable association readback remain required. Demo seeding no longer invents an Account owner without an authoritative source. This repairs the previous numeric StartSession carrier rejection, not complete catalog enrollment, Account operator-reference/digest authorization, membership RPC or credential activation. The unmerged gameplay child stays unpublished pending its actual unique-scope proof. +Exact #2929 source `73e19d7f8e74f8fa684c56ca0139ddac0751d31e` [CI36909989685](https://github.com/benhook1013/FireMUD/actions/runs/36909989685) completed aggregate FAILURE. The new management-owner migration case executed once and passed strict PostgreSQL verification, as did the four-case retained snapshot suite including exact changed-owner digest binding. Both new Account profile cases executed but failed during creation because their generated usernames exceeded `accounts.username VARCHAR(50)`; the artifact proves that constraint violation, not an identity/readback assertion failure. The longer Game Session cross-service task failed34of35cases during shared fixture setup because PostgreSQL rejected a string JDBC bind for the UUID owner column. Those fixtures now keep the full random suffix with shorter usernames and use a typed UUID bind with a focused assertion. The affected full Account/Game Session/shared-support checks and both JARs passed162tasks(36executed/126up-to-date); local PostgreSQL cases remain skipped, so corrected-head runner recovery proof is still required. Python, shared dev-tool and other module failures remain separately open, and none of these results enables runtime paths. See the dated [JDBC UUID observation](../ai-observations.md). Account profile responses, updates and local export now carry the exact provenance-checked Account UUID, not the private row key. Before profile access the service verifies the requested Account source/readback; it then checks exact profile Account/tenant ownership. REST rejects a body/path Account mismatch, malformed/numeric/nil selectors and unauthorized callers without dispatch. Profile IDs and the current numeric tenant selector remain distinct; retained rows are not rewritten. Tenant-qualified/delegated profile routes, membership-generation authorization, Social Groups' numeric profile/presence callers and complete export semantics remain open owner work, not completed by this carrier correction. The composed Account/Game Session/Common Test Support checks, both service JARs, formatting/static analysis and documentation passed164tasks(28executed/136up-to-date). Account514unit cases and Game Session1,770unit,18non-PostgreSQL integration and1cross-service case executed without failures/errors in the preceding same-code run; final unit and Game Session test tasks were up-to-date, not fresh executions. Game Session skipped17unit,135integration and33cross-service cases; all161Account PostgreSQL cases skipped locally without Docker. This includes the new V10 migration, snapshot owner-change binding and two Account profile source/readback cases: they compile and are mandatory in early strict CI but have not executed. Shared43unit results were reused, not newly executed. Actionlint,23CI-scope contracts, Flyway sanity(12sets/128files) and diff hygiene passed. Fresh-image, current-head runner database and authenticated live handoff/activation proof remain required. @@ -34,7 +52,7 @@ Exact bootstrap UUID source `56a222bf289caa710285bf8655eee1d04161b22e` [CI368884 An additional Account-local PostgreSQL case holds the exact composite generation snapshot, proves that concurrent issuer and tenant advances are blocked by that holder's exact backend, then verifies generation/source-version advancement with the independent Account fence unchanged. It also preserves membership authority when the requested tenant-authority map is empty and rejects a missing membership scope without enrollment. This is a repository linearization prerequisite, not the complete immutable evidence bundle, registry, credential producer, or cross-store authorization. Local Account check/JAR and docs passed70tasks(14executed/56up-to-date); the existing506unit results were up-to-date, not newly executed, and all159PostgreSQL cases compiled/discovered but skipped without Docker. The new method is mandatory in strict CI; executed proof is pending. Runtime RPC, credential/context, catalog and ring-mount gates remain closed. -The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Other numeric DTO, catalog and cross-service consumers are explicitly unfinished; this component does not establish a working end-to-end login/admission path. Game Session V9.1 separately adds exact command UUID storage without altering or inventing identities for retained numeric rows. The consumer-carrier correction remains a separate unpublished candidate. +The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Game Session's published consumer carrier preserves canonical Account UUIDs in LOGIN, sessions, presence, Account-qualified client requests and V9.1 command storage; it no longer stringifies private numeric Account keys. Retained command evidence is preserved without inferred mapping or backfill, and unreadable retained Redis session/presence values fail closed without deletion. Other numeric DTO, tenant/catalog carriers and cross-service owners remain unfinished; this does not establish a working authenticated end-to-end login/admission path. First-party credential/context parsing, Account runtime membership and catalog activation remain denied. Local consolidated Account/Game Session full checks and JARs passed (156 tasks, 72 executed/84 up-to-date), including formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account's 502 unit cases passed in the preceding same-code execution; their final task was up-to-date, not a second execution. All 149 Account PostgreSQL cases compiled/discovered and skipped without Docker, including the three new persisted-identity/profile no-mutation cases. Game Session executed 1,747 unit, 18 non-PostgreSQL integration and one cross-service case; 17 unit, 133 integration and 33 cross-service cases skipped, including five new command-storage/migration cases. The earlier possible-null integration fixture readback defect was corrected with explicit required-row checks, not an analyzer suppression. Ring publication infrastructure is an open Platform Operations prerequisite; its mount and all previously denied activation paths remain held back. 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/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 6b86f81cdc..d0a9fe5995 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -17,6 +17,8 @@ import org.junit.jupiter.api.Test; class AccountRuntimeStubServerCompatibilityTest { + private static final String ACCOUNT_UUID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + private static final String OTHER_ACCOUNT_UUID = "c7dc8122-91d6-48c4-9484-9350c25d9b61"; private static final String REALM_ID = "8a1df0f1-1b57-465e-9c4b-bb34f8153d31"; private static final String NAMESPACE_ID = "2ea958e0-13a2-41d0-9c39-59a96cf31412"; private static final Set NON_RUNTIME_METHODS = @@ -75,7 +77,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe server.denyGameplayAdmission(); var existingButNonAdmitting = - stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, "11")); assertThat(existingButNonAdmitting.getMembershipExists()).isTrue(); assertThat(existingButNonAdmitting.getGameplayAdmissionAllowed()).isFalse(); assertThat(existingButNonAdmitting.getMembershipLifecycleState()).isEqualTo("ACTIVE"); @@ -84,7 +86,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe .containsEntry(existingButNonAdmitting.getTenantId(), "1"); server.setMembershipExists(false); - var missing = stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + var missing = stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, "11")); assertThat(missing.getMembershipExists()).isFalse(); assertThat(missing.getGameplayAdmissionAllowed()).isFalse(); assertThat(missing.getMembershipLifecycleState()).isEqualTo("MISSING"); @@ -97,7 +99,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe server.setRealmAccessGranted(false); PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setTenantId("11") .setRealmId(REALM_ID) .setGameInstanceId("33") @@ -131,7 +133,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe .build()); assertThat(join.getSuccess()).isTrue(); - var afterJoin = stub.getTenantMembershipForRuntime(membershipRequest("7", "11")); + var afterJoin = stub.getTenantMembershipForRuntime(membershipRequest(ACCOUNT_UUID, "11")); assertThat(afterJoin.getMembershipExists()).isTrue(); assertThat(afterJoin.getGameplayAdmissionAllowed()).isTrue(); assertThat(afterJoin.getMembershipLifecycleState()).isEqualTo("ACTIVE"); @@ -140,7 +142,7 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe var realmGrant = stub.getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setTenantId("11") .setWorldSlug("demo") .setRealmSlug("live") @@ -179,6 +181,22 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro .setPlayerContext( validRequest.getPlayerContext().toBuilder().setRequestId(" ")) .build(), + validRequest.toBuilder() + .setPlayerContext(validRequest.getPlayerContext().toBuilder().setAccountId("7")) + .build(), + validRequest.toBuilder() + .setPlayerContext( + validRequest.getPlayerContext().toBuilder() + .setAccountId("00000000-0000-0000-0000-000000000000")) + .build(), + validRequest.toBuilder() + .setPlayerContext( + validRequest.getPlayerContext().toBuilder() + .setAccountId(ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT))) + .build(), + validRequest.toBuilder() + .setPlayerContext(validRequest.getPlayerContext().toBuilder().setSessionId(" ")) + .build(), validRequest.toBuilder().setCatalogRevision(0L).build(), validRequest.toBuilder().setPointerVersion(-1L).build()); @@ -218,6 +236,36 @@ void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { assertThat(blankSession.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(blankSession.getSuccess()).isFalse(); + var mismatchedSession = + stub.joinPublicProductionMembership( + validJoin.toBuilder() + .setPlayerContext( + validJoin.getPlayerContext().toBuilder().setSessionId("session-2")) + .build()); + assertThat(mismatchedSession.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(mismatchedSession.getSuccess()).isFalse(); + + var mismatchedAccount = + stub.joinPublicProductionMembership( + validJoin.toBuilder() + .setPlayerContext( + validJoin.getPlayerContext().toBuilder().setAccountId(OTHER_ACCOUNT_UUID)) + .build()); + assertThat(mismatchedAccount.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(mismatchedAccount.getSuccess()).isFalse(); + + var mismatchedRequest = + stub.joinPublicProductionMembership( + validJoin.toBuilder().setRequestId("different-request").build()); + assertThat(mismatchedRequest.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(mismatchedRequest.getSuccess()).isFalse(); + + var unknownScope = + stub.joinPublicProductionMembership( + validJoin.toBuilder().setConnectScopeId("unknown-connect-scope").build()); + assertThat(unknownScope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(unknownScope.getSuccess()).isFalse(); + assertThat(stub.joinPublicProductionMembership(validJoin).getSuccess()).isTrue(); server.resetRuntimeState(); @@ -233,7 +281,7 @@ void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { private static IssueDirectTextConnectScopeRequest validConnectScopeRequest() { PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setTenantId("11") .setRealmId(REALM_ID) .setGameInstanceId("33") diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index 9c81cf2871..a3a3befc92 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 @@ -1,10 +1,12 @@ package net.firedevops.firemud.test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.time.Instant; +import java.util.Locale; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; @@ -18,6 +20,9 @@ import org.junit.jupiter.api.Test; class AccountRuntimeStubServerTest { + private static final String ACCOUNT_UUID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + private static final String NIL_ACCOUNT_UUID = "00000000-0000-0000-0000-000000000000"; + @Test void authenticationCanonicalizesEmailAndRuntimeAuthoritySnapshotsAreFreshAndComplete() throws Exception { @@ -27,7 +32,7 @@ void authenticationCanonicalizesEmailAndRuntimeAuthoritySnapshotsAreFreshAndComp try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); - server.mapAccountId("demo@example.com", 7L); + server.mapAccountUuid("demo@example.com", ACCOUNT_UUID); assertThat( stub.authenticate( @@ -36,13 +41,13 @@ void authenticationCanonicalizesEmailAndRuntimeAuthoritySnapshotsAreFreshAndComp .setPassword("password") .build()) .getAccountId()) - .isEqualTo("7"); + .isEqualTo(ACCOUNT_UUID); var request = GetTenantMembershipForRuntimeRequest.newBuilder() .setPlayerContext( net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setTenantId("1") .setRequestId("request-1")) .build(); @@ -50,6 +55,8 @@ void authenticationCanonicalizesEmailAndRuntimeAuthoritySnapshotsAreFreshAndComp GetTenantMembershipForRuntimeResponse active = stub.getTenantMembershipForRuntime(request); Instant activeAfter = Instant.now(); assertThat(active.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(active.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(active.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(active.getMembershipExists()).isTrue(); assertThat(active.getGameplayAdmissionAllowed()).isTrue(); assertThat(active.getMembershipVersionMap()).containsEntry(active.getTenantId(), "1"); @@ -130,7 +137,7 @@ void authenticationCanonicalizesEmailAndRuntimeAuthoritySnapshotsAreFreshAndComp var grant = stub.getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setTenantId("1") .setWorldSlug("demo") .setRealmSlug("production") @@ -205,7 +212,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { AccountProfileJson initialProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(initialProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -214,11 +224,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setProfileJson( - """ - {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} - """) + "{\"displayName\":\"Demo-%s\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}" + .formatted(ACCOUNT_UUID)) .build()) .getSuccess()) .isTrue(); @@ -226,7 +235,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { AccountProfileJson updatedProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(updatedProfile.presenceVisibilityPolicy()).isEqualTo("PRIVATE"); @@ -236,6 +248,65 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { } } + @Test + void rejectsInvalidAccountSelectorsForRegistrationAndProfileMutation() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + server.setDefaultAccountUuid(ACCOUNT_UUID); + assertThat( + stub.updateProfile(profileUpdate(ACCOUNT_UUID, "Protected profile")).getSuccess()) + .isTrue(); + + String[] invalidAccountUuids = { + "7", ACCOUNT_UUID.toUpperCase(Locale.ROOT), NIL_ACCOUNT_UUID + }; + for (String invalidAccountUuid : invalidAccountUuids) { + assertThatThrownBy( + () -> server.mapAccountUuid("candidate@example.com", invalidAccountUuid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> server.setDefaultAccountUuid(invalidAccountUuid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> server.setPresenceVisibilityPolicy(invalidAccountUuid, "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + stub.updateProfile(profileUpdate(invalidAccountUuid, "Overwritten profile")) + .getSuccess()) + .isFalse(); + } + + assertThatThrownBy(() -> server.mapAccountUuid("candidate@example.com", null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> server.setDefaultAccountUuid(null)) + .isInstanceOf(IllegalArgumentException.class); + AuthenticateRequest candidateRequest = + AuthenticateRequest.newBuilder() + .setEmail("candidate@example.com") + .setPassword("password") + .build(); + assertThat(stub.authenticate(candidateRequest).getAccountId()).isEqualTo(ACCOUNT_UUID); + + AccountProfileJson protectedProfile = + AccountProfileJson.parse( + stub.getProfile( + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) + .getProfileJson(), + "FRIENDS_ONLY"); + assertThat(protectedProfile.displayName()).isEqualTo("Protected profile"); + assertThat(protectedProfile.presenceVisibilityPolicy()).isEqualTo("PRIVATE"); + } finally { + channel.shutdownNow(); + } + } + } + @Test void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { @@ -249,7 +320,7 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setProfileJson( """ {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} @@ -263,7 +334,10 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { AccountProfileJson resetProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(resetProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -272,4 +346,14 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { } } } + + private static UpdateProfileRequest profileUpdate(String accountUuid, String displayName) { + return UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .setProfileJson( + "{\"displayName\":\"%s\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}" + .formatted(displayName)) + .build(); + } } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 6391f74c07..0414f443d6 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -50,6 +50,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe implements AutoCloseable { private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String DEFAULT_ACCOUNT_UUID = "a7e0feac-60ab-4fd1-9002-0ad38d585db0"; private static final String MEMBERSHIP_EVENT_ID = "00000000-0000-0000-0000-000000000099"; private static final String MEMBERSHIP_EVENT_REQUEST_ID = "runtime-membership-request"; private static final Set IMPLEMENTED_RUNTIME_METHODS = @@ -70,10 +71,11 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final AtomicBoolean gameplayAvailable = new AtomicBoolean(true); private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); - private final AtomicLong defaultAccountId = new AtomicLong(1L); + private final AtomicReference defaultAccountUuid = + new AtomicReference<>(DEFAULT_ACCOUNT_UUID); private final AtomicLong nextConnectScopeId = new AtomicLong(1L); - private final Map accountIdsByEmail = new ConcurrentHashMap<>(); - private final Map profilesByAccountId = new ConcurrentHashMap<>(); + private final Map accountUuidsByEmail = new ConcurrentHashMap<>(); + private final Map profilesByAccountUuid = new ConcurrentHashMap<>(); private final Map connectScopesById = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { @@ -92,19 +94,21 @@ public List capturedAuthenticateRequests() { return List.copyOf(authenticateRequests); } - public void setDefaultAccountId(long accountId) { - defaultAccountId.set(accountId); + public void setDefaultAccountUuid(String accountUuid) { + defaultAccountUuid.set(requireCanonicalAccountUuid(accountUuid)); } - public void mapAccountId(String email, long accountId) { - accountIdsByEmail.put(EmailCanonicalization.normalize(email), accountId); + public void mapAccountUuid(String email, String accountUuid) { + accountUuidsByEmail.put( + EmailCanonicalization.normalize(email), requireCanonicalAccountUuid(accountUuid)); } - public void setPresenceVisibilityPolicy(long accountId, String visibilityPolicy) { - profilesByAccountId.compute( - accountId, + public void setPresenceVisibilityPolicy(String accountUuid, String visibilityPolicy) { + String canonicalAccountUuid = requireCanonicalAccountUuid(accountUuid); + profilesByAccountUuid.compute( + canonicalAccountUuid, (ignored, current) -> - (current == null ? StubProfile.defaultFor(accountId) : current) + (current == null ? StubProfile.defaultFor(canonicalAccountUuid) : current) .withPresenceVisibilityPolicy(visibilityPolicy)); } @@ -156,7 +160,7 @@ public void resetRuntimeState() { gameplayAvailable.set(true); allowPublicJoin.set(true); realmAccessGranted.set(true); - profilesByAccountId.clear(); + profilesByAccountUuid.clear(); connectScopesById.clear(); } @@ -171,12 +175,12 @@ public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { authenticateRequests.add(request); String canonicalEmail = EmailCanonicalization.normalize(request.getEmail()); - long accountId = accountIdsByEmail.getOrDefault(canonicalEmail, defaultAccountId.get()); - profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); + String accountUuid = accountUuidsByEmail.getOrDefault(canonicalEmail, defaultAccountUuid.get()); + profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); responseObserver.onNext( AuthenticateResponse.newBuilder() - .setAccountId(Long.toString(accountId)) - .setAuthToken("stub-token-" + accountId) + .setAccountId(accountUuid) + .setAuthToken("stub-token-" + accountUuid) .build()); responseObserver.onCompleted(); } @@ -186,7 +190,7 @@ public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { boolean exists = membershipExists.get(); - String accountSelector = request.getPlayerContext().getAccountId(); + String accountUuid = requireCanonicalAccountUuid(request.getPlayerContext().getAccountId()); String tenantSelector = request.getPlayerContext().getTenantId(); String lifecycle = membershipLifecycleState.get(); boolean admitted = gameplayAdmissionAllowed.get(); @@ -194,7 +198,7 @@ public void getTenantMembershipForRuntime( if (exists && "ACTIVE".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, + accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle, @@ -202,7 +206,7 @@ public void getTenantMembershipForRuntime( } else if (exists && !admitted && "INACTIVE".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, + accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle, @@ -210,7 +214,7 @@ public void getTenantMembershipForRuntime( } else if (!exists && !admitted && "MISSING".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, + accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle, @@ -218,9 +222,9 @@ public void getTenantMembershipForRuntime( } else { response = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(canonicalUuid(accountSelector)) - .setTenantId(canonicalUuid(tenantSelector)) - .setRequestAccountId(accountSelector) + .setAccountId(accountUuid) + .setTenantId(syntheticTenantUuid(tenantSelector)) + .setRequestAccountId(accountUuid) .setRequestTenantId(tenantSelector) .setRequestId(request.getPlayerContext().getRequestId()) .setMembershipExists(exists) @@ -234,15 +238,14 @@ public void getTenantMembershipForRuntime( } private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( - String accountSelector, + String accountUuid, String tenantSelector, String requestId, String lifecycle, boolean admitted) { boolean exists = !"MISSING".equals(lifecycle); List roles = "ACTIVE".equals(lifecycle) ? List.of("player") : List.of(); - String accountUuid = canonicalUuid(accountSelector); - String tenantUuid = canonicalUuid(tenantSelector); + String tenantUuid = syntheticTenantUuid(tenantSelector); String membershipStream = AUTHORITY_STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; List checkpoints = @@ -271,7 +274,7 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(accountUuid) .setTenantId(tenantUuid) - .setRequestAccountId(accountSelector) + .setRequestAccountId(accountUuid) .setRequestTenantId(tenantSelector) .setRequestId(requestId) .setAuthorityAvailability("AVAILABLE") @@ -333,10 +336,29 @@ private static RuntimeOutboxCheckpoint checkpoint(String streamKey, String seque .build(); } - private static String canonicalUuid(String selector) { + private static String requireCanonicalAccountUuid(String selector) { + if (selector == null) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil"); + } + UUID parsed; + try { + parsed = UUID.fromString(selector); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil", exception); + } + if ((parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) + || !parsed.toString().equals(selector)) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil"); + } + return selector; + } + + private static String syntheticTenantUuid(String selector) { + // This stable UUID-shaped key is only a legacy synthetic-tenant test fixture. It is not + // evidence of an Account-owned tenant identity or an authenticated membership snapshot. long value = Long.parseLong(selector); if (value <= 0L || !Long.toString(value).equals(selector)) { - throw new IllegalArgumentException("runtime membership fixture selector must be canonical"); + throw new IllegalArgumentException("synthetic tenant fixture selector must be canonical"); } return "00000000-0000-0000-0000-" + String.format(Locale.ROOT, "%012d", value); } @@ -379,9 +401,10 @@ public void issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest request, StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); - if (caller.getAccountId().isBlank() + if (!isCanonicalNonNilUuid(caller.getAccountId()) || caller.getTenantId().isBlank() || caller.getRealmId().isBlank() + || caller.getSessionId().isBlank() || caller.getRequestId().isBlank() || caller.getGameInstanceId().isBlank() || caller.getPlayableStateNamespaceId().isBlank() @@ -418,6 +441,7 @@ public void issueDirectTextConnectScope( scopeId, new StubConnectScope( caller.getAccountId(), + caller.getSessionId(), request.getTenantId(), request.getRealmId(), request.getGameInstanceId(), @@ -444,6 +468,14 @@ private static boolean isCanonicalUuid(String value) { } } + private static boolean isCanonicalNonNilUuid(String value) { + if (!isCanonicalUuid(value)) { + return false; + } + UUID parsed = UUID.fromString(value); + return parsed.getMostSignificantBits() != 0L || parsed.getLeastSignificantBits() != 0L; + } + @Override public void joinPublicProductionMembership( JoinPublicProductionMembershipRequest request, @@ -453,12 +485,13 @@ public void joinPublicProductionMembership( if (request.getConnectScopeId().isBlank() || request.getRequestId().isBlank() || !request.getRequestId().equals(caller.getRequestId()) - || caller.getAccountId().isBlank() + || !isCanonicalNonNilUuid(caller.getAccountId()) || caller.getTenantId().isBlank() || caller.getSessionId().isBlank() || scope == null || !scope.expiresAt().isAfter(Instant.now()) || !scope.accountId().equals(caller.getAccountId()) + || !scope.sessionId().equals(caller.getSessionId()) || !scope.tenantId().equals(caller.getTenantId()) || !scope.realmId().equals(caller.getRealmId()) || !scope.gameInstanceId().equals(caller.getGameInstanceId()) @@ -500,9 +533,10 @@ public void joinPublicProductionMembership( @Override public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { - long accountId = Long.parseLong(request.getAccountId()); - StubProfile profile = profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); try { + String accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + StubProfile profile = + profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); responseObserver.onNext( GetProfileResponse.newBuilder() .setProfileJson( @@ -521,13 +555,13 @@ public void getProfile( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { - long accountId = Long.parseLong(request.getAccountId()); + String accountUuid = requireCanonicalAccountUuid(request.getAccountId()); AccountProfileJson profile = AccountProfileJson.parse(request.getProfileJson(), StubProfile.DEFAULT_VISIBILITY_POLICY); StubProfile existing = - profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); - profilesByAccountId.put( - accountId, + profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); + profilesByAccountUuid.put( + accountUuid, new StubProfile( profile.displayName(), profile.bio(), @@ -550,8 +584,8 @@ public void close() { private record StubProfile(String displayName, String bio, String presenceVisibilityPolicy) { private static final String DEFAULT_VISIBILITY_POLICY = "FRIENDS_ONLY"; - private static StubProfile defaultFor(long accountId) { - return new StubProfile("Demo-" + accountId, null, DEFAULT_VISIBILITY_POLICY); + private static StubProfile defaultFor(String accountUuid) { + return new StubProfile("Demo-" + accountUuid, null, DEFAULT_VISIBILITY_POLICY); } private StubProfile withPresenceVisibilityPolicy(String visibilityPolicy) { @@ -564,6 +598,7 @@ private StubProfile withPresenceVisibilityPolicy(String visibilityPolicy) { private record StubConnectScope( String accountId, + String sessionId, String tenantId, String realmId, String gameInstanceId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index a143551f83..1cb5a28f29 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -292,7 +292,8 @@ private boolean hasUsableConnectScope(Instant expiresAt) { } private boolean hasDirectTextCallerIdentity(PlayerExecutionContext context) { - return isPositiveLong(context.getAccountId()) && isPositiveLong(context.getSessionId()); + return AccountIds.isCanonicalNonNilUuid(context.getAccountId()) + && isPositiveLong(context.getSessionId()); } private boolean isPositiveLong(String value) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java index 18d933c243..d77d2c4a42 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java @@ -203,7 +203,7 @@ private String sessionAttestation( return gameplaySessionAttestationService.issueGameplaySessionAttestation( Long.toString(context.tenantId()), Long.toString(context.sessionId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(context.characterId()), gameInstanceId, canonicalRoomId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index 525f08b1ec..d5dc212732 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -160,7 +160,7 @@ public SendCommunicationResponse sendCommunication( String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); String characterId = Long.toString(context.characterId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String gameInstanceId = Long.toString(context.gameInstanceId()); SendCommunicationRequest request = SendCommunicationRequest.newBuilder() @@ -346,7 +346,7 @@ public PickupItemFromRoomResponse pickupVisibleRoomItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -449,7 +449,7 @@ public DropItemToRoomResponse dropCarriedItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -720,7 +720,7 @@ private String sessionAttestation(SessionContext context, String roomId) { return gameplaySessionAttestationService.issueGameplaySessionAttestation( Long.toString(context.tenantId()), Long.toString(context.sessionId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(context.characterId()), Long.toString(context.gameInstanceId()), canonicalRoomId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java index 3ad6c4b534..71ad8a65c5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java @@ -50,11 +50,12 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( LoggingAdminServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public EvaluateModerationPolicyResponse evaluateGameplayAdmission(long tenantId, long accountId) { + public EvaluateModerationPolicyResponse evaluateGameplayAdmission( + long tenantId, String accountId) { EvaluateModerationPolicyRequest request = EvaluateModerationPolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setScope(SCOPE_GAMEPLAY_ADMISSION) .build(); return stub().evaluateModerationPolicy(request); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java index 050a9b781b..b0e0de1d6d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java @@ -67,107 +67,110 @@ protected SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub buildStub( SocialGroupsServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public ListFriendPresenceResponse listFriendPresence(long tenantId, long accountId) { + public ListFriendPresenceResponse listFriendPresence(long tenantId, String accountId) { return callStub() .listFriendPresence( ListFriendPresenceRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId, FriendRosterFilter filter) { + public ListFriendsResponse listFriends( + long tenantId, String accountId, FriendRosterFilter filter) { return callStub() .listFriends( ListFriendsRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setFilter(filter) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId) { + public ListFriendsResponse listFriends(long tenantId, String accountId) { return listFriends(tenantId, accountId, FriendRosterFilter.FRIEND_ROSTER_FILTER_ALL); } - public AddFriendResponse addFriend(long tenantId, long accountId, long friendAccountId) { + public AddFriendResponse addFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .addFriend( AddFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } - public RemoveFriendResponse removeFriend(long tenantId, long accountId, long friendAccountId) { + public RemoveFriendResponse removeFriend( + long tenantId, String accountId, String friendAccountId) { return callStub() .removeFriend( RemoveFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } public RemoveFriendByOrdinalResponse removeFriendByOrdinal( - long tenantId, long accountId, int ordinal) { + long tenantId, String accountId, int ordinal) { return callStub() .removeFriendByOrdinal( RemoveFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setOrdinal(ordinal) .build()); } - public GetFriendResponse getFriend(long tenantId, long accountId, long friendAccountId) { + public GetFriendResponse getFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .getFriend( GetFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } - public GetFriendByOrdinalResponse getFriendByOrdinal(long tenantId, long accountId, int ordinal) { + public GetFriendByOrdinalResponse getFriendByOrdinal( + long tenantId, String accountId, int ordinal) { return callStub() .getFriendByOrdinal( GetFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setOrdinal(ordinal) .build()); } - public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, long accountId) { + public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, String accountId) { return callStub() .getFriendRosterSummary( GetFriendRosterSummaryRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } - public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, long accountId) { + public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, String accountId) { return callStub() .getFriendPresencePolicy( GetFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } public UpdateFriendPresencePolicyResponse updateFriendPresencePolicy( long tenantId, - long accountId, + String accountId, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy visibilityPolicy) { return callStub() .updateFriendPresencePolicy( UpdateFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setVisibilityPolicy(visibilityPolicy) .build()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java index c946577a32..cd1a5db42e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidence.java @@ -3,15 +3,18 @@ import java.time.Clock; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.gamesession.service.AccountIds; /** Shared validation for caller- and tenant-bound Account runtime authority snapshots. */ final class AccountAuthorityEvidence { private AccountAuthorityEvidence() {} static boolean hasMatchingAccountAndTenant( - String accountId, String tenantId, long expectedAccountId, long expectedTenantId) { + String accountId, String tenantId, String expectedAccountId, long expectedTenantId) { try { - return Long.parseLong(accountId) == expectedAccountId + return AccountIds.isCanonicalNonNilUuid(accountId) + && AccountIds.isCanonicalNonNilUuid(expectedAccountId) + && accountId.equals(expectedAccountId) && Long.parseLong(tenantId) == expectedTenantId; } catch (NumberFormatException ex) { return false; @@ -36,7 +39,7 @@ static boolean isValidEntitlement( static boolean isValidRealmAccessGrant( GetRealmAccessGrantForRuntimeResponse response, - long expectedAccountId, + String expectedAccountId, long expectedTenantId, String expectedWorldSlug, String expectedRealmSlug, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 4092522f01..85e0d3d5e8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.presentation.FriendPresenceViewOutput; import net.firedevops.firemud.gamesession.presentation.FriendRosterSummaryViewOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -152,7 +153,7 @@ private boolean isPlayerSafeFilter(FriendListFilter filter) { private TextCommandInterpretationResult handleAdd( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == context.accountId()) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } @@ -176,7 +177,7 @@ private TextCommandInterpretationResult handleAdd( private TextCommandInterpretationResult handleRemove( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == context.accountId()) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } @@ -432,7 +433,7 @@ private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendList private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry entry) { FriendPresenceEntry presence = entry.getPresence(); - long friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); + String friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); if (!isPlayerDisclosablePolicy(presence.getVisibilityPolicy())) { return redactedEntry(ordinal, entry, friendAccountId, "Friend #" + friendAccountId); } @@ -459,7 +460,7 @@ private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry en } private FriendPresenceViewOutput.Entry redactedEntry( - int ordinal, FriendRosterEntry entry, long friendAccountId, String displayName) { + int ordinal, FriendRosterEntry entry, String friendAccountId, String displayName) { return new FriendPresenceViewOutput.Entry( ordinal, parseOptionalLong(entry.getFriendLinkId()), @@ -499,14 +500,16 @@ private String activityState(FriendPresenceActivityState activityState) { }; } - private long requireFriendAccountId(String value) { + private String requireFriendAccountId(String value) { if (!StringUtils.hasText(value)) { throw new IllegalStateException( "Malformed friend roster friendAccountId: friendAccountId is required"); } try { - return PositiveLongParsing.requireOptionalText(value, "friendAccountId") - .orElseThrow(() -> new IllegalArgumentException("friendAccountId is required")); + if (!AccountIds.isCanonicalNonNilUuid(value)) { + throw new IllegalArgumentException("friendAccountId must be a canonical non-nil UUID"); + } + return value; } catch (IllegalArgumentException ex) { throw new IllegalStateException( "Malformed friend roster friendAccountId: " + ex.getMessage(), ex); @@ -588,13 +591,13 @@ private FriendAction parseAction(TextCommand command) { } private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction action) { - Long accountId = tryParseAccountId(action.targetToken()); + String accountId = tryParseAccountId(action.targetToken()); if (accountId != null) { return new ResolvedFriendTarget(accountId, null, null); } if (!StringUtils.hasText(action.targetToken())) { return new ResolvedFriendTarget( - 0L, + null, null, invalidUsage("FRIENDS " + action.keyword() + " ")); } @@ -603,17 +606,16 @@ private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction context, resolvePlayableStateScope(context), action.targetToken().trim()); if (character.isEmpty() || !StringUtils.hasText(character.get().getAccountId())) { return new ResolvedFriendTarget( - 0L, + null, null, friendTargetError("FRIEND_TARGET_NOT_FOUND", notFoundMessage(action.targetToken()))); } - PositiveLongParsing.ParsedPositiveLong parsedAccountId = - PositiveLongParsing.parseOptionalText(character.get().getAccountId(), "friendAccountId"); - if (!parsedAccountId.valid()) { + String resolvedAccountId = character.get().getAccountId(); + if (!AccountIds.isCanonicalNonNilUuid(resolvedAccountId)) { return new ResolvedFriendTarget( - 0L, null, malformedResolvedTargetError(action, character.get().getAccountId())); + null, null, malformedResolvedTargetError(action, resolvedAccountId)); } - return new ResolvedFriendTarget(parsedAccountId.value(), character.get().getName(), null); + return new ResolvedFriendTarget(resolvedAccountId, character.get().getName(), null); } private TextCommandInterpretationResult malformedResolvedTargetError( @@ -693,10 +695,8 @@ private FriendRosterFilter mapRosterFilter(FriendListFilter filter) { }; } - private Long tryParseAccountId(String value) { - return PositiveLongParsing.parseOptionalText(value, "friendAccountId") - .optionalValue() - .orElse(null); + private String tryParseAccountId(String value) { + return AccountIds.isCanonicalNonNilUuid(value) ? value : null; } private boolean isOrdinalToken(String value) { @@ -854,5 +854,5 @@ private record FriendAction( String invalidUsage) {} private record ResolvedFriendTarget( - long friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} + String friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 1604a04105..1d79e8bbd9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; @@ -22,7 +23,6 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; -import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; @@ -140,8 +140,8 @@ public LoginCommandHandlingResult handle( return failure(errorCode, publicErrorMessage(error, errorCode)); } - Long authenticatedAccountId = parseAccountId(authResponse.getAccountId()); - if (authenticatedAccountId == null || authenticatedAccountId <= 0) { + String authenticatedAccountId = parseAccountId(authResponse.getAccountId()); + if (authenticatedAccountId == null) { clearFailedLoginSessionState( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); @@ -165,10 +165,10 @@ public LoginCommandHandlingResult handle( Map.of("loginName", canonicalLoginName)))); } - private void invalidateStaleFirstPartyConnectContext(long sessionId, long accountId) { + private void invalidateStaleFirstPartyConnectContext(long sessionId, String accountId) { firstPartyConnectContextRegistry .find(sessionId) - .filter(connectContext -> connectContext.accountId() != accountId) + .filter(connectContext -> !Objects.equals(connectContext.accountId(), accountId)) .ifPresent(ignored -> firstPartyConnectContextRegistry.unregister(sessionId)); } @@ -233,8 +233,8 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI var verifiedContext = maybeContext.get(); if (existingSession != null - && existingSession.accountId() > 0 - && existingSession.accountId() != verifiedContext.accountId()) { + && existingSession.hasAccountIdentity() + && !Objects.equals(existingSession.accountId(), verifiedContext.accountId())) { firstPartyConnectContextRegistry.unregister(numericSessionId); return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); } @@ -275,8 +275,8 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI } if (existingSession != null - && existingSession.accountId() > 0L - && (existingSession.accountId() != verifiedContext.accountId() + && existingSession.hasAccountIdentity() + && (!Objects.equals(existingSession.accountId(), verifiedContext.accountId()) || existingSession.tenantId() != verifiedContext.tenantId())) { clearPreviousSessionForVerifiedContext(numericSessionId, existingSession, verifiedContext); } @@ -292,7 +292,7 @@ private void clearPreviousSessionForVerifiedContext( new SessionContext( sessionId, verifiedContext.tenantId(), - 0L, + null, null, 0L, null, @@ -312,7 +312,7 @@ private void clearPreviousSessionForVerifiedContext( private void persistSessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, String jwt, long bootstrapGameInstanceId, @@ -329,7 +329,10 @@ private void persistSessionContext( projectedExisting != null && projectedExisting.tenantId() == tenantId ? projectedExisting : null; - boolean sameAuthenticatedAccount = existing != null && existing.accountId() == accountId; + boolean sameAuthenticatedAccount = + existing != null + && existing.hasAccountIdentity() + && Objects.equals(existing.accountId(), accountId); Optional reusableBootstrapShell = sameAuthenticatedAccount ? Optional.empty() @@ -387,7 +390,9 @@ private void persistSessionContext( existing.playableStateScope(), existing.connectScopeId(), existing.connectRequestId()); - if (projectedExisting != null && projectedExisting.accountId() != accountId) { + if (projectedExisting != null + && projectedExisting.hasAccountIdentity() + && !Objects.equals(projectedExisting.accountId(), accountId)) { gameplayPresenceLifecycleService.clearGameplayBinding( projectedExisting, "LOGIN_ACCOUNT_CHANGED"); } else if (projectedExisting != null && projectedExisting.tenantId() != tenantId) { @@ -405,12 +410,12 @@ private void persistSessionContext( private Optional reusableBootstrapShell( SessionContext existing, long tenantId, - long accountId, + String accountId, long bootstrapGameInstanceId, net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedConnectContext, String verifiedPlayableStateScope) { if (existing == null - || existing.accountId() != 0L + || existing.hasAccountIdentity() || existing.tenantId() != tenantId || existing.bootstrapGameInstanceId() != bootstrapGameInstanceId || existing.hasGameplayBinding() @@ -426,7 +431,7 @@ private Optional reusableBootstrapShell( boolean verifiedIdentityAndTargetMatch = verifiedConnectContext.hasCompleteRoutingScope() - && verifiedConnectContext.accountId() == accountId + && Objects.equals(verifiedConnectContext.accountId(), accountId) && verifiedConnectContext.tenantId() == tenantId && verifiedConnectContext.gameInstanceId() == bootstrapGameInstanceId && Objects.equals(existing.playableStateScope(), verifiedPlayableStateScope) @@ -446,7 +451,7 @@ private Optional reusableBootstrapShell( private SessionContext authenticatedBootstrapContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, String jwt, SessionContext bootstrapShell, @@ -584,7 +589,7 @@ private void clearFailedLoginSessionState( new SessionContext( sessionId, tenantId, - 0L, + null, null, 0L, null, @@ -644,13 +649,8 @@ private SessionIdParsing.ParsedSessionId parseSessionId(String sessionIdText) { return SessionIdParsing.parse(sessionIdText); } - private Long parseAccountId(String accountIdText) { - PositiveLongParsing.ParsedPositiveLong parsed = - PositiveLongParsing.parseOptionalText(accountIdText, "accountId"); - if (!parsed.valid()) { - return null; - } - return parsed.value(); + private String parseAccountId(String accountIdText) { + return AccountIds.isCanonicalNonNilUuid(accountIdText) ? accountIdText : null; } private LoginCommandHandlingResult invalidSessionFailure(String message) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java index fe83169f9f..c3b708f381 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java @@ -32,7 +32,7 @@ public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) SessionIdParsing.parse(sessionId) .optionalValue() .flatMap(sessionContextService::findBySessionId) - .filter(context -> context.accountId() > 0L); + .filter(SessionContext::hasAccountIdentity); } catch (RuntimeException ex) { return unavailable(); } 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 028ea38bec..3b85a9bc03 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 @@ -27,6 +27,7 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; @@ -672,19 +673,19 @@ private ResolvedCharacter resolveCharacter( ListCharactersByAccountResponse response = entityManagementClient.listCharactersByAccount( Long.toString(selectedRealm.tenantId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(selectedRealm.gameInstanceId()), playableStateScope); if (response == null || response.hasError()) { throw new IllegalStateException("Character roster unavailable for selected gameplay target"); } - List roster = response.getCharactersList(); Set characterIds = new HashSet<>(); for (Character character : roster) { long characterId = requireResolvedCharacterId(character.getId()); if (!Long.toString(selectedRealm.tenantId()).equals(character.getTenantId()) - || !Long.toString(context.accountId()).equals(character.getAccountId()) + || !context.accountId().equals(character.getAccountId()) + || !AccountIds.isCanonicalNonNilUuid(character.getAccountId()) || character.getPlayableStateScope() != playableStateScope || !StringUtils.hasText(character.getName()) || !characterIds.add(characterId)) { @@ -829,7 +830,7 @@ private Optional validateRuntimeAdmission( // Only an already-bound character in the selected live runtime can identify denial cleanup; // a caller's textual selector is not actor identity or Account authority. long currentCharacterId = - context.accountId() > 0L + context.hasAccountIdentity() && context.tenantId() == selectedRealm.tenantId() && context.gameInstanceId() == selectedRealm.gameInstanceId() && context.characterId() > 0L @@ -965,7 +966,7 @@ private Optional validateMembershipResponse( if (!isPublicProductionRealm(selectedRealm)) { GetRealmAccessGrantForRuntimeResponse grantResponse = accountClient.getRealmAccessGrantForRuntime( - Long.toString(context.accountId()), + context.accountId(), Long.toString(selectedRealm.tenantId()), selectedWorld.slug(), selectedRealm.slug(), @@ -1034,7 +1035,8 @@ private static boolean hasCompleteMembershipAuthorityCarrier( if (!response.getAuthorityTuple().getUnknownFields().asMap().isEmpty()) { return false; } - if (!isCanonicalUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId())) { + if (!AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + || !isCanonicalUuid(response.getTenantId())) { return false; } if (!response @@ -1263,7 +1265,7 @@ private static PlayerExecutionContext membershipPlayerContext( long characterId, String requestId) { return PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId(caller.accountId()) .setTenantId(Long.toString(target.tenantId())) .setRealmId(Objects.toString(target.realmId(), "")) .setPlayableStateNamespaceId(Objects.toString(target.playableStateNamespaceId(), "")) @@ -1537,9 +1539,9 @@ private boolean isSafeMembershipAuthorityResponse( || !StringUtils.hasText(response.getAccountId()) || !StringUtils.hasText(response.getTenantId()) || !StringUtils.hasText(response.getEvaluatedAt()) - || !isCanonicalUuid(response.getAccountId()) + || !AccountIds.isCanonicalNonNilUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId()) - || !response.getRequestAccountId().equals(Long.toString(context.accountId())) + || !response.getRequestAccountId().equals(context.accountId()) || !response.getRequestTenantId().equals(Long.toString(selectedRealm.tenantId())) || !response.getRequestId().equals(requestId)) { return false; @@ -1856,7 +1858,7 @@ private void recordResumeDeniedIfApplicable( && context.gameInstanceId() == requestedGameInstanceId; boolean sameGameplayIdentity = sameRuntimeTarget - && context.accountId() > 0L + && context.hasAccountIdentity() && context.characterId() > 0L && requestedCharacterId > 0 && context.characterId() == requestedCharacterId; 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 dab0caf2e5..e65ca65bf2 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 @@ -75,7 +75,7 @@ public WorldsViewOutput browseView( GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); connectScopeSessionStore.replaceWorldSnapshot( sessionId, - maybeCaller.map(SessionContext::accountId).orElse(0L), + maybeCaller.map(SessionContext::accountId).orElse(null), snapshot.catalogFingerprint(), snapshot.ordinalTargets(), clock.instant()); @@ -95,7 +95,7 @@ public RealmBrowseResult browseRealms( String transportSessionId, SessionContext sessionContext, String worldSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); OptionalLong parsedSessionId = parseTransportSessionId(transportSessionId); - if (sessionContext.accountId() <= 0 || parsedSessionId.isEmpty()) { + if (!sessionContext.hasAccountIdentity() || parsedSessionId.isEmpty()) { return RealmBrowseResult.failure("LOGIN_REQUIRED"); } if (parsedSessionId.getAsLong() != sessionContext.sessionId()) { @@ -488,7 +488,7 @@ public JoinMembershipResult joinPublicProductionMembership( if (parsedSessionId.isEmpty() || parsedSessionId.getAsLong() != sessionContext.sessionId()) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } - if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + if (!sessionContext.hasAccountIdentity() || sessionContext.sessionId() <= 0) { return JoinMembershipResult.failure("LOGIN_REQUIRED"); } if (accountClient == null || connectScopeSessionStore == null) { @@ -629,7 +629,7 @@ private DirectTextConnectScopeTarget connectScopeTarget( private PlayerExecutionContext playerContext( SessionContext caller, GameplayWorldCatalog.RealmView realm, String requestId) { return PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) .setTenantId(Long.toString(realm.tenantId())) .setRealmId(realm.realmId().toString()) @@ -709,7 +709,7 @@ public CharacterBrowseResult browseCharacters( String realmSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); OptionalLong parsedSessionId = parseTransportSessionId(transportSessionId); - if (sessionContext.accountId() <= 0 || parsedSessionId.isEmpty()) { + if (!sessionContext.hasAccountIdentity() || parsedSessionId.isEmpty()) { return CharacterBrowseResult.failure("LOGIN_REQUIRED"); } if (parsedSessionId.getAsLong() != sessionContext.sessionId()) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java index 2923de43cc..4f6ecb40e0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java @@ -90,7 +90,17 @@ public ResolvedValue resolvedReconnection(Session public FiremudReconnectionProperties resolve(long tenantId, long gameInstanceId) { return resolvedReconnection( new SessionContext( - 0L, tenantId, 0L, null, 0L, null, gameInstanceId, null, null, null, gameInstanceId)) + 0L, + tenantId, + null, + null, + 0L, + null, + gameInstanceId, + null, + null, + null, + gameInstanceId)) .effective(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java index d98e06ebaa..2b6cd3b1ca 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java @@ -152,7 +152,7 @@ private SessionResolution resolveContext( new SessionContext( 0L, resolvedTenantId, - 0L, + null, null, 0L, null, 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 ed2a67c117..4fe28f54c6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -18,7 +18,7 @@ public final class GameplayLocalPathReadinessProbe { private static final long PROBE_TENANT_ID = 0L; private static final long PROBE_SESSION_ID = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_ID = "ff36f51a-6cbd-4f26-8332-031535e2e3b4"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; private static final long PROBE_GAME_INSTANCE_ID = 0L; private static final String PROBE_ROOM_INSTANCE_ID_PREFIX = "readiness-room-"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java index 0bd9a89cfd..c17bf5c6f9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java @@ -4,7 +4,11 @@ /** Structured payload for canonical friend add/remove mutation results. */ public record FriendMutationResultOutput( - String action, long friendAccountId, String displayName, String characterName, Integer ordinal) + String action, + String friendAccountId, + String displayName, + String characterName, + Integer ordinal) implements PlayerOutputPayload { public FriendMutationResultOutput { Objects.requireNonNull(action, "action must not be null"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java index 0a9745b6ff..9994d0ad8e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java @@ -13,7 +13,7 @@ public record FriendPresenceViewOutput(String filter, int totalCount, List queryAccountPresence( - long tenantId, long viewerAccountId, List accountIds); + long tenantId, String viewerAccountId, List accountIds); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java index 244da44537..81627959d1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java @@ -6,7 +6,7 @@ * Canonical account-scoped social presence snapshot derived from current gameplay runtime state. */ public record AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String playableStateScope, @@ -21,7 +21,7 @@ public record AccountPresenceSnapshot( Instant lastSeenAt, AccountRecentPresenceDisposition recentDisposition) { public AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String worldSlug, @@ -50,7 +50,7 @@ public AccountPresenceSnapshot( } public AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String playableStateScope, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java index 8fc44afeda..993d372864 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java @@ -11,6 +11,6 @@ public interface AccountRecentPresenceService { void recordDisconnect(long sessionId, AccountRecentPresenceDisposition disposition); - Map findByAccountIds( - long tenantId, Collection accountIds); + Map findByAccountIds( + long tenantId, Collection accountIds); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java index c8ecc54aca..71db4e4192 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java @@ -5,7 +5,7 @@ /** Bounded recent-presence facts retained after a gameplay presence disconnects. */ public record AccountRecentPresenceState( long tenantId, - long accountId, + String accountId, Long gameInstanceId, String playableStateScope, String worldSlug, @@ -18,7 +18,7 @@ public record AccountRecentPresenceState( public AccountRecentPresenceState( long tenantId, - long accountId, + String accountId, long lastSeenAtEpochMs, AccountRecentPresenceDisposition disposition) { this(tenantId, accountId, null, null, null, null, null, lastSeenAtEpochMs, disposition); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index 279e983c5f..1cea65d656 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -61,13 +61,14 @@ public static DirectTextConnectScopeSessionStore inMemoryForTest() { public void replaceWorldSnapshot( long transportSessionId, - long authenticatedAccountId, + String authenticatedAccountId, String catalogFingerprint, List ordinalTargets, Instant now) { requireTransportSessionId(transportSessionId); - if (authenticatedAccountId < 0L) { - throw new IllegalArgumentException("authenticatedAccountId must not be negative"); + if (authenticatedAccountId != null + && !AccountIds.isCanonicalNonNilUuid(authenticatedAccountId)) { + throw new IllegalArgumentException("authenticatedAccountId must be a canonical non-nil UUID"); } Objects.requireNonNull(now, "now must not be null"); if (catalogFingerprint == null || catalogFingerprint.isBlank()) { @@ -87,13 +88,13 @@ public void replaceWorldSnapshot( if (record.sessionId() != transportSessionId) { throw new ConflictingIdentityException("lobby record transport session did not match"); } - if (authenticatedAccountId > 0L - && record.accountId() > 0L - && record.accountId() != authenticatedAccountId) { + if (authenticatedAccountId != null + && !record.accountId().isEmpty() + && !record.accountId().equals(authenticatedAccountId)) { record = LobbyRecord.empty(transportSessionId); } - long accountId = - authenticatedAccountId > 0L ? authenticatedAccountId : record.accountId(); + String accountId = + authenticatedAccountId != null ? authenticatedAccountId : record.accountId(); return record.withWorldSnapshot( accountId, expiresAtMillis, catalogFingerprint, safeTargets); }); @@ -106,7 +107,7 @@ public Optional worldsSnapshot(SessionContext caller, Instant no LobbyRecord record = readRecord(caller.sessionId()); if (record == null || record.sessionId() != caller.sessionId() - || (record.accountId() > 0L && record.accountId() != caller.accountId())) { + || (!record.accountId().isEmpty() && !record.accountId().equals(caller.accountId()))) { return Optional.empty(); } return asWorldsSnapshot(record, now); @@ -168,7 +169,7 @@ public void replaceWorldScopes( if (record.sessionId() != caller.sessionId()) { throw new ConflictingIdentityException("lobby record transport session did not match"); } - if (record.accountId() > 0L && record.accountId() != caller.accountId()) { + if (!record.accountId().isEmpty() && !record.accountId().equals(caller.accountId())) { record = LobbyRecord.empty(caller.sessionId()); } Map> byWorld = new HashMap<>(record.scopesByWorld()); @@ -248,7 +249,7 @@ public void replaceRealmSnapshot( if (record.sessionId() != caller.sessionId()) { throw new ConflictingIdentityException("lobby record transport session did not match"); } - if (record.accountId() > 0L && record.accountId() != caller.accountId()) { + if (!record.accountId().isEmpty() && !record.accountId().equals(caller.accountId())) { record = LobbyRecord.empty(caller.sessionId()); } Map> byWorld = new HashMap<>(record.scopesByWorld()); @@ -363,7 +364,7 @@ public void clearWorldScopes( throw new ConflictingIdentityException("lobby record transport session did not match"); } LobbyRecord record = current; - if (record.accountId() > 0L && record.accountId() != caller.accountId()) { + if (!record.accountId().isEmpty() && !record.accountId().equals(caller.accountId())) { record = LobbyRecord.empty(caller.sessionId()); } Map> byWorld = new HashMap<>(record.scopesByWorld()); @@ -420,6 +421,7 @@ public Optional publicProductionScope( List publicScopes = record.scopesByWorld().getOrDefault(worldKey, List.of()).stream() .map(DirectTextConnectScopeSessionStore::fromStoredScope) + .peek(scope -> validateScopeIdentity(caller, tenantId, scope)) .filter(scope -> scope.expiresAt().isAfter(now)) .filter(ScopedRealm::publicProductionRealm) .toList(); @@ -494,7 +496,9 @@ public Optional publicProductionScopeForJoin( byWorld.put(worldKey, updatedScopes); current = current.withScopes(byWorld); } - selected[0] = new JoinScope(fromStoredScope(boundScope), requestId); + ScopedRealm resolvedScope = fromStoredScope(boundScope); + validateScopeIdentity(caller, tenantId, resolvedScope); + selected[0] = new JoinScope(resolvedScope, requestId); return current; }); return Optional.ofNullable(selected[0]); @@ -543,7 +547,7 @@ private LobbyRecord decode(String json, long expectedSessionId) { } try { LobbyRecord record = objectMapper.readValue(json, LobbyRecord.class); - if (record == null || record.sessionId() != expectedSessionId || record.accountId() < 0L) { + if (record == null || record.sessionId() != expectedSessionId) { throw new ConflictingIdentityException("lobby state identity was invalid"); } return record.normalized(); @@ -658,7 +662,8 @@ private static void validateScopeIdentity( SessionContext caller, long tenantId, ScopedRealm scope) { Objects.requireNonNull(scope, "scope must not be null"); PlayerExecutionContext context = scope.playerContext(); - if (!Long.toString(caller.accountId()).equals(context.getAccountId()) + if (!AccountIds.isCanonicalNonNilUuid(context.getAccountId()) + || !caller.accountId().equals(context.getAccountId()) || !Long.toString(caller.sessionId()).equals(context.getSessionId()) || tenantId <= 0L || !Long.toString(tenantId).equals(context.getTenantId())) { @@ -740,7 +745,7 @@ private static String worldIdentityKey(long tenantId, String worldSlug) { private static boolean matchesCaller(LobbyRecord record, SessionContext caller) { return record != null && record.sessionId() == caller.sessionId() - && record.accountId() == caller.accountId(); + && record.accountId().equals(caller.accountId()); } private static void validateOrdinalTargets(List targets) { @@ -764,7 +769,7 @@ private static void validateRealmOrdinalTargets(List targets } private static void requireCallerIdentity(SessionContext caller) { - if (caller.accountId() <= 0L) { + if (!caller.hasAccountIdentity()) { throw new IllegalArgumentException("authenticated account is required"); } requireTransportSessionId(caller.sessionId()); @@ -1083,13 +1088,17 @@ private record StoredRealmsSnapshot( private record LobbyRecord( long sessionId, - long accountId, + String accountId, long worldsExpiresAtEpochMs, String catalogFingerprint, List ordinalTargets, Map> scopesByWorld, Map realmsByWorld) { private LobbyRecord { + if (accountId == null + || (!accountId.isEmpty() && !AccountIds.isCanonicalNonNilUuid(accountId))) { + throw new ConflictingIdentityException("lobby Account identity was invalid or unmapped"); + } ordinalTargets = ordinalTargets == null ? List.of() : List.copyOf(ordinalTargets); Map> scopesCopy = new HashMap<>(); if (scopesByWorld != null) { @@ -1100,11 +1109,11 @@ private record LobbyRecord( } private static LobbyRecord empty(long sessionId) { - return new LobbyRecord(sessionId, 0L, 0L, null, List.of(), Map.of(), Map.of()); + return new LobbyRecord(sessionId, "", 0L, null, List.of(), Map.of(), Map.of()); } private LobbyRecord normalized() { - if (sessionId <= 0L || accountId < 0L) { + if (sessionId <= 0L) { throw new ConflictingIdentityException("lobby state identity was invalid"); } return new LobbyRecord( @@ -1118,7 +1127,7 @@ private LobbyRecord normalized() { } private LobbyRecord withWorldSnapshot( - long accountId, + String accountId, long expiresAtEpochMs, String fingerprint, List targets) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java index 3a33918103..d70bcc3463 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java @@ -4,7 +4,7 @@ import org.springframework.util.StringUtils; public record FirstPartyConnectContext( - long accountId, + String accountId, long tenantId, String worldSlug, String realmSlug, @@ -18,7 +18,7 @@ public record FirstPartyConnectContext( private static final long serialVersionUID = 1L; public boolean hasCompleteRoutingScope() { - return accountId > 0L + return AccountIds.isCanonicalNonNilUuid(accountId) && tenantId > 0L && gameInstanceId > 0L && pointerVersion > 0L diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java index b3be62a86b..56889d3476 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java @@ -2,6 +2,7 @@ import java.util.Objects; import java.util.Optional; +import org.springframework.data.redis.serializer.SerializationException; public record FirstPartyConnectContextResolution( Optional connectContext, boolean invalid) { @@ -16,8 +17,14 @@ public static FirstPartyConnectContextResolution resolve( FirstPartyConnectContextRegistry firstPartyConnectContextRegistry) { Objects.requireNonNull( firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); - Optional registryContext = - firstPartyConnectContextRegistry.find(sessionId); + Optional registryContext; + try { + registryContext = firstPartyConnectContextRegistry.find(sessionId); + } catch (SerializationException | ClassCastException ex) { + // A retained value using the old numeric Account carrier is not an absent registry entry: + // treating it as absent would permit fallback to persisted session context. + return new FirstPartyConnectContextResolution(Optional.empty(), true); + } if (registryContext.isPresent()) { FirstPartyConnectContext connectContext = registryContext.orElseThrow(); return new FirstPartyConnectContextResolution( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java index 7f7938aa62..ef919528b9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java @@ -11,7 +11,7 @@ public record GameplayPresence( String worldSlug, String realmSlug, long pointerVersion, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, @@ -28,7 +28,7 @@ public GameplayPresence( long gameInstanceId, String worldSlug, String realmSlug, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, @@ -60,7 +60,7 @@ public GameplayPresence( String playableStateScope, String worldSlug, String realmSlug, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java index 58f54f8c91..7ec56bd602 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java @@ -17,8 +17,8 @@ public interface GameplayPresenceService { List listConnectedByGameInstance(long tenantId, long gameInstanceId); - Map> listConnectedByAccountIds( - long tenantId, Collection accountIds); + Map> listConnectedByAccountIds( + long tenantId, Collection accountIds); Optional findConnectedBySessionId(long sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java index 1956ffbf95..0ebff77e98 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java @@ -103,7 +103,7 @@ public SessionContext normalizeResolvedContext(SessionContext context) { } private boolean isAuthenticatedContext(SessionContext context) { - return context.accountId() > 0; + return context.hasAccountIdentity(); } private Optional parseSessionId(String text) { 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 01cf34ef35..dd47f6fb32 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 @@ -2,13 +2,14 @@ import java.io.Serializable; import java.util.Locale; +import java.util.Objects; import java.util.Optional; /** Represents persisted login context stored in Redis for a session. */ public record SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -27,6 +28,9 @@ public record SessionContext( private static final long serialVersionUID = 1L; public SessionContext { + if (accountId != null && !AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } loginName = loginName == null ? null : loginName.trim(); characterName = characterName == null ? null : characterName.trim(); roomInstanceId = normalizeText(roomInstanceId); @@ -41,7 +45,7 @@ public record SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -77,7 +81,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -108,7 +112,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -140,7 +144,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, long characterId, long gameInstanceId, String roomInstanceId, @@ -168,7 +172,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, long characterId, long gameInstanceId, String jwt) { @@ -195,7 +199,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -224,7 +228,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -281,6 +285,10 @@ public boolean hasGameplayIdentity() { return gameInstanceId > 0 && characterId > 0; } + public boolean hasAccountIdentity() { + return AccountIds.isCanonicalNonNilUuid(accountId); + } + public SessionContext withoutJwt() { if (jwt == null) { return this; @@ -328,13 +336,13 @@ public boolean sameGameplayIdentity(SessionContext that) { } return sessionId == that.sessionId() && tenantId == that.tenantId() - && accountId == that.accountId() + && Objects.equals(accountId, that.accountId()) && characterId == that.characterId() && gameInstanceId == that.gameInstanceId(); } public Optional persistedFirstPartyConnectContext() { - if (accountId <= 0 || tenantId <= 0) { + if (!hasAccountIdentity() || tenantId <= 0) { return Optional.empty(); } FirstPartyConnectContext connectContext = @@ -355,7 +363,7 @@ public Optional persistedFirstPartyConnectContext() { } public boolean hasPartialPersistedFirstPartyConnectContext() { - if (accountId <= 0 || tenantId <= 0) { + if (!hasAccountIdentity() || tenantId <= 0) { return false; } boolean hasAnyPersistedSelectorField = connectScopeId != null || connectRequestId != null; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java index df33088477..1315348909 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java @@ -11,6 +11,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; @@ -57,11 +58,11 @@ public AccountPresenceQueryServiceImpl( @Override public List queryAccountPresence( - long tenantId, long viewerAccountId, List accountIds) { + long tenantId, String viewerAccountId, List accountIds) { Objects.requireNonNull(accountIds, "accountIds"); - LinkedHashSet requestedIds = new LinkedHashSet<>(); - for (Long accountId : accountIds) { - if (accountId != null && accountId > 0) { + LinkedHashSet requestedIds = new LinkedHashSet<>(); + for (String accountId : accountIds) { + if (AccountIds.isCanonicalNonNilUuid(accountId)) { requestedIds.add(accountId); } } @@ -69,20 +70,20 @@ public List queryAccountPresence( return List.of(); } - Map results = new LinkedHashMap<>(); + Map results = new LinkedHashMap<>(); Map currentRuntimePointers = new HashMap<>(); - Map recentStates = + Map recentStates = accountRecentPresenceService.findByAccountIds(tenantId, requestedIds); - for (Long accountId : requestedIds) { + for (String accountId : requestedIds) { results.put( accountId, offline(tenantId, accountId, recentStates.get(accountId), currentRuntimePointers)); } - Map> activePresences = + Map> activePresences = gameplayPresenceService.listConnectedByAccountIds(tenantId, requestedIds); - for (Map.Entry> entry : activePresences.entrySet()) { - Long accountId = entry.getKey(); + for (Map.Entry> entry : activePresences.entrySet()) { + String accountId = entry.getKey(); GameplayPresence presence = selectCurrentPresence(tenantId, entry.getValue(), currentRuntimePointers); if (presence == null) { @@ -170,7 +171,7 @@ private boolean isCurrentPresence( private AccountPresenceSnapshot offline( long tenantId, - long accountId, + String accountId, AccountRecentPresenceState recentState, Map currentRuntimePointers) { GameplayAdmissionPointerSnapshot pointer = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java index f24de8b5ad..a1db851740 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java @@ -198,9 +198,10 @@ private GameplayCommand persistAcceptedCommand( gameplayCommand.setGameInstanceId(queueTarget.queueTargetId()); gameplayCommand.setSessionId(sessionId); sessionContext + .filter(SessionContext::hasAccountIdentity) .map(SessionContext::accountId) - .filter(id -> id > 0) - .ifPresent(gameplayCommand::setAccountId); + .map(UUID::fromString) + .ifPresent(gameplayCommand::setAccountUuid); sessionContext .map(SessionContext::characterId) .filter(id -> id > 0) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java index fdd924dba7..f2bdbc889a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java @@ -1545,8 +1545,8 @@ private GameplayCommandStatus toStatus(GameplayCommand command) { .setLastAttemptAtMs(toEpochMillis(command.getLastAttemptAt())) .setAttemptCount(command.getAttemptCount()) .setPlayableStateScope(toPlayableStateScopeStatus(command.getPlayableStateScope())); - if (command.getAccountId() != null) { - builder.setAccountId(command.getAccountId().toString()); + if (command.getAccountUuid() != null) { + builder.setAccountId(command.getAccountUuid().toString()); } if (command.getCharacterId() != null) { builder.setCharacterId(command.getCharacterId().toString()); 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 9bef851376..bacf6be2ce 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 @@ -234,9 +234,15 @@ private String parseOwnerAccountUuid(String ownerAccountId) { return ownerAccountId; } - private List parseAccountIds(List accountIds) { + private List parseAccountIds(List accountIds) { return accountIds.stream() - .map(accountId -> ControlPlaneRequestParser.parsePositiveLong(accountId, "accountId")) + .map( + accountId -> { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return accountId; + }) .toList(); } @@ -439,20 +445,18 @@ public void queryAccountPresence( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); - long viewerAccountId = - ControlPlaneRequestParser.parsePositiveLong( - request.getViewerAccountId(), "viewerAccountId"); - requireNumericAccountPresenceAccess(tenantId); + String viewerAccountId = parseCanonicalAccountId(request.getViewerAccountId()); + requireTenantOrCurrentAccountAccess(tenantId, viewerAccountId); if (request.getAccountIdsCount() > 100) { throw new IllegalArgumentException("accountIds must contain at most 100 entries"); } - List accountIds = parseAccountIds(request.getAccountIdsList()); + List accountIds = parseAccountIds(request.getAccountIdsList()); QueryAccountPresenceResponse.Builder builder = QueryAccountPresenceResponse.newBuilder(); for (var snapshot : accountPresenceQueryService.queryAccountPresence(tenantId, viewerAccountId, accountIds)) { AccountPresenceEntry.Builder entry = AccountPresenceEntry.newBuilder() - .setAccountId(Long.toString(snapshot.accountId())) + .setAccountId(snapshot.accountId()) .setOnline(snapshot.online()); if (snapshot.gameInstanceId() != null) { entry.setGameInstanceId(Long.toString(snapshot.gameInstanceId())); @@ -862,11 +866,21 @@ private void requireTenantAccess(long tenantId) { throw new AuthorizationException("Tenant access required"); } - private void requireNumericAccountPresenceAccess(long tenantId) { + private String parseCanonicalAccountId(String accountId) { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return accountId; + } + + private void requireTenantOrCurrentAccountAccess(long tenantId, String accountId) { if (SessionContext.hasTenantAccess(tenantId)) { return; } - throw new AuthorizationException("Numeric account self-service is unavailable"); + if (SessionContext.isCurrentAccount(accountId)) { + return; + } + throw new AuthorizationException("Account access required"); } private void requireInstanceAccess(long sessionId) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java index baaec064eb..1d86e2248f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java @@ -6,6 +6,7 @@ import java.util.Map; import java.util.function.LongSupplier; import net.firedevops.firemud.gamesession.config.PresenceProperties; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceState; @@ -21,7 +22,7 @@ @Service public final class RedisAccountRecentPresenceService implements AccountRecentPresenceService { - private static final String RECENT_PRESENCE_KEY_TEMPLATE = "accountrecentpresence:%d:%d"; + private static final String RECENT_PRESENCE_KEY_TEMPLATE = "accountrecentpresence:%d:%s"; private final RedisTemplate redisTemplate; private final SessionRoutingNormalizationService sessionRoutingNormalizationService; @@ -58,7 +59,7 @@ public RedisAccountRecentPresenceService( @Override public void recordConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || context.accountId() <= 0) { + if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { return; } GameplayPresence presence = @@ -99,12 +100,12 @@ public void recordDisconnect(long sessionId, AccountRecentPresenceDisposition di } @Override - public Map findByAccountIds( - long tenantId, Collection accountIds) { + public Map findByAccountIds( + long tenantId, Collection accountIds) { ValueOperations valueOps = redisTemplate.opsForValue(); - LinkedHashMap results = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0 || valueOps == null) { + LinkedHashMap results = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (!AccountIds.isCanonicalNonNilUuid(accountId) || valueOps == null) { continue; } AccountRecentPresenceState state = @@ -138,7 +139,7 @@ private void write( } private RoutingSnapshot routingSnapshot(SessionContext context, GameplayPresence presence) { - if (context == null || context.tenantId() <= 0 || context.accountId() <= 0) { + if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { return null; } GameplayPresence effectivePresence = @@ -180,13 +181,13 @@ private String blankToNull(String value) { return null; } - private String key(long tenantId, long accountId) { + private String key(long tenantId, String accountId) { return String.format(RECENT_PRESENCE_KEY_TEMPLATE, tenantId, accountId); } private record RoutingSnapshot( long tenantId, - long accountId, + String accountId, Long gameInstanceId, String playableStateScope, String worldSlug, 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 a577c3af0f..58e3b90398 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,6 +11,7 @@ import java.util.Optional; import java.util.Set; import java.util.function.LongSupplier; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; @@ -21,6 +22,7 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -29,7 +31,7 @@ public final class RedisGameplayPresenceService implements GameplayPresenceService { 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"; + private static final String ACCOUNT_SET_TEMPLATE = "gameplaypresence:%d:account:%s:sessions"; private static final Comparator ACCOUNT_PRESENCE_PREFERENCE = Comparator.comparing( GameplayPresence::lastMeaningfulActivityAtEpochMs, @@ -62,7 +64,10 @@ public RedisGameplayPresenceService( @Override public void registerConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || context.gameInstanceId() <= 0) { + if (context == null + || !context.hasAccountIdentity() + || context.tenantId() <= 0 + || context.gameInstanceId() <= 0) { return; } ValueOperations valueOps = redisTemplate.opsForValue(); @@ -100,8 +105,7 @@ public void registerConnected(SessionContext context) { @Override public void removeBySessionId(long sessionId) { - ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readPresenceForMutation(presenceKey(sessionId)); redisTemplate.delete(presenceKey(sessionId)); if (existing != null) { String gameInstanceKey = gameInstanceKey(existing.tenantId(), existing.gameInstanceId()); @@ -115,7 +119,7 @@ public void removeBySessionId(long sessionId) { @Override public void setExplicitAfk(long sessionId, boolean explicitAfk) { ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readPresence(presenceKey(sessionId)); if (existing == null) { return; } @@ -146,7 +150,7 @@ public void setExplicitAfk(long sessionId, boolean explicitAfk) { @Override public void recordCommandActivity(long sessionId, boolean meaningfulGameplayActivity) { ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readPresence(presenceKey(sessionId)); if (existing == null) { return; } @@ -186,7 +190,6 @@ public List listConnectedByGameInstance(long tenantId, long ga return List.of(); } - ValueOperations valueOps = redisTemplate.opsForValue(); ArrayList matches = new ArrayList<>(); for (Object member : members) { String sessionIdText = String.valueOf(member); @@ -195,7 +198,13 @@ public List listConnectedByGameInstance(long tenantId, long ga setOps.remove(gameInstanceKey, sessionIdText); continue; } - GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence; + try { + presence = readPresenceForMutation(presenceKey); + } catch (SerializationException | ClassCastException | UnreadablePresenceException ex) { + // Keep the index member until its retained presence value can be read safely. + continue; + } if (presence == null) { setOps.remove(gameInstanceKey, sessionIdText); continue; @@ -215,17 +224,15 @@ public List listConnectedByGameInstance(long tenantId, long ga } @Override - public Map> listConnectedByAccountIds( - long tenantId, Collection accountIds) { + public Map> listConnectedByAccountIds( + long tenantId, Collection accountIds) { if (accountIds == null || accountIds.isEmpty()) { return Map.of(); } SetOperations setOps = redisTemplate.opsForSet(); - ValueOperations valueOps = redisTemplate.opsForValue(); - - LinkedHashMap> matches = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0) { + LinkedHashMap> matches = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { continue; } String accountKey = accountKey(tenantId, accountId); @@ -241,12 +248,18 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } - GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence; + try { + presence = readPresenceForMutation(presenceKey); + } catch (SerializationException | ClassCastException | UnreadablePresenceException ex) { + // Keep the index member until its retained presence value can be read safely. + continue; + } if (presence == null) { setOps.remove(accountKey, sessionIdText); continue; } - if (presence.tenantId() != tenantId || presence.accountId() != accountId) { + if (presence.tenantId() != tenantId || !accountId.equals(presence.accountId())) { setOps.remove(accountKey, sessionIdText); continue; } @@ -262,11 +275,38 @@ public Map> listConnectedByAccountIds( @Override public Optional findConnectedBySessionId(long sessionId) { - ValueOperations valueOps = redisTemplate.opsForValue(); - return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))) + return Optional.ofNullable(readPresence(presenceKey(sessionId))) .map(RedisGameplayPresenceService::playerPresence); } + private GameplayPresence readPresence(String key) { + ValueOperations valueOps = redisTemplate.opsForValue(); + try { + GameplayPresence presence = (GameplayPresence) valueOps.get(key); + return hasCurrentAccountIdentity(presence) ? presence : null; + } catch (SerializationException | ClassCastException ex) { + // An older numeric Account carrier cannot be mapped to a UUID. Fail closed without + // mutating the retained record; the session must authenticate through its context path. + return null; + } + } + + private GameplayPresence readPresenceForMutation(String key) { + ValueOperations valueOps = redisTemplate.opsForValue(); + // Unlike read-only lookups, mutation cleanup must distinguish absence from a retained value + // that cannot be decoded under the current Account carrier. Propagate these decode failures + // so callers do not delete or overwrite the record or its indexes. + GameplayPresence presence = (GameplayPresence) valueOps.get(key); + if (presence != null && !hasCurrentAccountIdentity(presence)) { + throw new UnreadablePresenceException(); + } + return presence; + } + + private static boolean hasCurrentAccountIdentity(GameplayPresence presence) { + return presence == null || AccountIds.isCanonicalNonNilUuid(presence.accountId()); + } + private static GameplayPresence playerPresence(GameplayPresence presence) { if (presence.role() == GameplayPresenceRole.PLAYER) { return presence; @@ -289,6 +329,8 @@ private static GameplayPresence playerPresence(GameplayPresence presence) { presence.lastMeaningfulActivityAtEpochMs()); } + private static final class UnreadablePresenceException extends RuntimeException {} + private String presenceKey(long sessionId) { return String.format(PRESENCE_KEY_TEMPLATE, sessionId); } @@ -306,7 +348,7 @@ private String gameInstanceKey(long tenantId, long gameInstanceId) { return String.format(GAME_INSTANCE_SET_TEMPLATE, tenantId, gameInstanceId); } - private String accountKey(long tenantId, long accountId) { + private String accountKey(long tenantId, String accountId) { return String.format(ACCOUNT_SET_TEMPLATE, tenantId, accountId); } 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 ef48bccc22..fd6e49ca66 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 @@ -162,7 +162,15 @@ private String contextKey(long tenantId, long sessionId) { } private Optional readSessionContext(String key) { - SessionContext context = (SessionContext) redisTemplate.opsForValue().get(key); + SessionContext context; + try { + context = (SessionContext) redisTemplate.opsForValue().get(key); + } catch (org.springframework.data.redis.serializer.SerializationException + | ClassCastException ex) { + // Numeric Account identities from the old record shape are not convertible to UUIDs. + // Keep the retained value intact and require a fresh LOGIN before gameplay can resume. + return Optional.empty(); + } return Optional.ofNullable(context).map(SessionContext::withoutJwt); } @@ -193,7 +201,13 @@ private List watchKeys(SessionContext context) { private SessionContext readContext( org.springframework.data.redis.core.RedisOperations operations, String key) { - return (SessionContext) operations.opsForValue().get(key); + try { + return (SessionContext) operations.opsForValue().get(key); + } catch (org.springframework.data.redis.serializer.SerializationException + | ClassCastException ex) { + // The caller cannot authorize from an unreadable legacy identity; do not mutate it here. + return null; + } } private void addWatchKeys(Set watchKeys, SessionContext context) { 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 489197bbfc..dfe2b36146 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 @@ -782,7 +782,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext new SessionContext( existing.sessionId(), existing.tenantId(), - 0L, + null, null, 0L, null, @@ -829,7 +829,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext new SessionContext( incomingShell.sessionId(), incomingShell.tenantId(), - 0L, + null, null, 0L, null, @@ -847,7 +847,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext } private boolean hasAuthenticatedOrGameplayBinding(SessionContext context) { - return context.accountId() > 0 + return context.hasAccountIdentity() || context.characterId() > 0 || context.gameInstanceId() > 0 || StringUtils.hasText(context.roomInstanceId()) @@ -868,7 +868,7 @@ private SessionContext bootstrapShell( return new SessionContext( sessionId, tenantId, - 0L, + null, null, 0L, null, 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 b4b7f7f092..bc085d3988 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 @@ -29,9 +29,14 @@ class CommunicationWebSocketCrossServiceTest { private static final Duration COMMAND_WAIT = Duration.ofSeconds(45); private static final long TENANT_ID = 1L; - private static final long ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); - private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); - private static final long NYX_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); + private static final String ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_EMBERLINE; + private static final String SORA_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_SORA; + private static final String NYX_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_NYX; + private static final long EMBERLINE_CHARACTER_ID = + Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); + private static final long SORA_CHARACTER_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + private static final long NYX_CHARACTER_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); + private static final long MANAGEMENT_OWNER_SELECTOR = EMBERLINE_CHARACTER_ID; private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; private static final String SORA_EMAIL = "sora@example.com"; @@ -76,7 +81,7 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { .hasValueSatisfying( request -> { assertThat(request.getTenantId()).isEqualTo(Long.toString(TENANT_ID)); - assertThat(request.getAccountId()).isEqualTo(Long.toString(ACCOUNT_ID)); + assertThat(request.getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(request.getGameInstanceId()) .isEqualTo(Long.toString(DEMO_WORLD_INSTANCE_ID)); assertThat(request.getPlayableStateScope()) @@ -225,12 +230,13 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { List responses = runCommunicationSequence( - sessionId, "FRIENDS", "Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)"); + sessionId, "FRIENDS", "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online (idle)"); assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses) .anyMatch( - response -> response.contains("Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)")); + response -> + response.contains("Sora [acct #" + SORA_ACCOUNT_UUID + "] - online (idle)")); assertThat(responses) .noneMatch( response -> @@ -241,7 +247,7 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { || response.contains("shared") || response.contains("Pointer version")); GameplaySocialAssertions.assertListFriendsRequest( - socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -253,18 +259,18 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { runCommunicationSequence( sessionId, "FRIENDS ONLINE", - "Friends ONLINE:\n" + "1) Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)"); + "Friends ONLINE:\n" + "1) Sora [acct #" + SORA_ACCOUNT_UUID + "] - online (idle)"); assertThat(responses) .anyMatch( response -> response.contains("Friends ONLINE:\n") && response.contains( - "1) Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)")); + "1) Sora [acct #" + SORA_ACCOUNT_UUID + "] - online (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @@ -299,11 +305,12 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc sessionId = prepareGameInstance(); List responses = runCommunicationSequence( - sessionId, "FRIENDS", "Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)"); + sessionId, "FRIENDS", "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online (idle)"); assertThat(responses) .anyMatch( - response -> response.contains("Sora [acct #" + SORA_ACCOUNT_ID + "] - online (idle)")); + response -> + response.contains("Sora [acct #" + SORA_ACCOUNT_UUID + "] - online (idle)")); } @Test @@ -311,7 +318,7 @@ void websocketFriendsDetailRedactsMissingPolicyPresenceWithoutDisconnecting() th ensureTestServicesStarted(); FriendPresenceEntry missingPolicyPresence = FriendPresenceEntry.newBuilder() - .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setFriendAccountId(SORA_ACCOUNT_UUID) .setOnline(true) .setCharacterId(ChatTestFixtures.PLAYER_SORA) .setCharacterName("Sora") @@ -347,22 +354,22 @@ void websocketFriendsMutationFlowUsesCanonicalRosterSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-conn")) { - client.send("FRIENDS ADD 77"); - client.awaitContains("Friend #77 added."); - client.send("FRIENDS REMOVE 77"); - client.awaitContains("Friend #77 removed."); + client.send("FRIENDS ADD " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " added."); + client.send("FRIENDS REMOVE " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -373,21 +380,21 @@ void websocketFriendsMutationByCharacterNameUsesCanonicalIdentityLookup() throws try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-name-conn")) { client.send("FRIENDS ADD Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] added."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] added."); client.send("FRIENDS REMOVE Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -398,14 +405,11 @@ void websocketFriendsRemoveByRosterOrdinalUsesRenderedRosterIdentity() throws Ex try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-remove-ordinal-conn")) { client.send("FRIENDS REMOVE #1"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertRemoveFriendByOrdinalRequest( - socialStub().lastRemoveFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastRemoveFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -417,7 +421,7 @@ void websocketFriendsShowUsesCanonicalFriendDetailSurface() throws Exception { openReadySessionClient(sessionId, "friends-show-detail-conn")) { int baseline = client.responses().size(); client.send("FRIENDS SHOW #1"); - client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_ID + "]"); + client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_UUID + "]"); client.awaitContains("Presence: online (idle)"); client.awaitContains("Roster entry: #1"); assertThat(client.responses().subList(baseline, client.responses().size())) @@ -432,10 +436,7 @@ void websocketFriendsShowUsesCanonicalFriendDetailSurface() throws Exception { } GameplaySocialAssertions.assertGetFriendByOrdinalRequest( - socialStub().lastGetFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastGetFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -456,7 +457,7 @@ void websocketFriendsSummaryUsesCanonicalRosterSummarySurface() throws Exception } GameplaySocialAssertions.assertFriendRosterSummaryRequest( - socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -474,13 +475,11 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { } GameplaySocialAssertions.assertGetVisibilityRequest( - socialStub().lastGetVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID)); + socialStub().lastGetVisibilityRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); GameplaySocialAssertions.assertUpdateVisibilityRequest( socialStub().lastUpdateVisibilityRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } @@ -493,7 +492,7 @@ void websocketFirstPartyBareLoginFailsClosedWithoutAdmission() throws Exception java.util.Map connectClaims = java.util.Map.of( "accountId", - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, "tenantId", Long.toString(TENANT_ID), "worldSlug", @@ -519,7 +518,7 @@ void websocketFirstPartyBareLoginFailsClosedWithoutAdmission() throws Exception COMMAND_WAIT, Long.toString(sessionId), "stub-secret-key-for-tests-1234567890", - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, connectClaims)) { int baseline = client.responses().size(); client.send("LOGIN"); @@ -544,7 +543,13 @@ void websocketFirstPartyBareLoginFailsClosedWithoutAdmission() throws Exception gameSession() .bean(net.firedevops.firemud.gamesession.service.SessionContextService.class) .findByTenantAndSessionId(TENANT_ID, sessionId)) - .satisfies(saved -> saved.ifPresent(context -> assertThat(context.accountId()).isZero())); + .satisfies( + saved -> + saved.ifPresent( + context -> { + assertThat(context.accountId()).isNull(); + assertThat(context.hasAccountIdentity()).isFalse(); + })); assertThat(entityStub().lastListCharactersByAccountRequest()) .isEqualTo(previousCharacterLookup); } @@ -728,16 +733,16 @@ void websocketEquipmentLoopMovesCarriedItemThroughSlotAndBack() throws Exception private static synchronized void ensureTestServicesStarted() throws Exception { if (STACK == null) { STACK = - GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) - .mapAccountId("sora@example.com", SORA_ACCOUNT_ID) - .mapAccountId("nyx@example.com", NYX_ACCOUNT_ID) + GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_UUID) + .mapAccountUuid("sora@example.com", SORA_ACCOUNT_UUID) + .mapAccountUuid("nyx@example.com", NYX_ACCOUNT_UUID) .withInitialRoomEntities(ChatTestFixtures.sampleEntities()) .withSocialEnabled(true) .withInitialFriendPresenceResponse( net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse.newBuilder() .addPresences( FriendPresenceEntry.newBuilder() - .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setFriendAccountId(SORA_ACCOUNT_UUID) .setOnline(true) .setCharacterId(ChatTestFixtures.PLAYER_SORA) .setCharacterName("Sora") @@ -766,14 +771,14 @@ private long prepareGameInstance() { STACK.freshGameplayBaseline( TENANT_ID, DEMO_WORLD_INSTANCE_ID, - ACCOUNT_ID, + MANAGEMENT_OWNER_SELECTOR, 7L, - ACCOUNT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + EMBERLINE_CHARACTER_ID, + SORA_CHARACTER_ID, + NYX_CHARACTER_ID); entityStub().resetCharacterRosterState(); - STACK.accountStub().mapAccountId(SORA_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_SORA)); - STACK.accountStub().mapAccountId(NYX_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + STACK.accountStub().mapAccountUuid(SORA_EMAIL, SORA_ACCOUNT_UUID); + STACK.accountStub().mapAccountUuid(NYX_EMAIL, NYX_ACCOUNT_UUID); return sessionId; } @@ -791,9 +796,9 @@ private void seedLiveTargetSession() { STACK.seedLiveSession( 90210L, TENANT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + ChatTestFixtures.characterByName("Sora").getAccountId(), "sora@example.com", - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + SORA_CHARACTER_ID, "Sora", DEMO_WORLD_INSTANCE_ID, ChatTestFixtures.ROOM_ID, 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 51e928c9ed..6426fcdcfa 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 @@ -8,6 +8,7 @@ import net.firedevops.firemud.entitymanagement.v1.ActorConditionState; import net.firedevops.firemud.entitymanagement.v1.ActorResourceValue; import net.firedevops.firemud.entitymanagement.v1.QueryActorStateResponse; +import net.firedevops.firemud.gamesession.test.ChatTestFixtures; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayCrossServiceStack; @@ -28,7 +29,8 @@ class LookWebSocketCrossServiceTest { private static final Duration COMMAND_WAIT = Duration.ofSeconds(8); private static final long TENANT_ID = 1L; - private static final long ACCOUNT_ID = 7L; + private static final String ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_EMBERLINE; + private static final long MANAGEMENT_OWNER_SELECTOR = 7L; private static final long CHARACTER_ID = 123L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; @@ -334,7 +336,7 @@ void websocketReconnectWithoutBufferedTranscriptStillGetsFreshLook() throws Exce private static synchronized void ensureTestServicesStarted() throws Exception { if (STACK == null) { - STACK = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID).start(); + STACK = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_UUID).start(); } } @@ -348,9 +350,10 @@ private long prepareAdditionalGameInstance() { private long insertGameInstance(boolean clearExisting) { if (clearExisting) { - return STACK.freshGameplayBaseline(TENANT_ID, 1L, ACCOUNT_ID, 7L, CHARACTER_ID); + return STACK.freshGameplayBaseline( + TENANT_ID, 1L, MANAGEMENT_OWNER_SELECTOR, 7L, CHARACTER_ID); } - return STACK.insertRunningGameInstance(TENANT_ID, ACCOUNT_ID, 7L, false); + return STACK.insertRunningGameInstance(TENANT_ID, MANAGEMENT_OWNER_SELECTOR, 7L, false); } private List runLookSequence(long sessionId) throws Exception { diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java index fece520e58..714459e851 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java @@ -13,6 +13,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.test.ChatTestFixtures; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.gamesession.test.stubs.SocialGroupsStubServer; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; @@ -35,7 +36,7 @@ class MultiplayerLoadProofCrossServiceTest { private static final Duration FOLLOW_UP_PHASE_BUDGET = Duration.ofSeconds(15); private static final long TENANT_ID = 1L; private static final int CLIENT_COUNT = 10; - private static final long ACCOUNT_ID_BASE = 7000L; + private static final long CHARACTER_ID_BASE = 7000L; @Container static final PostgreSQLContainer POSTGRES = @@ -67,7 +68,8 @@ static synchronized void stopServices() { void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throws Exception { ensureTestServicesStarted(); List players = - GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); + GameplayLoadScenarios.seedPlayers( + STACK, TENANT_ID, 1L, CHARACTER_ID_BASE, CLIENT_COUNT, 7L); URI uri = URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); TimedResult> playerRuns = timed( @@ -117,8 +119,9 @@ void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throw .hasValueSatisfying( context -> { assertThat(context.tenantId()).isEqualTo(TENANT_ID); + assertThat(context.accountId()).isEqualTo(player.accountUuid()); assertThat(context.gameInstanceId()).isEqualTo(1L); - assertThat(context.characterId()).isEqualTo(player.accountId()); + assertThat(context.characterId()).isEqualTo(player.characterId()); assertThat(context.roomInstanceId()).isEqualTo(LookTestFixtures.ROOM_ID); }); } @@ -134,7 +137,8 @@ void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throw void tenConcurrentPlayersCanMoveNorthAfterConcurrentEntry() throws Exception { ensureTestServicesStarted(); List players = - GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); + GameplayLoadScenarios.seedPlayers( + STACK, TENANT_ID, 1L, CHARACTER_ID_BASE, CLIENT_COUNT, 7L); URI uri = URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); TimedResult> readyPlayers = @@ -180,7 +184,8 @@ void tenConcurrentPlayersCanMoveNorthAfterConcurrentEntry() throws Exception { void tenConcurrentPlayersCanBroadcastSayAfterConcurrentEntry() throws Exception { ensureTestServicesStarted(); List players = - GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); + GameplayLoadScenarios.seedPlayers( + STACK, TENANT_ID, 1L, CHARACTER_ID_BASE, CLIENT_COUNT, 7L); URI uri = URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); TimedResult> readyPlayers = @@ -236,7 +241,8 @@ void tenConcurrentPlayersCanBroadcastSayAfterConcurrentEntry() throws Exception private static synchronized void ensureTestServicesStarted() throws Exception { if (STACK == null) { STACK = - GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID_BASE) + GameplayCrossServiceStack.defaultDemoBuilder( + POSTGRES, REDIS, ChatTestFixtures.ACCOUNT_UUID_EMBERLINE) .withSocialEnabled(true) .start(); } @@ -309,11 +315,11 @@ private void runConcurrentSayBurst(List connectedPlayers) t } private String sayText(GameplayLoadScenarios.PlayerSeed player) { - return "multiplayer burst " + player.accountId(); + return "multiplayer burst " + player.characterId(); } private String expectedSayTranscript(GameplayLoadScenarios.PlayerSeed player) { - return "You say, \"Multiplayer burst " + player.accountId() + ".\""; + return "You say, \"Multiplayer burst " + player.characterId() + ".\""; } private List runConcurrently(List items, ConcurrentTask task) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 50d80c77d0..248b4e4d89 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -297,7 +297,7 @@ void effectiveSettingsEndpointMergesScopedOverridesForPersistedSession() { new SessionContext( 999L, 42L, - 100L, + "d3a8c26e-8253-4836-b01b-63c9b7fb1f75", "player@example.com", 55L, "Player", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index 52dcd33fed..f263d592f1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -99,7 +99,10 @@ void setUp() { .delete(anyString()); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("stub-token").setAccountId("7").build()); + AuthenticateResponse.newBuilder() + .setAuthToken("stub-token") + .setAccountId("c91fb96e-5ad8-4e4e-a12d-2838640093b2") + .build()); when(sharedSettingsAuthorityReader.readOverrides(anyLong(), org.mockito.ArgumentMatchers.any())) .thenReturn(ScopedSettingsSnapshot.empty()); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java index 74f621cadc..cc8aabd897 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java @@ -28,7 +28,7 @@ @SuppressWarnings("resource") class RedisDirectTextConnectScopeSessionStoreTest { private static final long SESSION_ID = 4401L; - private static final long ACCOUNT_ID = 7L; + private static final String ACCOUNT_UUID = "7c74170e-7755-4d3a-8f12-3d2839b835de"; private static final String REDIS_KEY = "gamesession:lobby:4401"; @Container @@ -69,7 +69,7 @@ void sharesLobbySnapshotAndAtomicallyBindsJoinRetryAcrossStoreInstances() throws 1, "demo-world", 22L, 13L, "target-fingerprint-v13"); firstInstance.replaceWorldSnapshot( - SESSION_ID, 0L, "catalog-fingerprint-v13", List.of(target), now); + SESSION_ID, null, "catalog-fingerprint-v13", List.of(target), now); firstInstance.replaceRealmSnapshot( caller, "1", @@ -201,7 +201,7 @@ void readsLegacyLobbyJsonWithUnusedSelectorMapAcrossStoreInstances() throws Exce "sessionId", SESSION_ID, "accountId", - ACCOUNT_ID, + ACCOUNT_UUID, "worldsExpiresAtEpochMs", expiresAt, "catalogFingerprint", @@ -262,8 +262,7 @@ void readsLegacyLobbyJsonWithUnusedSelectorMapAcrossStoreInstances() throws Exce selected -> { assertThat(selected.scope().connectScopeId()) .isEqualTo("account-connect-scope-legacy"); - assertThat(selected.scope().playerContext().getAccountId()) - .isEqualTo(Long.toString(ACCOUNT_ID)); + assertThat(selected.scope().playerContext().getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(selected.scope().playerContext().getSessionId()) .isEqualTo(Long.toString(SESSION_ID)); assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); @@ -277,7 +276,7 @@ private DirectTextConnectScopeSessionStore newStoreInstance() { } private static SessionContext session() { - return new SessionContext(SESSION_ID, 22L, ACCOUNT_ID, 7001L, 9L, "R-1", "unused-test-jwt"); + return new SessionContext(SESSION_ID, 22L, ACCOUNT_UUID, 7001L, 9L, "R-1", "unused-test-jwt"); } private static PlayerExecutionContext playerContext(SessionContext caller) { @@ -286,7 +285,7 @@ private static PlayerExecutionContext playerContext(SessionContext caller) { private static PlayerExecutionContext playerContext(SessionContext caller, long tenantId) { return PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) .setTenantId(Long.toString(tenantId)) .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") 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 12e807c6c7..7d3cf85177 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 @@ -246,7 +246,7 @@ void setUp() { return members == null ? java.util.Set.of() : new java.util.LinkedHashSet<>(members); }); when(moderationPolicyClient.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -263,14 +263,14 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("stub-token") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .build()); org.mockito.Mockito.doAnswer( invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1"), + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1"), invocation.getArgument(0))) .when(accountClient) .getTenantMembershipForRuntime( @@ -302,7 +302,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("123") .setTenantId("22") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setName("Emberline") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -311,7 +311,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("456") .setTenantId("22") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setName("Sora") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(7) @@ -319,7 +319,10 @@ void setUp() { .build()) .when(entityManagementClient) .listCharactersByAccount( - eq("22"), eq("123"), eq("1"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + eq("22"), + eq("f2ed193b-12c1-4c96-bcad-c162229af440"), + eq("1"), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(commandService.enqueue( org.mockito.ArgumentMatchers.anyString(), eq("PLAY demo Emberline"), eq(false))) .thenReturn(CommandEnqueueResult.success()); @@ -662,7 +665,10 @@ void unexpectedDisconnectKeepsFreshReconnectLookButDoesNotReplayPrivateContext() GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isPresent(); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(123L))).containsKey(123L); + assertThat( + accountRecentPresenceService.findByAccountIds( + 22L, List.of("f2ed193b-12c1-4c96-bcad-c162229af440"))) + .containsKey("f2ed193b-12c1-4c96-bcad-c162229af440"); List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { @@ -916,7 +922,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("789") .setTenantId("22") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setName("CutoverArrival") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(1) @@ -926,7 +932,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() .when(entityManagementClient) .listCharactersByAccount( "22", - "123", + "f2ed193b-12c1-4c96-bcad-c162229af440", Long.toString(CUTOVER_GAME_INSTANCE_ID), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -1013,7 +1019,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(sessionContextService.findByTenantAndSessionId(23L, 41L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.accountId()).isEqualTo("f2ed193b-12c1-4c96-bcad-c162229af440"); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); @@ -1139,7 +1145,8 @@ void websocketFirstPartyBareLoginRemainsUnavailableWithoutPlayAdmission() throws saved -> saved.ifPresent( context -> { - assertThat(context.accountId()).isZero(); + assertThat(context.accountId()).isNull(); + assertThat(context.hasAccountIdentity()).isFalse(); assertThat(context.jwt()).isNull(); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); @@ -1210,7 +1217,7 @@ void websocketCredentialRouteChangeHidesPrivateOnlySandboxFromPublicWorldCommand assertThat(sessionContextService.findByTenantAndSessionId(22L, 43L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.accountId()).isEqualTo("f2ed193b-12c1-4c96-bcad-c162229af440"); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); 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 00c4b80613..5a3979cede 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 @@ -91,20 +91,21 @@ public List listConnectedByGameInstance(long tenantId, long ga } @Override - public Map> listConnectedByAccountIds( - long tenantId, Collection accountIds) { + public Map> listConnectedByAccountIds( + long tenantId, Collection accountIds) { if (accountIds == null || accountIds.isEmpty()) { return Map.of(); } - Map> results = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0) { + Map> results = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (accountId == null) { continue; } List matches = presences.values().stream() .filter( - presence -> presence.tenantId() == tenantId && presence.accountId() == accountId) + presence -> + presence.tenantId() == tenantId && accountId.equals(presence.accountId())) .sorted(ordering()) .toList(); if (!matches.isEmpty()) { 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 14b17cc986..1bbd778bf8 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 @@ -90,7 +90,8 @@ void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() t ArgumentCaptor captor = ArgumentCaptor.forClass(IssueDirectTextConnectScopeRequest.class); verify(stub).issueDirectTextConnectScope(captor.capture()); - assertThat(captor.getValue().getPlayerContext().getAccountId()).isEqualTo("41"); + assertThat(captor.getValue().getPlayerContext().getAccountId()) + .isEqualTo("d0c68a37-5126-42d2-9506-8df13e97699e"); assertThat(captor.getValue().getPlayerContext().getSessionId()).isEqualTo("7"); assertThat(captor.getValue().getTenantId()).isEqualTo("22"); assertThat(captor.getValue().getWorldSlug()).isEqualTo("demo-world"); @@ -304,7 +305,7 @@ void directTextJoinRechecksExpiryAfterChannelReloadBeforeRetry() throws Exceptio private static PlayerExecutionContext directTextContext(String requestId) { return PlayerExecutionContext.newBuilder() - .setAccountId("41") + .setAccountId("d0c68a37-5126-42d2-9506-8df13e97699e") .setSessionId("7") .setTenantId("22") .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java index a4a27094e4..5dc61371d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java @@ -26,7 +26,8 @@ class EntityManagementClientTest { private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, 0L, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, 22L, null, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, + "SHARED"); @Test void listRoomEntitiesFailsClosedWhenSessionContextDropsPartOfAdmittedRoutingBundle() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index 49f6284c6b..a6ff1ab169 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -39,9 +39,24 @@ import org.mockito.ArgumentCaptor; class GameLogicClientTest { + private static final String ACCOUNT_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, 0L, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, + 22L, + ACCOUNT_UUID, + "", + 123L, + "", + 1L, + "R-1021", + "", + null, + 1L, + "world", + "realm", + 17L, + "SHARED"); @Test void resolveLookForwardsGameInstanceIdIntoRoomInstance() throws Exception { @@ -317,7 +332,7 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( PickupVisibleRoomItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -422,7 +437,7 @@ void dropCarriedItemForwardsRawReferenceAndSessionContextThroughGameLogic() thro DropCarriedItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -527,10 +542,10 @@ private static GameLogicClient newClient() { GameplaySessionAttestationService attestationService = mock(GameplaySessionAttestationService.class); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-1021", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "world", "realm", "17", "SHARED")) .thenReturn("attestation"); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-2045", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-2045", "world", "realm", "17", "SHARED")) .thenReturn("destination-attestation"); when(attestationService.issueInternalProbeAttestation("22", "1", "R-1021")) .thenReturn("probe-attestation"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java index 2db4c405ba..3386891ce7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java @@ -22,7 +22,16 @@ class ActionStateCommandHandlerTest { private final ActionStateCommandHandler handler = new ActionStateCommandHandler(gameLogicClient, Clock.fixed(NOW, ZoneOffset.UTC)); private final SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); @Test void blockAppliesShortLivedBlockingState() { @@ -106,7 +115,16 @@ void applyUsesTheProvidedEffectPayload() { @Test void blockRejectsPartialGameplayIdentityShell() { SessionContext partialContext = - new SessionContext(42L, 22L, 7L, "demo@example.com", 0L, null, 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 0L, + null, + 5L, + "R-1", + "jwt-token"); var result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java index 35c17c0645..cd01f82b63 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java @@ -266,7 +266,17 @@ void rejectsUnregisteredCommandEffectsFromTheAdmittedBundle() { } private SessionContext context() { - return new SessionContext(1L, 7L, 2L, "player", 3L, "hero", 44L, "room", "jwt", 0L); + return new SessionContext( + 1L, + 7L, + "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30", + "player", + 3L, + "hero", + 44L, + "room", + "jwt", + 0L); } private GameInstance admittedInstance() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java index 8340547b0a..95e9418b08 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java @@ -25,7 +25,17 @@ class AfkCommandHandlerTest { void afkOnSetsExplicitAfkOnPresence() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1021", + null, + "en-NZ", + 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -40,7 +50,17 @@ void afkOnSetsExplicitAfkOnPresence() { void afkOffClearsExplicitAfkOnPresence() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1021", + null, + "en-NZ", + 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -72,7 +92,17 @@ void afkRequiresGameplayContext() { void afkRejectsPartialGameplayIdentityShellFromResolvedSession() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 1L, + "R-1021", + null, + "en-NZ", + 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -87,7 +117,17 @@ void afkRejectsPartialGameplayIdentityShellFromResolvedSession() { void directAfkRejectsPartialGameplayIdentityShell() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 1L, + "R-1021", + null, + "en-NZ", + 1L); AfkCommandHandlingResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java index e065a0e8dd..52840feeee 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java @@ -43,7 +43,16 @@ void admittedAuthoredActionFailsClosedUntilItsDeclaredEffectHasARuntimeHandler() TextCommandInterpretationResult result = handler.handle( - new SessionContext(1L, 1L, 2L, "player@example.com", 3L, "Player", 4L, "room", "jwt"), + new SessionContext( + 1L, + 1L, + "11111111-1111-4111-8111-111111111111", + "player@example.com", + 3L, + "Player", + 4L, + "room", + "jwt"), command); assertFalse(result.commandResult().accepted()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java index 13063bac47..1a999bea77 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java @@ -87,7 +87,15 @@ void rejectsAuthoredActionsWithoutGameplayContext() { private static SessionContext context() { return new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); } private static TextCommand authoredAction(String commandId, String rawLine, List args) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java index 930b9ec39c..e7a3a8ac22 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java @@ -43,7 +43,7 @@ class CommunicationCommandHandlerTest { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "emberline@example.com", 911L, "Emberline", @@ -144,7 +144,7 @@ void tellRequiresOnlineTarget() { Character.newBuilder() .setId("300") .setTenantId("22") - .setAccountId("700") + .setAccountId("b96201c6-8894-49ea-8f60-3f0b4ee72f5d") .setName("Sora") .build())); when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) @@ -164,7 +164,17 @@ void tellRequiresOnlineTarget() { void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { SessionContext normalizedTarget = new SessionContext( - 77L, 22L, 700L, "sora@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 77L, + 22L, + "b96201c6-8894-49ea-8f60-3f0b4ee72f5d", + "sora@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(entityManagementClient.findCharacterByName( sessionContext, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Sora")) .thenReturn( @@ -172,7 +182,7 @@ void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { Character.newBuilder() .setId("300") .setTenantId("22") - .setAccountId("700") + .setAccountId("b96201c6-8894-49ea-8f60-3f0b4ee72f5d") .setName("Sora") .build())); when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java index 7624a3e4fc..8abb5e0546 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java @@ -26,7 +26,15 @@ class ContainerCommandHandlerTest { private final ContainerCommandHandler handler = new ContainerCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void containerViewReturnsStructuredContents() { 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 ca9480694d..5ea4531d2d 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 @@ -16,10 +16,11 @@ import org.junit.jupiter.api.Test; class DirectTextOrdinalSelectionResolverTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final Instant NOW = Instant.parse("2030-05-06T07:08:09Z"); private final SessionContext caller = - new SessionContext(7L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + new SessionContext(7L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt"); private final RealmView realm = new RealmView( "production", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java index 211de4cf9c..9113c00828 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java @@ -24,7 +24,15 @@ class EquipmentCommandHandlerTest { private final EquipmentCommandHandler handler = new EquipmentCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void wearWithoutItemReferenceFailsFast() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index d5ba783c12..9e13ddfb27 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -37,11 +37,15 @@ import org.mockito.Mockito; class FriendsCommandHandlerTest { + private static final String CALLER_ACCOUNT_ID = "d0c68a37-5126-42d2-9506-8df13e97699e"; + private static final String FRIEND_ACCOUNT_ID = "550e8400-e29b-41d4-a716-446655440000"; + private static final String SECOND_FRIEND_ACCOUNT_ID = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; + private static final SessionContext GAMEPLAY_CONTEXT = new SessionContext( 7L, 1L, - 41L, + "d0c68a37-5126-42d2-9506-8df13e97699e", "demo@example.com", 99L, "Emberline", @@ -70,16 +74,16 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterId("99") .setCharacterName("Sora") @@ -119,7 +123,7 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { .satisfies( entry -> { assertThat(entry.friendLinkId()).isNull(); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.status()).isEqualTo("active"); assertThat(entry.linkedAtEpochMs()).isNull(); assertThat(entry.displayName()).isEqualTo("Sora"); @@ -136,7 +140,7 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Sora [acct #77] - online (idle)") + .contains("Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online (idle)") .doesNotContain( "private-playtest", "Private Playtest World", @@ -162,16 +166,16 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -199,7 +203,7 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { entry -> { assertThat(entry.friendLinkId()).isNull(); assertThat(entry.status()).isEqualTo("active"); - assertThat(entry.displayName()).isEqualTo("Friend #77"); + assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(entry.lastSeenAtEpochMs()) .isEqualTo(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()); }); @@ -218,15 +222,15 @@ void friendsOnlyPresenceDoesNotExposeDisconnectDispositionInText() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -286,13 +290,15 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("ADD", "77"), "friends add 77"), + TextCommandType.FRIENDS, + java.util.List.of("ADD", FRIEND_ACCOUNT_ID), + "friends add " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -300,12 +306,12 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 added."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -315,7 +321,8 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { Mockito.argThat( gameplayCommand -> "FRIENDS".equals(gameplayCommand.getCommandName()) - && "friends add 77".equals(gameplayCommand.getCommandText()))); + && ("friends add " + FRIEND_ACCOUNT_ID) + .equals(gameplayCommand.getCommandText()))); } @Test @@ -325,7 +332,8 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE) @@ -334,10 +342,10 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setVisibilityPolicy( @@ -364,9 +372,9 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) .contains("Friends ONLINE:\n") - .contains("1) Sora [acct #77] - online"); + .contains("1) Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @Test @@ -376,7 +384,8 @@ void friendsOnlineWithNoMatchesKeepsRosterTotalOutOfPlayerText() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE) @@ -402,7 +411,7 @@ void friendsOnlineWithNoMatchesKeepsRosterTotalOutOfPlayerText() { .contains("Friends ONLINE: no matching friends.") .doesNotContain("[0/2]", "[0/0]"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @Test @@ -444,19 +453,19 @@ void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(4) .setFriendLinkId("12") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setCreatedAtMs(1_744_336_000_000L) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterId("99") .setCharacterName("Sora") @@ -491,10 +500,10 @@ void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { ((FriendPresenceViewOutput) result.outputs().getFirst().payload()).friends().getFirst(); assertThat(entry.ordinal()).isEqualTo(4); assertThat(entry.friendLinkId()).isEqualTo(12L); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.status()).isEqualTo("active"); assertThat(entry.linkedAtEpochMs()).isEqualTo(1_744_336_000_000L); - assertThat(entry.displayName()).isEqualTo("Friend #77"); + assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(entry.online()).isNull(); assertThat(entry.worldSlug()).isNull(); assertThat(entry.worldDisplayName()).isNull(); @@ -510,7 +519,7 @@ void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friend #77") + .contains("Friend #" + FRIEND_ACCOUNT_ID + "") .contains("presence unavailable") .doesNotContain("Sora") .doesNotContain("Demo World") @@ -524,7 +533,8 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT) @@ -533,10 +543,10 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -558,7 +568,7 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { assertThat(view.totalCount()).isEqualTo(2); assertThat(view.friends()) .singleElement() - .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(77L)); + .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID)); } @Test @@ -568,7 +578,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendRosterSummary(1L, 41L)) + when(socialGroupsClient.getFriendRosterSummary(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendRosterSummaryResponse.newBuilder() .setSummary( @@ -613,7 +623,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { .doesNotContain("Recent offline:") .doesNotContain("Visibility") .doesNotContain("Scope"); - Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, CALLER_ACCOUNT_ID); } @Test @@ -629,8 +639,12 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -644,15 +658,15 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] added."); + assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).addFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -662,13 +676,15 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("REMOVE", "77"), "FRIENDS REMOVE 77"), + TextCommandType.FRIENDS, + java.util.List.of("REMOVE", FRIEND_ACCOUNT_ID), + "FRIENDS REMOVE " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -676,12 +692,12 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 removed."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -700,8 +716,12 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -717,15 +737,16 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).removeFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -735,17 +756,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) .setRemovedFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setCharacterName("Sora") .setVisibilityPolicy( FriendPresenceVisibilityPolicy @@ -765,16 +786,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); assertThat(mutation.ordinal()).isEqualTo(1); }); - Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test @@ -784,7 +806,7 @@ void friendsRemoveByOrdinalRejectsMalformedReturnedFriendAccountId() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) @@ -818,18 +840,18 @@ void friendsShowReturnsCanonicalFriendDetailView() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriend(1L, 41L, 77L)) + when(socialGroupsClient.getFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn( GetFriendResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setFriendLinkId("11") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setCreatedAtMs(Instant.parse("2026-04-10T01:02:03Z").toEpochMilli()) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setWorldSlug("private-playtest") @@ -852,7 +874,9 @@ void friendsShowReturnsCanonicalFriendDetailView() { TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("SHOW", "77"), "FRIENDS SHOW 77"), + TextCommandType.FRIENDS, + java.util.List.of("SHOW", FRIEND_ACCOUNT_ID), + "FRIENDS SHOW " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -861,7 +885,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { .extracting(PlayerOutput::payload) .isInstanceOf(FriendDetailViewOutput.class); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); - assertThat(detail.friend().friendAccountId()).isEqualTo(77L); + assertThat(detail.friend().friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(detail.friend().friendLinkId()).isEqualTo(11L); assertThat(detail.friend().characterName()).isEqualTo("Sora"); assertThat(detail.friend().online()).isTrue(); @@ -876,7 +900,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friend Sora [acct #77]") + .contains("Friend Sora [acct #" + FRIEND_ACCOUNT_ID + "]") .contains("Presence: online (idle)") .contains("Character: Sora") .doesNotContain( @@ -895,16 +919,16 @@ void friendsShowByOrdinalRedactsMissingPolicyAndRendersDetail() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( GetFriendByOrdinalResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setWorldDisplayName("Demo World") @@ -924,7 +948,7 @@ void friendsShowByOrdinalRedactsMissingPolicyAndRendersDetail() { assertThat(result.commandResult().accepted()).isTrue(); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); assertThat(detail.friend().ordinal()).isEqualTo(1); - assertThat(detail.friend().displayName()).isEqualTo("Friend #77"); + assertThat(detail.friend().displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(detail.friend().online()).isNull(); assertThat(detail.friend().characterName()).isNull(); assertThat(detail.friend().worldDisplayName()).isNull(); @@ -936,7 +960,7 @@ void friendsShowByOrdinalRedactsMissingPolicyAndRendersDetail() { .contains("Presence: presence unavailable") .contains("Roster entry: #1") .doesNotContain("Sora", "Demo World", "online", "idle"); - Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test @@ -950,7 +974,9 @@ void friendsMutationRejectsSelfLink() { TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("ADD", "41"), "FRIENDS ADD 41"), + TextCommandType.FRIENDS, + java.util.List.of("ADD", CALLER_ACCOUNT_ID), + "FRIENDS ADD " + CALLER_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isFalse(); @@ -990,7 +1016,7 @@ void friendsRemoveRejectsUnknownRosterOrdinal() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(false) @@ -1080,16 +1106,18 @@ void friendsListTreatsMalformedFriendLinkIdAsAbsent() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() .setFriendLinkId("abc") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( - FriendPresenceEntry.newBuilder().setFriendAccountId("77").build()) + FriendPresenceEntry.newBuilder() + .setFriendAccountId(FRIEND_ACCOUNT_ID) + .build()) .build()) .build()); @@ -1113,7 +1141,7 @@ void friendsListRejectsMalformedFriendAccountIdPayload() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( @@ -1142,7 +1170,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setCurrentPolicy( @@ -1178,7 +1206,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { .render(result.outputs().getFirst())) .contains("Friend presence visibility: FRIENDS_ONLY") .contains("Use FRIENDS VISIBILITY ."); - Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID); } @Test @@ -1188,7 +1216,7 @@ void friendsVisibilityViewFailsClosedWhenCanonicalPolicyReadIsUnavailable() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setError( @@ -1221,7 +1249,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1258,7 +1286,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { Mockito.verify(socialGroupsClient) .updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); Mockito.verify(scriptEventPublisher) @@ -1276,7 +1304,7 @@ void friendsVisibilityUpdateFailsClosedWhenCanonicalPolicyUpdateIsUnavailable() socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1329,7 +1357,7 @@ void friendsVisibilityRejectsReservedHiddenStaffPolicy() { .isEqualTo("ERROR INVALID_ARGUMENT FRIENDS VISIBILITY "); assertThat(result.outputs().getFirst().text()).doesNotContain("HIDDEN_STAFF"); Mockito.verify(socialGroupsClient, Mockito.never()) - .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); + .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyString(), Mockito.any()); } @Test 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 229823da75..7e4e0ee49c 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 @@ -314,7 +314,15 @@ void helpIndexHidesHistoryWhenFeatureDisabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(false)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -333,7 +341,15 @@ void helpIndexHidesEveryDisabledStandardCapabilityFamily() { CommandCapabilitiesTestSupport.resolver(false, false, false, true)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -353,7 +369,15 @@ void helpHistoryTopicUnavailableWhenFeatureDisabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(false)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -371,7 +395,15 @@ void helpHistoryTopicAvailableWhenFeatureEnabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(true)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = enabledHandler.handle( @@ -394,7 +426,15 @@ void publishedGameAuthoredTopicOverridesPlatformTopicForAdmittedSession() { HelpCommandHandler authoredHelpHandler = new HelpCommandHandler(reader, null, null); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); TextCommandInterpretationResult result = authoredHelpHandler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java index 2d20e1651b..75bee23eb2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java @@ -20,7 +20,15 @@ class HelpTextCommandDispatchHandlerTest { void publishesCommandEventForGameplayScopedHelp() { SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java index d69cd7549a..79c8676d9b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java @@ -193,7 +193,15 @@ void rejectsNonPositiveHistoryCountWithoutReadingStorage() { private SessionContext standardContext() { return new SessionContext( - 22L, 7L, 99L, "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 22L, + 7L, + "a3be406d-718c-419a-afcf-0afbc2e8e451", + "demo@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); } private HistoryCommandHandler handler( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java index 4859f2ae05..0977252b70 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java @@ -31,7 +31,16 @@ void dispatchesToHistoryHandler() { Mockito.when(historyStorageService.findRecent(7L, 9L, 7001L, 2)) .thenReturn(List.of("LOOK", "SAY hi")); SessionContext context = - new SessionContext(22L, 7L, 99L, "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + new SessionContext( + 22L, + 7L, + "a3be406d-718c-419a-afcf-0afbc2e8e451", + "demo@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java index 8e29601ed9..66e3f2f904 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java @@ -26,7 +26,15 @@ class InventoryCommandHandlerTest { private final InventoryCommandHandler handler = new InventoryCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void inventoryReturnsStructuredViewFromRuntimeContract() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java index b716bebb5c..292dc42846 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java @@ -30,7 +30,15 @@ class ItemCommandHandlerTest { scriptEventPublisher); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void recordsInvocationForSuccessfulItemCommand() { 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 ed9dbcfe85..697dd3ce43 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 @@ -44,13 +44,18 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class LoginCommandHandlerTest { private static final String AUTH_TOKEN = "mock-jwt"; + private static final String ACCOUNT_77 = "774f987b-6650-4d04-8e0f-441867c17923"; + private static final String ACCOUNT_99 = "998a7412-13c4-4dbc-86d9-8f40aee3c6f1"; private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private static final String SECOND_GAME_OWNER_ACCOUNT_UUID = "723c126e-4159-493b-ad15-36a67d673031"; @@ -81,7 +86,10 @@ void setUp() { stubSessionContext(bootstrapShell(1L, 1L)); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_77) + .build()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); sessionRoutingNormalizationService = @@ -382,7 +390,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { new SessionContext( 1L, 22L, - 0L, + null, null, 0L, null, @@ -402,7 +410,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + ACCOUNT_99, 22L, "demo", "production", @@ -428,7 +436,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { verify(accountClient, never()).requestEmailLoginOtp(anyString()); verify(sessionContextService, never()).save(any(SessionContext.class)); verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); - assertEquals(0L, shell.accountId()); + assertNull(shell.accountId()); assertNull(shell.jwt()); assertEquals(1L, shell.bootstrapGameInstanceId()); assertEquals("demo", shell.worldSlug()); @@ -452,7 +460,7 @@ void bareLoginRejectsDifferentVerifiedSubjectWithoutClearingPersistedAccount() { stubMutableSessionContext(accountA); FirstPartyConnectContext verifiedAccountBContext = new FirstPartyConnectContext( - 99L, + ACCOUNT_99, 33L, "demo", "production", @@ -474,7 +482,7 @@ void bareLoginRejectsDifferentVerifiedSubjectWithoutClearingPersistedAccount() { .clearGameplayBinding(any(SessionContext.class), anyString()); verify(gameInstanceRepository, never()).findById(anyLong()); verify(gameplayAdmissionPointerAuthorityService, never()).listByRuntimeTarget(33L, 2L); - assertEquals(77L, accountA.accountId()); + assertEquals(ACCOUNT_77, accountA.accountId()); assertEquals(22L, accountA.tenantId()); assertEquals(AUTH_TOKEN, accountA.jwt()); assertTrue(accountA.hasGameplayBinding()); @@ -515,7 +523,7 @@ void bareLoginForSameVerifiedSubjectPreservesRetryableSessionState() { verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(any(SessionContext.class), anyString()); verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); - assertEquals(77L, existing.accountId()); + assertEquals(ACCOUNT_77, existing.accountId()); assertEquals(AUTH_TOKEN, existing.jwt()); assertTrue(existing.hasGameplayBinding()); assertEquals("scope-stale", existing.connectScopeId()); @@ -553,7 +561,7 @@ void bareLoginForSameAccountInDifferentTenantClearsOldTenantBeforeReturningUnava verify(sessionContextService).save(savedContext.capture()); SessionContext tenantBShell = savedContext.getValue(); assertEquals(33L, tenantBShell.tenantId()); - assertEquals(0L, tenantBShell.accountId()); + assertNull(tenantBShell.accountId()); assertNull(tenantBShell.jwt()); assertFalse(tenantBShell.hasGameplayBinding()); assertEquals(2L, tenantBShell.bootstrapGameInstanceId()); @@ -577,12 +585,21 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi TextCommand credentialLogin = new TextCommand( TextCommandType.LOGIN, - List.of("demo@example.com", "swordfish"), - "LOGIN demo@example.com swordfish"); + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, OWNER_ACCOUNT_UUID); FirstPartyConnectContext accountAContext = new FirstPartyConnectContext( - 99L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); + ACCOUNT_77, + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); AtomicBoolean accountAContextRegistered = new AtomicBoolean(true); List registryEvents = new java.util.ArrayList<>(); Mockito.doAnswer( @@ -605,7 +622,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi new SessionContext( 1L, 22L, - 0L, + null, null, 0L, null, @@ -621,8 +638,16 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi "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(ACCOUNT_99) + .build()); LoginCommandHandlingResult firstPartyResult = handler.handle("1", bareLogin, false); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 3L))); LoginCommandHandlingResult credentialResult = handler.handle("1", credentialLogin, false); LoginCommandHandlingResult subsequentBareResult = handler.handle("1", bareLogin, false); @@ -637,33 +662,49 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi assertEquals( List.of("find-account-a", "find-account-a", "unregister", "find-empty"), registryEvents); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService, times(2)).save(captor.capture()); - SessionContext credentialIdentity = captor.getAllValues().get(0); - assertEquals(22L, credentialIdentity.tenantId()); - assertEquals(77L, credentialIdentity.accountId()); - assertEquals("demo@example.com", credentialIdentity.loginName()); - assertEquals(AUTH_TOKEN, credentialIdentity.jwt()); - assertNull(credentialIdentity.localeTag()); - assertEquals(1L, credentialIdentity.bootstrapGameInstanceId()); - assertNull(credentialIdentity.worldSlug()); - assertNull(credentialIdentity.realmSlug()); - assertEquals(0L, credentialIdentity.pointerVersion()); - assertNull(credentialIdentity.playableStateScope()); - assertNull(credentialIdentity.connectScopeId()); - assertNull(credentialIdentity.connectRequestId()); - assertClearedSessionContext(captor.getAllValues().get(1), 0L, null, null, null); + verify(sessionContextService, Mockito.times(2)).save(captor.capture()); + List savedContexts = captor.getAllValues(); + SessionContext credentialContext = savedContexts.get(0); + assertEquals(ACCOUNT_99, credentialContext.accountId()); + assertEquals(1L, credentialContext.bootstrapGameInstanceId()); + assertEquals("demo", credentialContext.worldSlug()); + assertEquals("production", credentialContext.realmSlug()); + assertEquals(3L, credentialContext.pointerVersion()); + assertEquals("SHARED", credentialContext.playableStateScope()); + assertNull(credentialContext.connectScopeId()); + assertNull(credentialContext.connectRequestId()); + assertEquals(0L, credentialContext.characterId()); + assertEquals(0L, credentialContext.gameInstanceId()); + + SessionContext unsupportedLoginShell = savedContexts.get(1); + assertFalse(unsupportedLoginShell.hasAccountIdentity()); + assertNull(unsupportedLoginShell.accountId()); + assertNull(unsupportedLoginShell.loginName()); + assertNull(unsupportedLoginShell.jwt()); + assertEquals(22L, unsupportedLoginShell.tenantId()); + assertEquals("en-NZ", unsupportedLoginShell.localeTag()); + assertEquals(1L, unsupportedLoginShell.bootstrapGameInstanceId()); + assertEquals("demo", unsupportedLoginShell.worldSlug()); + assertEquals("production", unsupportedLoginShell.realmSlug()); + assertEquals(3L, unsupportedLoginShell.pointerVersion()); + assertNull(unsupportedLoginShell.playableStateScope()); + assertNull(unsupportedLoginShell.connectScopeId()); + assertNull(unsupportedLoginShell.connectRequestId()); + assertEquals(0L, unsupportedLoginShell.characterId()); + assertEquals(0L, unsupportedLoginShell.gameInstanceId()); + assertNull(unsupportedLoginShell.roomInstanceId()); } @Test void staleFirstPartyRegistryCannotReplacePersistedCredentialIdentity() { SessionContext credentialIdentity = - new SessionContext(1L, 22L, 77L, "demo@example.com", 0L, null, 0L, "mock-jwt"); + new SessionContext(1L, 22L, ACCOUNT_77, "demo@example.com", 0L, null, 0L, "mock-jwt"); stubSessionContext(credentialIdentity); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + ACCOUNT_99, 22L, "demo", "production", @@ -692,7 +733,7 @@ void bareLoginFailsUnavailableForPersistedFirstPartyContextFallback() { new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, null, 0L, null, @@ -727,7 +768,7 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, null, 0L, null, @@ -755,6 +796,50 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss joinedOutputText(result.outputs())); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void bareLoginRejectsUnreadableRegistryContextWithoutPersistedFallback( + boolean serializationFailure) { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext persisted = + new SessionContext( + 1L, + 22L, + ACCOUNT_77, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 1L, + null, + "persisted-scope", + "persisted-request"); + stubSessionContext(persisted); + RuntimeException decodeFailure = + serializationFailure + ? new SerializationException("legacy numeric Account carrier") + : new ClassCastException("legacy numeric Account carrier"); + when(firstPartyConnectContextRegistry.find(1L)).thenThrow(decodeFailure); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + assertEquals( + "ERROR CONNECT_CONTEXT_INVALID Connect context invalid", + joinedOutputText(result.outputs())); + verify(accountClient, never()).authenticate(anyString(), anyString()); + verify(accountClient, never()).requestEmailLoginOtp(anyString()); + verify(gameInstanceRepository, never()).findById(anyLong()); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + } + @Test void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSessionIsMissing() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); @@ -763,7 +848,7 @@ void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSess new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, null, 0L, null, @@ -796,7 +881,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerTenantIsInvalid() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 0L, "demo", "production", @@ -822,7 +907,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerGameInstanceIdIsInvalid() .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 22L, "demo", "production", @@ -850,7 +935,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerWorldOrRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 22L, " ", "production", @@ -876,7 +961,16 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, 22L, "demo", " ", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"))); + ACCOUNT_77, + 22L, + "demo", + " ", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"))); when(gameInstanceRepository.findById(1L)) .thenReturn(Optional.of(buildInstance(1L, 22L, OWNER_ACCOUNT_UUID))); @@ -895,7 +989,7 @@ void bareLoginRejectsStalePointerVersion() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 22L, "demo", "production", @@ -935,7 +1029,7 @@ void successfulLoginStoresSessionContext() { net.firedevops.firemud.gamesession.service.SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals(ACCOUNT_77, context.accountId()); assertEquals(0L, context.characterId()); assertEquals(0L, context.gameInstanceId()); assertNull(context.roomInstanceId()); @@ -952,7 +1046,7 @@ void loginUsesBootstrappedGameInstanceInsteadOfTransportSessionId() { GameInstance instance = buildInstance(99L, 22L, OWNER_ACCOUNT_UUID); SessionContext bootstrapContext = - new SessionContext(12345L, 22L, 0L, null, 0L, null, 99L, null, null); + new SessionContext(12345L, 22L, null, null, 0L, null, 99L, null, null); when(sessionContextService.findBySessionId(12345L)).thenReturn(Optional.of(bootstrapContext)); when(sessionContextService.findByTenantAndSessionId(22L, 12345L)) .thenReturn(Optional.of(bootstrapContext)); @@ -1000,7 +1094,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1021,7 +1115,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1044,7 +1138,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals(ACCOUNT_77, context.accountId()); assertEquals(88L, context.characterId()); assertEquals(1L, context.gameInstanceId()); assertEquals("R-2045", context.roomInstanceId()); @@ -1063,12 +1157,15 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1095,7 +1192,7 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(99L, savedContext.getValue().accountId()); + assertEquals(ACCOUNT_99, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1111,7 +1208,10 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); stubSessionContext(staleGameplayContext(0L)); handler.handle("1", command, false); @@ -1124,10 +1224,10 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_ACCOUNT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals(77L, clearedContext.getValue().accountId()); + assertEquals(ACCOUNT_77, clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(99L, savedContext.getValue().accountId()); + assertEquals(ACCOUNT_99, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1143,12 +1243,15 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_77) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1174,9 +1277,9 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { .clearGameplayBinding(existing, "LOGIN_TENANT_CHANGED"); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); - assertEquals(77L, existing.accountId()); + assertEquals(ACCOUNT_77, existing.accountId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(77L, savedContext.getValue().accountId()); + assertEquals(ACCOUNT_77, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1192,7 +1295,10 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_77) + .build()); stubSessionContext(staleGameplayContext(0L)); handler.handle("1", command, false); @@ -1205,10 +1311,10 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_TENANT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals(77L, clearedContext.getValue().accountId()); + assertEquals(ACCOUNT_77, clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(77L, savedContext.getValue().accountId()); + assertEquals(ACCOUNT_77, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1225,12 +1331,15 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1256,7 +1365,7 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); inOrder.verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); - assertEquals(99L, context.accountId()); + assertEquals(ACCOUNT_99, context.accountId()); assertEquals("other@example.com", context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); @@ -1279,7 +1388,7 @@ void verifiedConnectForDifferentAccountPreservesPriorGameplayBinding() { new SessionContext( 1L, 33L, - 77L, + ACCOUNT_77, "old@example.com", 88L, "Sora", @@ -1301,7 +1410,7 @@ void verifiedConnectForDifferentAccountPreservesPriorGameplayBinding() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + ACCOUNT_99, 22L, "demo", "production", @@ -1322,7 +1431,7 @@ void verifiedConnectForDifferentAccountPreservesPriorGameplayBinding() { .clearGameplayBinding(any(SessionContext.class), anyString()); verify(gameInstanceRepository, never()).findById(anyLong()); verify(gameplayAdmissionPointerAuthorityService, never()).listByRuntimeTarget(22L, 1L); - assertEquals(77L, prior.accountId()); + assertEquals(ACCOUNT_77, prior.accountId()); assertEquals(33L, prior.tenantId()); assertEquals("old@example.com", prior.loginName()); assertEquals("old-jwt", prior.jwt()); @@ -1345,7 +1454,10 @@ void reloginAsDifferentAccountDoesNotReplaceContextWhenPresenceClearFails() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); SessionContext existing = staleGameplayContext(1L); stubSessionContext(existing); Mockito.doThrow(new IllegalStateException("presence clear unavailable")) @@ -1382,7 +1494,7 @@ void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals(ACCOUNT_77, context.accountId()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); assertEquals(0L, context.gameInstanceId()); @@ -1451,7 +1563,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1490,7 +1602,10 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1498,7 +1613,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { assertEquals("Logged in as demo@example.com", joinedOutputText(result.outputs())); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertEquals(99L, captor.getValue().accountId()); + assertEquals(ACCOUNT_99, captor.getValue().accountId()); assertEquals("demo@example.com", captor.getValue().loginName()); assertEquals(OWNER_ACCOUNT_UUID, instance.getOwnerAccountId()); } @@ -1917,7 +2032,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, @@ -1936,7 +2051,7 @@ private static SessionContext staleGameplayContext(long pointerVersion) { return new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1957,7 +2072,7 @@ private static SessionContext staleGameplayContextWithoutSelector(long pointerVe return new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1993,7 +2108,7 @@ private static void assertClearedSessionContext( String expectedLocaleTag) { assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(0L, context.accountId()); + assertNull(context.accountId()); assertNull(context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); @@ -2039,7 +2154,7 @@ void credentialLoginPreservesCurrentBootstrapTargetButDropsSubjectBoundConnectSc new SessionContext( 1L, 22L, - 0L, + null, null, 0L, null, @@ -2059,7 +2174,10 @@ void credentialLoginPreservesCurrentBootstrapTargetButDropsSubjectBoundConnectSc when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate("other@example.com", "swordfish")) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -2067,7 +2185,7 @@ void credentialLoginPreservesCurrentBootstrapTargetButDropsSubjectBoundConnectSc ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); SessionContext saved = captor.getValue(); - assertEquals(99L, saved.accountId()); + assertEquals(ACCOUNT_99, saved.accountId()); assertEquals(1L, saved.bootstrapGameInstanceId()); assertEquals("demo", saved.worldSlug()); assertEquals("production", saved.realmSlug()); @@ -2091,7 +2209,7 @@ void credentialLoginDropsStaleBootstrapTargetAndSubjectBoundConnectScope() { new SessionContext( 1L, 22L, - 0L, + null, null, 0L, null, @@ -2109,7 +2227,10 @@ void credentialLoginDropsStaleBootstrapTargetAndSubjectBoundConnectScope() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate("other@example.com", "swordfish")) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -2117,7 +2238,7 @@ void credentialLoginDropsStaleBootstrapTargetAndSubjectBoundConnectScope() { ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); SessionContext saved = captor.getValue(); - assertEquals(99L, saved.accountId()); + assertEquals(ACCOUNT_99, saved.accountId()); assertEquals(1L, saved.bootstrapGameInstanceId()); assertNull(saved.worldSlug()); assertNull(saved.realmSlug()); @@ -2136,7 +2257,7 @@ void verifiedConnectForDifferentTenantClearsPriorBindingWithoutReusingItsBootstr new SessionContext( 1L, 33L, - 77L, + ACCOUNT_77, "old@example.com", 88L, "Sora", @@ -2158,7 +2279,7 @@ void verifiedConnectForDifferentTenantClearsPriorBindingWithoutReusingItsBootstr .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 22L, "demo", "production", @@ -2182,7 +2303,7 @@ void verifiedConnectForDifferentTenantClearsPriorBindingWithoutReusingItsBootstr inOrder.verify(sessionContextService).save(saved.capture()); SessionContext freshTenantShell = saved.getValue(); assertEquals(22L, freshTenantShell.tenantId()); - assertEquals(0L, freshTenantShell.accountId()); + assertNull(freshTenantShell.accountId()); assertNull(freshTenantShell.loginName()); assertEquals(0L, freshTenantShell.characterId()); assertNull(freshTenantShell.characterName()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java index 8a629b6b61..e8fa35924f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java @@ -13,38 +13,37 @@ import org.mockito.Mockito; class LogoutCommandHandlerTest { + private static final String ACCOUNT_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final LogoutCommandHandler handler = new LogoutCommandHandler(sessionContextService); @Test - void authenticatedSharedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { - SessionContext context = context(41L, 123L, 1L, "SHARED"); - when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(context)); + void authenticatedSharedRuntimeLogoutFailsWithoutMutatingContext() { + when(sessionContextService.findBySessionId(41L)) + .thenReturn(Optional.of(context(41L, ACCOUNT_UUID, 1L, "SHARED"))); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); + assertUnavailable(handler.handle("41", logoutCommand())); - assertUnavailable(result); verify(sessionContextService).findBySessionId(41L); verifyNoMoreInteractions(sessionContextService); } @Test - void authenticatedIsolatedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { - SessionContext context = context(41L, 123L, 7L, "ISOLATED"); - when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(context)); + void authenticatedIsolatedRuntimeLogoutFailsWithoutMutatingContext() { + when(sessionContextService.findBySessionId(41L)) + .thenReturn(Optional.of(context(41L, ACCOUNT_UUID, 7L, "ISOLATED"))); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); + assertUnavailable(handler.handle("41", logoutCommand())); - assertUnavailable(result); verify(sessionContextService).findBySessionId(41L); verifyNoMoreInteractions(sessionContextService); } @Test - void unauthenticatedContextStillReturnsNotLoggedInWithoutMutation() { + void loggedOutContextRemainsNotLoggedInWithoutMutation() { when(sessionContextService.findBySessionId(41L)) - .thenReturn(Optional.of(context(41L, 0L, 1L, "SHARED"))); + .thenReturn(Optional.of(context(41L, null, 1L, "SHARED"))); LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); @@ -63,19 +62,20 @@ void unauthenticatedContextStillReturnsNotLoggedInWithoutMutation() { } @Test - void missingSessionStillReturnsNotLoggedIn() { + void missingSessionRemainsNotLoggedIn() { when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.empty()); LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + assertThat(result.commandResult().errorMessage()).isEqualTo("You are not logged in."); verify(sessionContextService).findBySessionId(41L); verifyNoMoreInteractions(sessionContextService); } @Test - void invalidSessionIdReturnsNotLoggedInWithoutLookingUpOrMutatingContext() { + void invalidSessionIdDoesNotLookUpOrMutateContext() { LogoutCommandHandlingResult result = handler.handle("not-a-session", logoutCommand()); assertThat(result.commandResult().accepted()).isFalse(); @@ -84,13 +84,12 @@ void invalidSessionIdReturnsNotLoggedInWithoutLookingUpOrMutatingContext() { } @Test - void unavailableSessionAuthorityReturnsRetryableFailure() { + void unavailableSessionAuthorityReturnsRetryableFailureWithoutMutation() { when(sessionContextService.findBySessionId(41L)) .thenThrow(new IllegalStateException("session store unavailable")); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); + assertUnavailable(handler.handle("41", logoutCommand())); - assertUnavailable(result); verify(sessionContextService).findBySessionId(41L); verifyNoMoreInteractions(sessionContextService); } @@ -116,7 +115,7 @@ private static TextCommand logoutCommand() { } private static SessionContext context( - long sessionId, long accountId, long gameInstanceId, String scope) { + long sessionId, String accountId, long gameInstanceId, String scope) { return new SessionContext( sessionId, 22L, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java index 180d6e8d3b..3939ca10ce 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java @@ -54,7 +54,7 @@ class LookCommandHandlerTest { lookCacheService, outputRenderer); private final SessionContext sessionContext = - new SessionContext(1L, 22L, 123L, 911L, 0L, "R-42", "jwt"); + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 911L, 0L, "R-42", "jwt"); private final LookResult lookResult = LookResult.newBuilder() .setRoomInstance(RoomInstanceRef.newBuilder().setRoomInstanceId("R-1021").build()) @@ -217,7 +217,16 @@ void quickLookUsesSharedLookupButShorterRenderVariant() { @Test void cachesRenderedLookByGameplayInstanceWhenAvailable() { SessionContext playedContext = - new SessionContext(17L, 22L, 123L, "demo", 911L, "demo", 77L, "R-42", "jwt"); + new SessionContext( + 17L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo", + 911L, + "demo", + 77L, + "R-42", + "jwt"); when(sessionAuthenticationService.resolveSessionContext("played")) .thenReturn(Optional.of(playedContext)); when(gameLogicClient.resolveLook(playedContext, "R-42", "")).thenReturn(lookResult); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java index a69f16082f..d0fa1bcf18 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java @@ -58,7 +58,15 @@ void setUp() { meterRegistry); context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 7L, "R-1021", "jwt-token"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 7L, + "R-1021", + "jwt-token"); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 52bb5b0686..7693d63e5d 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 @@ -62,9 +62,11 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.springframework.data.redis.serializer.SerializationException; class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; + private static final String PLAYER_ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final ObjectMapper JSON = new ObjectMapper(); private static final UUID ADMISSION_REALM_ID = UUID.fromString("00000000-0000-0000-0000-000000000001"); @@ -128,7 +130,7 @@ void setUp() { scriptEventPublisher, meterRegistry, connectScopeSessionStore); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -141,7 +143,7 @@ void setUp() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")), + .active(PLAYER_ACCOUNT_ID, 22L, "1")), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -199,7 +201,15 @@ void setUp() { @Test void playPromotesSessionIntoGameplay() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "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()); @@ -215,7 +225,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -233,7 +243,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -251,7 +261,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -270,7 +280,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -295,7 +305,8 @@ void playPromotesSessionIntoGameplay() { Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); admissionOrder .verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(entityManagementClient, never()) .findCharacterByName( Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); @@ -305,13 +316,17 @@ void playPromotesSessionIntoGameplay() { void playUsesSelectedTargetRosterInsteadOfStaleContextCharacterId() { SessionContext context = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 9999L, "demo", 41L, "R-1", "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 9999L, "demo", 41L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "8008", + "demo", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 8008L)) .thenReturn(Optional.empty()); @@ -330,10 +345,11 @@ void playUsesSelectedTargetRosterInsteadOfStaleContextCharacterId() { @Test void playRejectsSameNameCharacterFromAnotherAccountBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); @@ -349,10 +365,11 @@ void playRejectsSameNameCharacterFromAnotherAccountBeforeBinding() { @Test void playRejectsMissingCharacterEvidenceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); PlayCommandHandlingResult result = @@ -368,22 +385,28 @@ void playRejectsMissingCharacterEvidenceBeforeBinding() { @Test void playRejectsAmbiguousCharacterEvidenceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", + "demo", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8009") .setTenantId("22") - .setAccountId("123") + .setAccountId(PLAYER_ACCOUNT_ID) .setName("Demo") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -399,10 +422,11 @@ void playRejectsAmbiguousCharacterEvidenceBeforeBinding() { @Test void playRejectsNamespaceUnqualifiedRosterBeforeAdmissionOrBindingSideEffects() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( ListCharactersByAccountResponse.newBuilder() .setError( @@ -419,14 +443,15 @@ void playRejectsNamespaceUnqualifiedRosterBeforeAdmissionOrBindingSideEffects() assertThat(((ErrorOutput) result.outputs().getFirst().payload()).code()) .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); Mockito.verify(moderationPolicyClient, Mockito.never()) - .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong()); + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); verifyNoGameplayBindingSideEffects(); } @Test void numericWorldPlayRejectsReorderedWorldSnapshotBeforeAdmissionSideEffects() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); gameplayCatalogProperties .getWorlds() @@ -471,7 +496,8 @@ void numericWorldSelectorUsesInjectedAuthorityClockForSnapshotLookup() { Instant authorityNow = Instant.parse("2000-01-02T03:04:05Z"); Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); DirectTextConnectScopeSessionStore scopeStore = @@ -496,7 +522,8 @@ void numericRealmSelectorUsesInjectedAuthorityClockForSnapshotLookup() { Instant authorityNow = Instant.parse("2000-01-02T03:04:05Z"); Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = @@ -526,7 +553,8 @@ void numericRealmSelectorMapsPointerExceptionsToTypedFailures(String pointerFail Instant authorityNow = Instant.parse("2030-05-06T07:08:09Z"); Clock authorityClock = Clock.fixed(authorityNow, ZoneOffset.UTC); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); GameplayWorldCatalog baseCatalog = worldCatalog; GameplayWorldCatalog.DiscoverySnapshot worldSnapshot = baseCatalog.readDiscoverySnapshot(); @@ -594,7 +622,8 @@ void numericRealmSelectorMapsPointerExceptionsToTypedFailures(String pointerFail @Test void numericWorldPlayTreatsUnrecognizedSecondSelectorAsCharacterWhenDefaultRealmIsUnambiguous() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); connectScopeSessionStore.replaceWorldSnapshot( @@ -612,10 +641,14 @@ void numericWorldPlayTreatsUnrecognizedSecondSelectorAsCharacterWhenDefaultRealm .setName("Sora") .build())); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Sora", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -630,7 +663,8 @@ void numericWorldPlayTreatsUnrecognizedSecondSelectorAsCharacterWhenDefaultRealm @Test void numericWorldCharacterPlayRejectsStaleWorldSnapshotBeforeAdmissionSideEffects() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); GameplayWorldCatalog.DiscoverySnapshot snapshot = worldCatalog.readDiscoverySnapshot(); connectScopeSessionStore.replaceWorldSnapshot( @@ -660,7 +694,8 @@ void numericWorldCharacterPlayRejectsStaleWorldSnapshotBeforeAdmissionSideEffect @Test void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -682,7 +717,8 @@ void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { @Test void publicNumericPlayIgnoresPointerChangesToDeniedPrivateRealms() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -716,7 +752,8 @@ void publicNumericPlayIgnoresPointerChangesToDeniedPrivateRealms() { @Test void numericPlayRealmRejectsChangedTargetThatWasShownToTheCaller() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "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 = @@ -744,7 +781,8 @@ void numericPlayRealmRejectsChangedTargetThatWasShownToTheCaller() { @Test void numericPlayStillDeniesWhenSelectedPrivateGrantHasBeenRevoked() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "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 = @@ -765,7 +803,9 @@ void numericPlayStillDeniesWhenSelectedPrivateGrantHasBeenRevoked() { Mockito.eq("preview"), Mockito.anyString())) .thenReturn( - validGrant("123", "22", "demo", "preview").toBuilder().setGranted(false).build()); + validGrant(PLAYER_ACCOUNT_ID, "22", "demo", "preview").toBuilder() + .setGranted(false) + .build()); PlayCommandHandlingResult denied = handler.handle( @@ -789,7 +829,7 @@ void numericPlayStillDeniesWhenSelectedPrivateGrantHasBeenRevoked() { assertHiddenRealmDenialMatchesUnknownSelection(denied, unknown, "preview"); Mockito.verify(accountClient, Mockito.times(1)) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("demo"), Mockito.eq("preview"), @@ -801,7 +841,8 @@ void numericPlayStillDeniesWhenSelectedPrivateGrantHasBeenRevoked() { @Test void numericPlayRealmUsesTenantQualifiedSnapshotForDuplicateWorldSlug() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); GameplayCatalogProperties.World secondTenantWorld = world( @@ -857,7 +898,7 @@ void numericPlayRealmUsesTenantQualifiedSnapshotForDuplicateWorldSlug() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 23L, "1")), + .active(PLAYER_ACCOUNT_ID, 23L, "1")), invocation.getArgument(0))) .when(accountClient) .getTenantMembershipForRuntime( @@ -886,7 +927,7 @@ void numericPlayRealmUsesTenantQualifiedSnapshotForDuplicateWorldSlug() { Mockito.verify(accountClient) .getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); - Mockito.verify(moderationPolicyClient).evaluateGameplayAdmission(23L, 123L); + Mockito.verify(moderationPolicyClient).evaluateGameplayAdmission(23L, PLAYER_ACCOUNT_ID); Mockito.verify(sessionContextService) .save( Mockito.argThat( @@ -900,7 +941,8 @@ void numericPlayRealmUsesTenantQualifiedSnapshotForDuplicateWorldSlug() { @Test void numericPlayRealmFailsClosedForWrongTenantOrStaleRealmSnapshot() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); List configuredWorlds = new ArrayList<>(gameplayCatalogProperties.getWorlds()); @@ -981,7 +1023,8 @@ void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { .getFirst() .setPublicProductionRealm(true); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult ambiguousDefaultResult = @@ -1012,7 +1055,8 @@ void playFailsClosedWhenTenantHasNoPublicProductionRealm() { .getFirst() .setPublicProductionRealm(false); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1083,7 +1127,7 @@ void playRejectsPointerRevisionCutoverBeforeAdmissionReads() { scriptEventPublisher, meterRegistry, connectScopeSessionStore); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, PLAYER_ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1135,7 +1179,7 @@ void playMapsFinalPointerReadOutageToAuthUnavailableWithoutAdmissionSideEffects( scriptEventPublisher, meterRegistry, connectScopeSessionStore); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, PLAYER_ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1183,7 +1227,7 @@ void playMapsPointerAuthorityReadFailureBeforeAccountOrEntityAdmissionReads() { scriptEventPublisher, meterRegistry, connectScopeSessionStore); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, PLAYER_ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1241,7 +1285,7 @@ void playMapsMalformedDiscoveryPointerToAdmissionPointerUnavailableWithoutSideEf scriptEventPublisher, meterRegistry, connectScopeSessionStore); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, PLAYER_ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1294,7 +1338,7 @@ void playMapsDefaultRealmPointerReadFailureToAuthUnavailableWithoutAdmissionSide scriptEventPublisher, meterRegistry, connectScopeSessionStore); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, PLAYER_ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1331,7 +1375,8 @@ void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm( "Maintenance World", List.of(realm("maintenance", "Maintenance Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -1347,7 +1392,8 @@ void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm( .getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -1367,7 +1413,8 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { "Other Public World", List.of(realm("production", "Live Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1385,9 +1432,21 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(moderationPolicyClient.evaluateGameplayAdmission(22L, 123L)) + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(moderationPolicyClient.evaluateGameplayAdmission(22L, PLAYER_ACCOUNT_ID)) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(false) @@ -1407,13 +1466,25 @@ void playRejectsModerationPolicyDeniedAdmission() { @Test void playUsesPersistedAccountRosterCharacterForSelectedTarget() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "9007", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "9007", + "Emberline", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) .thenReturn(Optional.empty()); @@ -1431,7 +1502,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 9007L, "Emberline", @@ -1449,7 +1520,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 9007L, "Emberline", @@ -1469,7 +1540,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 9007L, "Emberline", @@ -1489,15 +1560,27 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { @Test void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1509,15 +1592,20 @@ void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -1532,13 +1620,18 @@ void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playRejectsMalformedPersistedRosterCharacterId() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "abc", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "abc", + "Emberline", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -1564,10 +1657,18 @@ void playRejectsMalformedPersistedRosterCharacterId() { @Test void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); @@ -1583,13 +1684,25 @@ void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { @Test void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "8008", "demo", "23", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "8008", + "demo", + "23", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1602,22 +1715,35 @@ void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { @Test void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", + "demo", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8008") .setTenantId("22") - .setAccountId("123") + .setAccountId(PLAYER_ACCOUNT_ID) .setName("other") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -1631,22 +1757,28 @@ void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { @Test void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", + "demo", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8009") .setTenantId("22") - .setAccountId("123") + .setAccountId(PLAYER_ACCOUNT_ID) .setName("Demo") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -1659,10 +1791,11 @@ void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { @Test void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); PlayCommandHandlingResult result = @@ -1675,22 +1808,28 @@ void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { @Test void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", + "demo", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8009") .setTenantId("22") - .setAccountId("123") + .setAccountId(PLAYER_ACCOUNT_ID) .setName("Emberline") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -1703,7 +1842,8 @@ void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() @Test void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1718,10 +1858,18 @@ void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { @Test void playRejectsUnavailableCharacterRosterBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( ListCharactersByAccountResponse.newBuilder() .setError( @@ -1744,7 +1892,7 @@ void playResumeRejectsChangedRosterIdentityWithoutBinding() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", @@ -1774,14 +1922,23 @@ void playResumeRejectsChangedRosterIdentityWithoutBinding() { @Test void playRejectsEntityRosterErrorWithoutBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "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); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1792,7 +1949,15 @@ void playRejectsEntityRosterErrorWithoutBinding() { @Test void playReadsMembershipGrantAndEntitlementBeforeActorRoster() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "41", @@ -1819,14 +1984,15 @@ void playReadsMembershipGrantAndEntitlementBeforeActorRoster() { order .verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); order .verify(entityManagementClient) - .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -1835,7 +2001,7 @@ void playResumeDoesNotPublishSpawnEvent() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", @@ -1850,10 +2016,14 @@ void playResumeDoesNotPublishSpawnEvent() { "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1873,9 +2043,27 @@ void playResumeDoesNotPublishSpawnEvent() { @Test void playIgnoresStaleExistingBindingAfterNormalization() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); SessionContext clearedExisting = - new SessionContext(9L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); + new SessionContext( + 9L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "old-jwt", + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(clearedExisting)); @@ -1890,7 +2078,7 @@ void playIgnoresStaleExistingBindingAfterNormalization() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -1912,12 +2100,20 @@ void playIgnoresStaleExistingBindingAfterNormalization() { @Test void playIgnoresExistingBindingWithoutRoomRegion() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); SessionContext existingWithoutRoom = new SessionContext( 9L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -1944,7 +2140,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -1965,13 +2161,23 @@ void playIgnoresExistingBindingWithoutRoomRegion() { @Test void firstPartyPlayRejectsMismatchedConnectScope() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, + PLAYER_ACCOUNT_ID, 22L, "demo", "production", @@ -1997,13 +2203,23 @@ void firstPartyPlayRejectsMismatchedConnectScope() { @Test void firstPartyPlayRejectsMismatchedWorldSlug() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, + PLAYER_ACCOUNT_ID, 22L, "sandbox", "production", @@ -2025,13 +2241,32 @@ void firstPartyPlayRejectsMismatchedWorldSlug() { void firstPartyPlayRejectsStalePointerVersion() { gameplayCatalogProperties.getWorlds().get(0).getRealms().get(0).setPointerVersion(9L); SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 8L, "scope-1", "jti-1", "req-1", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + "production", + 1L, + 8L, + "scope-1", + "jti-1", + "req-1", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -2043,13 +2278,32 @@ void firstPartyPlayRejectsStalePointerVersion() { @Test void firstPartyPlayRejectsConnectContextMissingRealmSlug() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", null, 1L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + null, + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -2060,16 +2314,95 @@ void firstPartyPlayRejectsConnectContextMissingRealmSlug() { .isEqualTo("ERROR CONNECT_CONTEXT_INVALID Connect context invalid"); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void firstPartyPlayRejectsUnreadableRegistryContextWithoutPersistedFallback( + boolean serializationFailure) { + SessionContext persisted = + new SessionContext( + 1L, + 22L, + PLAYER_ACCOUNT_ID, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 1L, + null, + "persisted-scope", + "persisted-request"); + when(sessionAuthenticationService.resolveSessionContext("1")) + .thenReturn(Optional.of(persisted)); + RuntimeException decodeFailure = + serializationFailure + ? new SerializationException("legacy numeric Account carrier") + : new ClassCastException("legacy numeric Account carrier"); + when(firstPartyConnectContextRegistry.find(1L)).thenThrow(decodeFailure); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); + assertThat(joinedOutputText(result.outputs())) + .isEqualTo("ERROR CONNECT_CONTEXT_INVALID Connect context invalid"); + Mockito.verify(accountClient, Mockito.never()).getTenantMembershipForRuntime(Mockito.any()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(entityManagementClient, Mockito.never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, Mockito.never()) + .registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishCommandEvent(Mockito.any(), Mockito.any(GameplayCommand.class)); + } + @Test void firstPartyPlayRejectsConnectContextMissingConnectScope() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 1L, "", "jti-1", "req-1", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + "production", + 1L, + 1L, + "", + "jti-1", + "req-1", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -2081,13 +2414,32 @@ void firstPartyPlayRejectsConnectContextMissingConnectScope() { @Test void firstPartyPlayRejectsConnectContextMissingConnectRequest() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -2109,7 +2461,8 @@ void playWithoutSessionReturnsLoginRequired() { @Test void playWithoutArgumentsReturnsInvalidArgument() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -2121,7 +2474,8 @@ void playWithoutArgumentsReturnsInvalidArgument() { @Test void unknownWorldReturnsSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -2171,7 +2525,7 @@ void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { scriptEventPublisher, meterRegistry, connectScopeSessionStore); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, PLAYER_ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -2227,7 +2581,8 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { meterRegistry, connectScopeSessionStore); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -2239,13 +2594,15 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); Mockito.verify(entityManagementClient, never()) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); } @Test void sandboxWithoutCharacterReturnsSelectionRequired() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -2266,7 +2623,8 @@ void sandboxWithoutCharacterReturnsSelectionRequired() { @Test void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -2306,7 +2664,8 @@ void playRejectsIsolatedStateRealm() { .getRealms() .get(1) .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -2329,19 +2688,41 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { .get(1) .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", + PLAYER_ACCOUNT_ID, + 22L, + "sandbox", + "preview", + 41L, + 1L, + "scope-1", + "jti-1", + "req-1", "gw-1"))); when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + "22", PLAYER_ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn( characterRoster( - "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + "7002", + "Sora", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -2368,7 +2749,7 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "first-party:123", 0L, null, @@ -2385,10 +2766,14 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { "req-persisted"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + "22", PLAYER_ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn( characterRoster( - "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + "7002", + "Sora", + "22", + PLAYER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -2412,7 +2797,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "first-party:123", 0L, null, @@ -2447,11 +2832,12 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( @Test void playPrivateMembershipDenialUsesNonEnumeratingSelectionFailure() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubMembershipResponses( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L)); + PLAYER_ACCOUNT_ID, 22L)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -2478,7 +2864,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { new SessionContext( 1L, 23L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -2500,7 +2886,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing(PLAYER_ACCOUNT_ID, 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -2528,11 +2914,11 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { void playDeniedDoesNotClearCrossTenantSameSlugBinding() { SessionContext context = new SessionContext( - 1L, 23L, 123L, "demo@example.com", 7001L, "demo", 1L, "R-1", "jwt-token"); + 1L, 23L, PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubMembershipResponses( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L)); + PLAYER_ACCOUNT_ID, 22L)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(false)); @@ -2549,7 +2935,15 @@ void playDeniedDoesNotClearCrossTenantSameSlugBinding() { @Test void playRejectsMalformedActiveMembershipEvidenceWithoutGameplaySideEffects() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -2559,7 +2953,8 @@ void playRejectsMalformedActiveMembershipEvidenceWithoutGameplaySideEffects() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support - .RuntimeMembershipTestFixtures.active(123L, 22L, "2")) + .RuntimeMembershipTestFixtures.active( + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "2")) .toBuilder() .setGameplayAdmissionAllowed(false) .build(), @@ -2594,7 +2989,16 @@ void playRejectsMalformedActiveMembershipEvidenceWithoutGameplaySideEffects() { @Test void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -2604,7 +3008,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = @@ -2638,7 +3042,7 @@ void playNonPublicLeftMembershipRequiresEnrollment() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( @@ -2676,7 +3080,7 @@ void playBoundNonPublicLeftMembershipRequiresEnrollmentAndClearsBinding() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( @@ -2745,7 +3149,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -2778,7 +3182,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { .clearGameplayBinding(context, "realm_access_denied"); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -2805,7 +3209,7 @@ void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -2817,9 +3221,10 @@ void privateOnlyWorldPlayDenialMatchesUnknownAndGrantedAccessStillWorks() { SessionContext context = previewRealmContext(); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubMembershipResponses( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing(123L, 22L), + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( + PLAYER_ACCOUNT_ID, 22L), net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 123L, 22L, "1")); + PLAYER_ACCOUNT_ID, 22L, "1")); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), @@ -2848,7 +3253,7 @@ void playCharacterShorthandDoesNotDistinguishHiddenRealmFromUnknownName() { .thenReturn(Optional.of(loggedInUnboundContext())); stubMembershipResponses( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L)); + PLAYER_ACCOUNT_ID, 22L)); PlayCommandHandlingResult hidden = handler.handle( @@ -2881,7 +3286,7 @@ void playHiddenRealmInPublicWorldMasksMembershipDenialLikeUnknownSelection() { when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubMembershipResponses( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L)); + PLAYER_ACCOUNT_ID, 22L)); PlayCommandHandlingResult denied = handler.handle( @@ -2922,7 +3327,7 @@ void playUnlistedNonPublicRealmInPublicWorldMasksDeniedGrantLikeUnknownSelection when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubMembershipResponses( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 123L, 22L, "1")); + PLAYER_ACCOUNT_ID, 22L, "1")); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), @@ -2949,7 +3354,7 @@ void playUnlistedNonPublicRealmInPublicWorldMasksDeniedGrantLikeUnknownSelection assertHiddenRealmDenialMatchesUnknownSelection(denied, unknown, "invite-only"); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("demo"), Mockito.eq("invite-only"), @@ -3085,7 +3490,16 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED", "FAILED_PRECONDITION"}) void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3116,7 +3530,25 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { @Test void playPublicMissingMembershipReturnsJoinRequiredBeforeCharacterRosterLookup() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + PLAYER_ACCOUNT_ID, + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "login-account-scope", + "login-account-request"); + assertThat(context.hasGameplayBinding()).isTrue(); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3126,27 +3558,85 @@ void playPublicMissingMembershipReturnsJoinRequiredBeforeCharacterRosterLookup() .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing(PLAYER_ACCOUNT_ID, 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_MESSAGE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.join-required"); + assertThat(result.outputs()).hasSize(1); + Mockito.verify(gameplayPresenceLifecycleService, Mockito.times(1)) + .clearGameplayBinding(context, "join_required"); + + ArgumentCaptor savedContextCaptor = + ArgumentCaptor.forClass(SessionContext.class); + Mockito.verify(sessionContextService).save(savedContextCaptor.capture()); + SessionContext savedContext = savedContextCaptor.getValue(); + assertThat(savedContext.accountId()).isEqualTo(context.accountId()); + assertThat(savedContext.loginName()).isEqualTo(context.loginName()); + assertThat(savedContext.jwt()).isEqualTo(context.jwt()); + assertThat(savedContext.connectScopeId()).isEqualTo(context.connectScopeId()); + assertThat(savedContext.connectRequestId()).isEqualTo(context.connectRequestId()); + assertThat(savedContext.localeTag()).isEqualTo(context.localeTag()); + assertThat(savedContext.bootstrapGameInstanceId()).isEqualTo(1L); + assertThat(savedContext.characterId()).isZero(); + assertThat(savedContext.characterName()).isNull(); + assertThat(savedContext.gameInstanceId()).isZero(); + assertThat(savedContext.roomInstanceId()).isNull(); + assertThat(savedContext.playableStateScope()).isNull(); + assertThat(savedContext.hasGameplayBinding()).isFalse(); + assertThat(savedContext.worldSlug()).isEqualTo("demo"); + assertThat(savedContext.realmSlug()).isEqualTo("production"); + assertThat(savedContext.pointerVersion()).isEqualTo(1L); Mockito.verify(entityManagementClient, never()) .listCharactersByAccount( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(PlayableStateScope.class)); - verifyNoGameplayBindingSideEffects(); + Mockito.verify(entityManagementClient, never()) + .findCharacterByName( + Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, never()) + .publishCommandEvent(Mockito.any(), Mockito.any(GameplayCommand.class)); + Mockito.verify(scriptEventPublisher, never()) + .publishSpawnEvent(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + Mockito.verify(moderationPolicyClient, never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(accountClient, never()) + .joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class)); } @ParameterizedTest @ValueSource(strings = {"", "ACTIVE", "UNKNOWN"}) void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleState) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3155,7 +3645,7 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)); + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); var malformedLifecycle = response.toBuilder() .setMembershipLifecycleState(lifecycleState) @@ -3181,7 +3671,15 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta @ValueSource(strings = {"MISSING", "INACTIVE"}) void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleState) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3191,10 +3689,10 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt "INACTIVE".equals(lifecycleState) ? freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3")) + .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3")) : freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)); + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( response.toBuilder().setGameplayAdmissionAllowed(true).build(), @@ -3215,7 +3713,7 @@ void playLeftMembershipRequiresJoinForPublicProduction() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); var leftEvent = MembershipAuthorityEventV1Codec.verify( leftMembership.getOutboxSourceEvidence(0).getCanonicalEventJson()); @@ -3223,9 +3721,9 @@ void playLeftMembershipRequiresJoinForPublicProduction() { assertThat(leftMembership.getGameplayAdmissionAllowed()).isFalse(); assertThat(leftMembership.getMembershipLifecycleState()).isEqualTo("INACTIVE"); assertThat(leftMembership.getAuthorityAvailability()).isEqualTo("AVAILABLE"); - assertThat(leftMembership.getAccountId()).isEqualTo("00000000-0000-0000-0000-000000000123"); + assertThat(leftMembership.getAccountId()).isEqualTo(PLAYER_ACCOUNT_ID); assertThat(leftMembership.getTenantId()).isEqualTo("00000000-0000-0000-0000-000000000022"); - assertThat(leftMembership.getRequestAccountId()).isEqualTo("123"); + assertThat(leftMembership.getRequestAccountId()).isEqualTo(PLAYER_ACCOUNT_ID); assertThat(leftMembership.getRequestTenantId()).isEqualTo("22"); assertThat(leftMembership.getMembershipVersionMap()) .containsExactly(Map.entry(leftMembership.getTenantId(), "3")); @@ -3305,7 +3803,8 @@ void playLeftMembershipRequiresJoinForPublicProduction() { @Test void playPrivateDeniedReturnsPrivacyOutcomeBeforeCharacterRosterLookup() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3315,7 +3814,7 @@ void playPrivateDeniedReturnsPrivacyOutcomeBeforeCharacterRosterLookup() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "4")), + .inactive(PLAYER_ACCOUNT_ID, 22L, "4")), invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -3339,11 +3838,12 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { @Test void playPublicAdmissionDeniedWhenFreshEntitlementsDisallowJoin() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 0L, null, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "demo", 0L, null, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubMembershipResponses( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L)); + PLAYER_ACCOUNT_ID, 22L)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(false)); @@ -3364,7 +3864,8 @@ void playPublicAdmissionDeniedWhenFreshEntitlementsDisallowJoin() { @ValueSource(strings = {"outage", "malformed", "stale"}) void playPublicJoinRequiresFreshEntitlementEvidence(String evidence) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 0L, null, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "demo", 0L, null, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3374,7 +3875,7 @@ void playPublicJoinRequiresFreshEntitlementEvidence(String evidence) { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing(PLAYER_ACCOUNT_ID, 22L)), invocation.getArgument(0))); GetTenantEntitlementsForRuntimeResponse entitlementResponse; if ("outage".equals(evidence)) { @@ -3415,11 +3916,20 @@ void playPublicJoinRequiresFreshEntitlementEvidence(String evidence) { @Test void playBoundLeftMembershipRequiresJoinAndClearsBindingForPublicProduction() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3501,7 +4011,8 @@ void playAuthorityFreshnessUsesInjectedClockAtExactInclusiveBoundaries() { authorityNow.minusSeconds(15).minusNanos(1).toString(), authorityNow.plusNanos(1).toString()); SessionContext unboundContext = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")) .thenReturn(Optional.of(unboundContext)); @@ -3591,7 +4102,15 @@ void playAuthorityFreshnessUsesInjectedClockAtExactInclusiveBoundaries() { @ValueSource(strings = {"ENTITLEMENT_UNAVAILABLE", "AUTH_UNAVAILABLE"}) void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3601,7 +4120,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -3629,7 +4148,15 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { @Test void playBillingDenialMasksMissingPublicMembership() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -3657,11 +4184,19 @@ void playBillingDenialMasksMissingPublicMembership() { @Test void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubMembershipResponses( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L)); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -3695,7 +4230,15 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { @Test void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", @@ -3722,7 +4265,15 @@ void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { @Test void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEntityCalls() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3732,7 +4283,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -3763,7 +4314,16 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti @ValueSource(strings = {"malformed", "future", "stale"}) void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3772,7 +4332,7 @@ void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")) + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")) .toBuilder() .setEvaluatedAt( switch (defect) { @@ -3804,7 +4364,16 @@ void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { @Test void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3815,7 +4384,8 @@ void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support - .RuntimeMembershipTestFixtures.active(123L, 22L, "1")), + .RuntimeMembershipTestFixtures.active( + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), invocation.getArgument(0)); return response.toBuilder().setRequestId("wrong-request-id").build(); }); @@ -3847,10 +4417,11 @@ void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { }) void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); GetTenantMembershipForRuntimeResponse.Builder response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 123L, 22L, "1") + PLAYER_ACCOUNT_ID, 22L, "1") .toBuilder(); switch (invalidEvidence) { case "stale" -> response.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); @@ -3898,7 +4469,8 @@ void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { @ValueSource(strings = {"stale", "future", "wrong-tenant", "missing-version", "missing-sequence"}) void playRejectsInvalidEntitlementAuthority(String invalidEvidence) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); GetTenantEntitlementsForRuntimeResponse.Builder response = GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId("22") @@ -3936,7 +4508,7 @@ void playRejectsInvalidPositiveGrantAuthority(String invalidEvidence) { when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); GetRealmAccessGrantForRuntimeResponse.Builder grant = GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(PLAYER_ACCOUNT_ID) .setTenantId("22") .setWorldSlug("sandbox") .setRealmSlug("preview") @@ -3970,7 +4542,16 @@ void playRejectsInvalidPositiveGrantAuthority(String invalidEvidence) { @Test void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3981,7 +4562,8 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support - .RuntimeMembershipTestFixtures.active(123L, 22L, "1")), + .RuntimeMembershipTestFixtures.active( + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), invocation.getArgument(0)); return response.toBuilder().clearMembershipAuthorityGeneration().build(); }); @@ -4001,7 +4583,8 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { @Test void playWhenMembershipAuthorityTupleHasUnknownFieldsIsDeniedBeforeAdmission() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4010,7 +4593,7 @@ void playWhenMembershipAuthorityTupleHasUnknownFieldsIsDeniedBeforeAdmission() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active(PLAYER_ACCOUNT_ID, 22L, "1")); var tupleWithUnknownField = response.getAuthorityTuple().toBuilder() .setUnknownFields( @@ -4042,7 +4625,16 @@ void playWhenMembershipAuthorityTupleHasUnknownFieldsIsDeniedBeforeAdmission() { @Test void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4051,7 +4643,7 @@ void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); String changedCanonicalJson = resealWithMembershipVersion( response.getOutboxSourceEvidence(0).getCanonicalEventJson(), "2"); @@ -4085,7 +4677,16 @@ void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { @Test void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4094,7 +4695,7 @@ void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); String changedCanonicalJson = changeCanonicalEventWithoutResealing( response.getOutboxSourceEvidence(0).getCanonicalEventJson()); @@ -4128,7 +4729,16 @@ void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { @Test void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4137,7 +4747,7 @@ void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); var source = response.getOutboxSourceEvidence(0).toBuilder().clearCanonicalEventJson(); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures @@ -4173,7 +4783,16 @@ void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { @Test void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4182,7 +4801,7 @@ void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); var mismatchedResponse = response.toBuilder() .putMembershipVersion("00000000-0000-0000-0000-000000000022", "2") @@ -4219,7 +4838,15 @@ void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { @ValueSource(strings = {"target", "version", "stale", "future", "malformed"}) void unsafeEntitlementSnapshotFailsClosed(String defect) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); String tenantId = "target".equals(defect) ? "23" : "22"; long entitlementVersion = "version".equals(defect) ? 0L : 1L; @@ -4258,7 +4885,16 @@ void unsafeEntitlementSnapshotFailsClosed(String defect) { @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -4287,7 +4923,16 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { @Test void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -4318,7 +4963,16 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { @Test void playWhenMembershipAuthorityUnavailableFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4361,7 +5015,16 @@ void playWhenMembershipAuthorityUnavailableFailsClosed() { void playRequiresExplicitAvailableMembershipAuthorityBeforePublicOutcomes( String lifecycle, String availability) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4371,13 +5034,13 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforePublicOutcomes( switch (lifecycle) { case "ACTIVE" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1"); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1"); case "MISSING" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L); + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L); case "INACTIVE" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3"); + .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3"); default -> throw new IllegalArgumentException("Unexpected lifecycle: " + lifecycle); }; @@ -4424,9 +5087,9 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforeNonPublicOutcome( var membership = "MISSING".equals(lifecycle) ? net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L) + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L) : net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3"); + .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3"); var builder = freshMembership(membership).toBuilder(); if (!"ABSENT".equals(availability)) { builder.setAuthorityAvailability(availability); @@ -4456,17 +5119,28 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforeNonPublicOutcome( scriptEventPublisher); } - @Test - void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { + @ParameterizedTest + @ValueSource( + strings = {GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE, "FAILED_PRECONDITION"}) + void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding(String errorCode) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE) + .setCode(errorCode) .setMessage(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_MESSAGE)) .build()); @@ -4484,15 +5158,49 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { Mockito.verify(gameplayPresenceLifecycleService, Mockito.never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); + Mockito.verify(entityManagementClient, Mockito.never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); } @Test void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { + SessionContext context = + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + } + + @Test + void staleRoomContextFallsBackToFreshEntry() { SessionContext context = new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -4520,7 +5228,7 @@ void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -4543,13 +5251,14 @@ void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { .isEqualTo(1.0); Mockito.verify(sessionAuthenticationService).resolveByGameplayIdentity(22L, 1L, 7001L); Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -4568,7 +5277,7 @@ void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -4591,7 +5300,7 @@ void roomlessRetainedActorMissingFromRosterCannotBeSilentlyReplaced() { new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -4626,7 +5335,7 @@ void roomlessRetainedActorMayChangeThroughExplicitCharacterSelection() { new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -4662,7 +5371,7 @@ void roomlessRetainedActorMayChangeThroughExplicitCharacterSelection() { new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7002L, "Sora", @@ -4735,7 +5444,7 @@ private static GetTenantMembershipForRuntimeResponse freshMembership( private static GetTenantMembershipForRuntimeResponse leftMembershipWithDefect(String defect) { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player")); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player")); var builder = response.toBuilder(); switch (defect) { case "membership-generation" -> { @@ -4785,6 +5494,13 @@ private void assertIdentityUnavailableWithoutMutation(PlayCommandHandlingResult .publishSpawnEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); } + private void stubOwnedRoster( + String gameInstanceId, PlayableStateScope scope, Character... characters) { + Mockito.doReturn(roster(characters)) + .when(entityManagementClient) + .listCharactersByAccount("22", PLAYER_ACCOUNT_ID, gameInstanceId, scope); + } + private PlayCommandHandler handlerWithClock(Clock clock) { return handlerWithClock(clock, connectScopeSessionStore); } @@ -4810,7 +5526,7 @@ private PlayCommandHandler handlerWithClock( private static GetTenantMembershipForRuntimeResponse missingMembershipAt(String evaluatedAt) { return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L) + PLAYER_ACCOUNT_ID, 22L) .toBuilder() .setEvaluatedAt(evaluatedAt) .build(); @@ -4818,7 +5534,7 @@ private static GetTenantMembershipForRuntimeResponse missingMembershipAt(String private static GetTenantMembershipForRuntimeResponse activeMembershipAt(String evaluatedAt) { return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 123L, 22L, "1") + PLAYER_ACCOUNT_ID, 22L, "1") .toBuilder() .setEvaluatedAt(evaluatedAt) .build(); @@ -4845,7 +5561,7 @@ private void stubMembershipResponses(GetTenantMembershipForRuntimeResponse... re } private static GetRealmAccessGrantForRuntimeResponse validGrant() { - return validGrant("123", "22", "sandbox", "preview"); + return validGrant(PLAYER_ACCOUNT_ID, "22", "sandbox", "preview"); } private static GetRealmAccessGrantForRuntimeResponse validGrant( @@ -4920,14 +5636,15 @@ private void assertHiddenRealmDenialMatchesUnknownSelection( } private SessionContext loggedInUnboundContext() { - return new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + return new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); } private SessionContext previewRealmContext() { return new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "Emberline", @@ -4946,7 +5663,7 @@ private SessionContext unboundContext() { return new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 0L, null, @@ -4974,7 +5691,7 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -4993,9 +5710,9 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi var membershipResponse = "MISSING".equals(lifecycleState) ? net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.missing( - 123L, 22L) + PLAYER_ACCOUNT_ID, 22L) : net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.inactive( - 123L, 22L, Long.toString(membershipVersion)); + PLAYER_ACCOUNT_ID, 22L, Long.toString(membershipVersion)); Mockito.doAnswer( invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures @@ -5083,7 +5800,7 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi SessionContext resolvedContext = realSessionAuthenticationService.resolveSessionContext("1").orElseThrow(); assertThat(resolvedContext).isEqualTo(savedContext); - assertThat(resolvedContext.accountId()).isEqualTo(123L); + assertThat(resolvedContext.accountId()).isEqualTo(PLAYER_ACCOUNT_ID); Mockito.verify(sessionContextService, Mockito.times(1)).save(Mockito.any()); String exactJoinScopeId = "account-issued-join-scope"; @@ -5122,7 +5839,7 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi requestIdCaptor.capture(), Mockito.any(Instant.class)); assertThat(scopeIdCaptor.getValue()).isEqualTo(exactJoinScopeId); - assertThat(playerContextCaptor.getValue().getAccountId()).isEqualTo("123"); + assertThat(playerContextCaptor.getValue().getAccountId()).isEqualTo(PLAYER_ACCOUNT_ID); assertThat(playerContextCaptor.getValue().getSessionId()).isEqualTo("1"); assertThat(playerContextCaptor.getValue().getTenantId()).isEqualTo("22"); assertThat(playerContextCaptor.getValue().getRequestId()).isEqualTo(requestIdCaptor.getValue()); @@ -5237,7 +5954,7 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -5257,7 +5974,7 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 23L, "2")), + .inactive(PLAYER_ACCOUNT_ID, 23L, "2")), invocation.getArgument(0))) .when(accountClient) .getTenantMembershipForRuntime( @@ -5291,12 +6008,14 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { @Test void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "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); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle( @@ -5318,22 +6037,24 @@ void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { order .verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); order .verify(entityManagementClient) - .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - stubOwnedRoster( + stubOwnedRosterForGameInstanceTenant( "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), @@ -5349,7 +6070,8 @@ void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { @Test void playRejectsAnotherAccountsActorEvenWhenNameMatches() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "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) @@ -5358,7 +6080,8 @@ void playRejectsAnotherAccountsActorEvenWhenNameMatches() { .build(); Mockito.doReturn(roster(foreign)) .when(entityManagementClient) - .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle( @@ -5374,9 +6097,10 @@ void playRejectsAnotherAccountsActorEvenWhenNameMatches() { @Test void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - stubOwnedRoster("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + stubOwnedRosterForGameInstanceTenant("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -5392,7 +6116,8 @@ void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { @ValueSource(strings = {"tenant", "scope"}) void playRejectsRosterRowsOutsideSelectedTenantOrScope(String mismatch) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "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 = @@ -5401,7 +6126,8 @@ void playRejectsRosterRowsOutsideSelectedTenantOrScope(String mismatch) { : valid.toBuilder() .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .build(); - stubOwnedRoster("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, mismatched); + stubOwnedRosterForGameInstanceTenant( + "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, mismatched); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -5415,7 +6141,7 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -5429,7 +6155,7 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { 1L, "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - stubOwnedRoster( + stubOwnedRosterForGameInstanceTenant( "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); @@ -5439,7 +6165,8 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { assertIdentityUnavailableWithoutMutation(result); Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); Mockito.verify(sessionAuthenticationService, never()) @@ -5452,7 +6179,7 @@ void playEntitlementCallerTargetPreconditionPreservesExistingBinding() { new SessionContext( 1L, 22L, - 123L, + PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "Emberline", @@ -5489,7 +6216,7 @@ void playEntitlementCallerTargetPreconditionPreservesExistingBinding() { .isEqualTo("error.play.entitlement-unavailable"); assertThat(context.hasGameplayBinding()).isTrue(); assertThat(context.tenantId()).isEqualTo(22L); - assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.accountId()).isEqualTo(PLAYER_ACCOUNT_ID); assertThat(context.characterId()).isEqualTo(123L); assertThat(context.gameInstanceId()).isEqualTo(1L); assertThat(context.worldSlug()).isEqualTo("demo"); @@ -5512,7 +6239,7 @@ void playEntitlementCallerTargetPreconditionPreservesExistingBinding() { Mockito.anyString(), Mockito.any(PlayableStateScope.class)); Mockito.verify(moderationPolicyClient, never()) - .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong()); + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); Mockito.verify(accountClient, never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -5523,12 +6250,12 @@ void playEntitlementCallerTargetPreconditionPreservesExistingBinding() { Mockito.verifyNoInteractions(scriptEventPublisher); } - private void stubOwnedRoster( + private void stubOwnedRosterForGameInstanceTenant( String gameInstanceId, PlayableStateScope scope, Character... characters) { Mockito.doReturn(roster(characters)) .when(entityManagementClient) .listCharactersByAccount( - tenantForGameInstance(gameInstanceId), "123", gameInstanceId, scope); + tenantForGameInstance(gameInstanceId), PLAYER_ACCOUNT_ID, gameInstanceId, scope); } private static ListCharactersByAccountResponse roster(Character... characters) { @@ -5546,7 +6273,7 @@ private static Character actorForTenant( return Character.newBuilder() .setId(id) .setTenantId(tenantId) - .setAccountId("123") + .setAccountId(PLAYER_ACCOUNT_ID) .setName(name) .setPlayableStateScope(scope) .build(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java index d70f74a2b9..0da523d2c8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java @@ -27,7 +27,9 @@ void doesNotRecordHistoryDisplayCommands() { Mockito.mock(PlayerCommandHistoryStorageService.class); SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); - SessionContext context = new SessionContext(1L, 7L, 9L, 17L, 11L, "R-1", "token"); + SessionContext context = + new SessionContext( + 1L, 7L, "3a16e242-3467-4d98-906f-71d47b888b5e", 17L, 11L, "R-1", "token"); List storedCommands = new ArrayList<>(List.of("LOOK")); when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); when(storage.findRecent(7L, 11L, 17L, 10)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java index 5b76eb52ba..d542c3d86d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java @@ -239,6 +239,7 @@ void quarantinesCapabilityResolutionFailure() { } private SessionContext gameplayContext(long characterId) { - return new SessionContext(1L, 7L, 9L, characterId, 11L, "R-1", "token"); + return new SessionContext( + 1L, 7L, "11111111-1111-4111-8111-111111111111", characterId, 11L, "R-1", "token"); } } 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 6e5d31ce4e..56a84d704f 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 @@ -170,14 +170,17 @@ void setUp() { .thenReturn(CommandEnqueueResult.success()); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken("jwt") + .setAccountId("550e8400-e29b-41d4-a716-446655440000") + .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 77L, 22L, "1") + "550e8400-e29b-41d4-a716-446655440000", 22L, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -191,7 +194,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -217,7 +220,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("77") + .setAccountId("550e8400-e29b-41d4-a716-446655440000") .setName("Emberline") .setLevel(12) .setPlayableStateScope( @@ -488,21 +491,28 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( - invocation -> - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .echoRequestId( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(77L, 22L, "2"), - invocation.getArgument(0))); + invocation -> { + var response = + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( + "550e8400-e29b-41d4-a716-446655440000", 22L, List.of("player")); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(response, invocation.getArgument(0)); + }); TextCommandInterpretationResult secondLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); assertTrue(secondLogin.commandResult().accepted()); SessionContext authenticatedContextBeforeDeniedPlay = sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow(); - assertEquals(77L, authenticatedContextBeforeDeniedPlay.accountId()); + assertEquals( + "550e8400-e29b-41d4-a716-446655440000", authenticatedContextBeforeDeniedPlay.accountId()); + assertTrue(authenticatedContextBeforeDeniedPlay.hasAccountIdentity()); assertEquals("demo@example.com", authenticatedContextBeforeDeniedPlay.loginName()); assertEquals("jwt", authenticatedContextBeforeDeniedPlay.jwt()); assertTrue(authenticatedContextBeforeDeniedPlay.hasGameplayRegionBinding()); + assertEquals(1L, authenticatedContextBeforeDeniedPlay.bootstrapGameInstanceId()); + assertEquals("demo", authenticatedContextBeforeDeniedPlay.worldSlug()); + assertEquals("production", authenticatedContextBeforeDeniedPlay.realmSlug()); + assertEquals(1L, authenticatedContextBeforeDeniedPlay.pointerVersion()); TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertFalse(deniedPlay.commandResult().accepted()); @@ -515,6 +525,11 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { assertEquals( authenticatedContextBeforeDeniedPlay.loginName(), authenticatedLobbyContext.loginName()); assertEquals(authenticatedContextBeforeDeniedPlay.jwt(), authenticatedLobbyContext.jwt()); + assertTrue(authenticatedLobbyContext.hasAccountIdentity()); + assertEquals(1L, authenticatedLobbyContext.bootstrapGameInstanceId()); + assertEquals("demo", authenticatedLobbyContext.worldSlug()); + assertEquals("production", authenticatedLobbyContext.realmSlug()); + assertEquals(1L, authenticatedLobbyContext.pointerVersion()); assertEquals(0L, authenticatedLobbyContext.gameInstanceId()); assertEquals(0L, authenticatedLobbyContext.characterId()); assertNull(authenticatedLobbyContext.characterName()); @@ -531,6 +546,34 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { interpreter.interpret("1", LOOK_PAYLOAD, false); assertFalse(lookAfterDeniedReconnect.commandResult().accepted()); assertEquals("PLAY_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); + assertTrue(sessionAuthenticationService.isAuthenticated("1")); + assertEquals( + "550e8400-e29b-41d4-a716-446655440000", + sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow().accountId()); + SessionContext lobbyContextBeforeDeniedJoin = + sessionAuthenticationService.resolveSessionContext("1").orElseThrow(); + Mockito.clearInvocations(accountClient, moderationPolicyClient, entityManagementClient); + TextCommandInterpretationResult joinAfterDeniedPlay = + interpreter.interpret("1", "JOIN demo", false); + assertFalse(joinAfterDeniedPlay.commandResult().accepted()); + assertEquals("CONNECT_SCOPE_MISMATCH", joinAfterDeniedPlay.commandResult().errorCode()); + assertEquals( + lobbyContextBeforeDeniedJoin, + sessionAuthenticationService.resolveSessionContext("1").orElseThrow()); + assertFalse( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(presence -> presence.sessionId() == 1L)); + Mockito.verify(accountClient, Mockito.never()) + .joinPublicProductionMembership( + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class)); + Mockito.verify(moderationPolicyClient, Mockito.never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); + Mockito.verify(entityManagementClient, Mockito.never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.class)); } @Test @@ -683,7 +726,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, @@ -788,17 +831,17 @@ private boolean hasGameplayIdentity(SessionContext context) { void reconnectDoesNotRestoreElevationFromPriorTenantRoleClaims() { String tenantAdminJwt = gameplayJwtUtil.generateToken( - "77", + "550e8400-e29b-41d4-a716-446655440000", Map.of( "accountId", - "77", + "550e8400-e29b-41d4-a716-446655440000", "scopedRoles", Map.of("22", List.of("tenantAdmin", "moderator")))); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken(tenantAdminJwt) - .setAccountId("77") + .setAccountId("550e8400-e29b-41d4-a716-446655440000") .build()); assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); @@ -821,12 +864,17 @@ void reconnectDoesNotRestoreElevationFromPriorTenantRoleClaims() { void unavailableAccountAdmissionEvidenceDoesNotElevateReconnectPresence() { String tenantAdminJwt = gameplayJwtUtil.generateToken( - "77", Map.of("accountId", "77", "scopedRoles", Map.of("22", List.of("tenantAdmin")))); + "550e8400-e29b-41d4-a716-446655440000", + Map.of( + "accountId", + "550e8400-e29b-41d4-a716-446655440000", + "scopedRoles", + Map.of("22", List.of("tenantAdmin")))); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken(tenantAdminJwt) - .setAccountId("77") + .setAccountId("550e8400-e29b-41d4-a716-446655440000") .build()); assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java index 2cc4258542..37d1bc8d9f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java @@ -23,7 +23,15 @@ class StatusCommandHandlerTest { new StatusCommandHandler(gameLogicClient, scriptEventPublisher); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void statusProjectsEvaluatedResourcesAndVisibleConditionsInStableOrder() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java index 66cd161139..f525dac286 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java @@ -29,7 +29,15 @@ void rejectsDisabledStandardOptionalCommandsBeforeDispatch( TextCommandDispatcher dispatcher = Mockito.mock(TextCommandDispatcher.class); SessionContext gameplayContext = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); when(sessionAuthenticationService.resolveSessionContext("41")) .thenReturn(Optional.of(gameplayContext)); TextCommandInterpreter interpreter = @@ -62,7 +70,15 @@ void failsClosedWhenCapabilityResolutionIsUnavailable() { Mockito.mock(EffectiveCommandCapabilitiesSettingsResolver.class); SessionContext gameplayContext = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); when(sessionAuthenticationService.resolveSessionContext("41")) .thenReturn(Optional.of(gameplayContext)); when(capabilitiesResolver.isEnabled(PlayerCommandCapability.SOCIAL, 22L, 7L)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java index c227399313..26db5eb219 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java @@ -23,7 +23,17 @@ void interpretUsesRegistryAndDispatcherInsteadOfCommandTypeBranches() { Mockito.mock(SessionAuthenticationService.class); SessionContext gameplayContext = new SessionContext( - 1L, 7L, 8L, "player@example.com", 9L, "Demo", 10L, "R-1", "token", "en-NZ", 10L); + 1L, + 7L, + "e87d27af-9f41-4575-915d-d76d1a5359c9", + "player@example.com", + 9L, + "Demo", + 10L, + "R-1", + "token", + "en-NZ", + 10L); Mockito.when(authenticationService.resolveSessionContext("1")) .thenReturn(Optional.of(gameplayContext)); 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 84df150688..54927a2737 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 @@ -90,6 +90,7 @@ @SuppressWarnings("unchecked") class TextCommandInterpreterTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private static final String PLAY_DEMO_PRODUCTION = "PLAY demo production"; private final CommandService commandService = Mockito.mock(CommandService.class); @@ -165,7 +166,7 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("auth-token") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .build()); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( @@ -182,7 +183,7 @@ void setUp() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 123L, 22L, "1") + ACCOUNT_ID, 22L, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -196,7 +197,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -419,15 +420,15 @@ void setUp() { lookCacheService, new TextPlayerOutputRenderer(new PresentationProperties())); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse.newBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("123") - .setName("demo") + .setAccountId(ACCOUNT_ID) + .setName("Emberline") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) @@ -539,7 +540,7 @@ void logoutAliasDispatchesBeforeStaleBindingNormalization() { new SessionContext( 1L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -632,7 +633,7 @@ void whoAfterPlayShowsCurrentPlayerList() { assertTrue(interpretation.commandResult().accepted()); assertEquals( - "OK WHO\nGods [0]: \nPlayers [1]: demo\n\n" + "demo> ", + "OK WHO\nGods [0]: \nPlayers [1]: Emberline\n\n" + "Emberline> ", renderedResponse("WHO", interpretation)); assertFalse(interpretation.meaningfulGameplayActivity()); } @@ -659,7 +660,7 @@ void inventoryIsVisibleAfterPlay() { List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); assertEquals( - "OK INVENTORY\n" + "Inventory:\n" + "- Torch x2 (A small torch)\n\n" + "demo> ", + "OK INVENTORY\n" + "Inventory:\n" + "- Torch x2 (A small torch)\n\n" + "Emberline> ", renderedResponse("INVENTORY", interpretation)); assertTrue(interpretation.meaningfulGameplayActivity()); } @@ -686,7 +687,7 @@ void equipmentIsVisibleAfterPlay() { List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); assertEquals( - "OK EQUIPMENT\n" + "Equipment:\n" + "- HEAD: Torch (A small torch)\n\n" + "demo> ", + "OK EQUIPMENT\n" + "Equipment:\n" + "- HEAD: Torch (A small torch)\n\n" + "Emberline> ", renderedResponse("EQ", interpretation)); } @@ -738,7 +739,7 @@ void wearAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("WEAR Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("WEAR Torch", interpretation)); verify(commandService).enqueue("1", "WEAR Torch", false); verify(gameLogicClient, never()) .wearEquipment(Mockito.any(SessionContext.class), Mockito.anyString(), Mockito.anyString()); @@ -756,7 +757,7 @@ void removeAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("REMOVE Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("REMOVE Torch", interpretation)); verify(commandService).enqueue("1", "REMOVE Torch", false); verify(gameLogicClient, never()) .removeEquipment(Mockito.any(SessionContext.class), Mockito.anyString()); @@ -773,7 +774,7 @@ void getAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("GET Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("GET Torch", interpretation)); verify(commandService).enqueue("1", "GET Torch", false); verify(gameLogicClient, never()) .pickupItemFromRoom( @@ -798,7 +799,7 @@ void dropAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("DROP Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("DROP Torch", interpretation)); verify(commandService).enqueue("1", "DROP Torch", false); verify(gameLogicClient, never()) .dropItemToRoom( @@ -823,7 +824,7 @@ void putAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("PUT Ration INTO Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("PUT Ration INTO Torch", interpretation)); verify(commandService).enqueue("1", "PUT Ration INTO Torch", false); verify(gameLogicClient, never()) .putItemIntoContainer( @@ -847,7 +848,7 @@ void takeAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("TAKE Ration FROM Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("TAKE Ration FROM Torch", interpretation)); verify(commandService).enqueue("1", "TAKE Ration FROM Torch", false); verify(gameLogicClient, never()) .takeItemFromContainer( @@ -862,7 +863,7 @@ void takeAfterPlayEnqueuesDurableMutation() { @Test void bootstrapContextWithoutAuthenticatedAccountStillRequiresLogin() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(55L, 22L, 0L, null, 0L, null, 77L, null, null)); + .save(new SessionContext(55L, 22L, null, null, 0L, null, 77L, null, null)); TextCommandInterpretationResult interpretation = interpreter.interpret("55", "LOOK", false); @@ -899,7 +900,9 @@ void gameplayAfterLoginBeforePlayReturnsPlayRequired() { @Test void gameplayWithRoomOnlyPartialShellStillReturnsPlayRequired() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(56L, 22L, 123L, "demo@example.com", 0L, null, 0L, "R-7", null)); + .save( + new SessionContext( + 56L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "R-7", null)); TextCommandInterpretationResult interpretation = interpreter.interpret("56", "LOOK", false); @@ -935,7 +938,7 @@ void lookAfterPlayAppendsPromptOutput() { LookViewOutput payload = (LookViewOutput) look.outputs().get(0).payload(); assertEquals("Login Hall", payload.roomName()); assertTrue(payload.includeLongDescription()); - assertEquals("demo> ", look.outputs().get(1).text()); + assertEquals("Emberline> ", look.outputs().get(1).text()); } @Test @@ -952,7 +955,7 @@ void quickLookAfterPlayUsesShortVariantAndAppendsPrompt() { LookViewOutput payload = (LookViewOutput) quickLook.outputs().get(0).payload(); assertEquals("Login Hall", payload.roomName()); assertFalse(payload.includeLongDescription()); - assertEquals("demo> ", quickLook.outputs().get(1).text()); + assertEquals("Emberline> ", quickLook.outputs().get(1).text()); } @Test @@ -1026,7 +1029,7 @@ void loginPlayAndLookFlowWorks() { assertTrue(login.commandResult().accepted()); assertTrue(play.commandResult().accepted()); assertEquals( - "OK PLAY Entered world: demo as demo\ndemo> ", + "OK PLAY Entered world: demo as Emberline\nEmberline> ", renderedResponse(PLAY_DEMO_PRODUCTION, play)); assertTrue(look.commandResult().accepted()); assertEquals( @@ -1072,7 +1075,7 @@ void moveAfterPlayReturnsStructuredViewAndPrompt() { assertTrue(interpretation.commandResult().accepted()); assertEquals(1, interpretation.outputs().size()); assertEquals(PlayerOutputKind.PROMPT, interpretation.outputs().get(0).kind()); - assertEquals("demo> ", interpretation.outputs().get(0).text()); + assertEquals("Emberline> ", interpretation.outputs().get(0).text()); verify(commandService).enqueue("1", "MOVE north", false); } @@ -1151,7 +1154,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, 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 b71afb5e05..3db826b2d8 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 @@ -33,7 +33,16 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "who"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [0]: "); @@ -55,32 +64,79 @@ void whoKeepsTenantRoleClaimsInThePlayerListWithoutGrantEvidence() { new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); String godJwt = jwtUtil.generateToken( - "1", + "11111111-1111-4111-8111-111111111111", java.util.Map.of( - "accountId", "1", "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); + "accountId", + "11111111-1111-4111-8111-111111111111", + "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)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "god@example.com", + 101L, + "Aster", + 7L, + "R-1", + godJwt)); String moderatorJwt = jwtUtil.generateToken( - "4", + "89ce29d0-212d-4769-892a-67299d123e17", java.util.Map.of( "accountId", - "4", + "89ce29d0-212d-4769-892a-67299d123e17", "scopedRoles", java.util.Map.of("22", java.util.List.of("moderator")))); gameplayPresenceService.registerConnected( new SessionContext( - 4L, 22L, 4L, "moderator@example.com", 104L, "Dara", 7L, "R-1", moderatorJwt)); + 4L, + 22L, + "89ce29d0-212d-4769-892a-67299d123e17", + "moderator@example.com", + 104L, + "Dara", + 7L, + "R-1", + moderatorJwt)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); gameplayPresenceService.registerConnected( - new SessionContext(3L, 22L, 3L, "third@example.com", 103L, "Cara", 7L, "R-1", null)); + new SessionContext( + 3L, + 22L, + "33333333-3333-4333-8333-333333333333", + "third@example.com", + 103L, + "Cara", + 7L, + "R-1", + null)); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [4]: Aster, Ben, Cara, Dara"); @@ -93,21 +149,38 @@ void whoShowsGlobalOnlyRolesAsPlayers() { new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); String globalOnlyJwt = jwtUtil.generateToken( - "1", + "c91fb96e-5ad8-4e4e-a12d-2838640093b2", java.util.Map.of( "accountId", - "1", + "c91fb96e-5ad8-4e4e-a12d-2838640093b2", "globalRoles", java.util.List.of("platformAdmin", "support", "billingAdmin", "god", "moderator"))); gameplayPresenceService.registerConnected( new SessionContext( - 1L, 22L, 1L, "staff@example.com", 101L, "Aster", 7L, "R-1", globalOnlyJwt)); + 1L, + 22L, + "c91fb96e-5ad8-4e4e-a12d-2838640093b2", + "staff@example.com", + 101L, + "Aster", + 7L, + "R-1", + globalOnlyJwt)); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [1]: Aster"); @@ -120,15 +193,42 @@ void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "first@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "first@example.com", + 101L, + "Aster", + 7L, + "R-1", + null)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); gameplayPresenceService.removeBySessionId(1L); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [1]: Ben"); @@ -143,9 +243,27 @@ void whoAnnotatesExplicitAndAutoAfkPlayers() { new WhoCommandHandler(gameplayPresenceService, resolver, scriptEventPublisher); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "active@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "active@example.com", + 101L, + "Aster", + 7L, + "R-1", + null)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "idle@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "idle@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); when(resolver.resolve(gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow())) .thenReturn(GameplayPresenceActivityState.ACTIVE); when(resolver.resolve(gameplayPresenceService.findConnectedBySessionId(2L).orElseThrow())) @@ -154,7 +272,16 @@ void whoAnnotatesExplicitAndAutoAfkPlayers() { TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(1L, 22L, 1L, "active@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "active@example.com", + 101L, + "Aster", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) 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 b84b784aa7..bc6e1d8497 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 @@ -34,6 +34,7 @@ import org.mockito.Mockito; class WorldsCommandHandlerTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final UUID ADMISSION_REALM_ID = UUID.fromString("00000000-0000-0000-0000-000000000001"); private static final UUID ADMISSION_NAMESPACE_ID = @@ -631,7 +632,7 @@ void browseCharactersFailsClosedForPublicRealmBeforeRosterPolicyProof() { WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt"); assertThat(localHandler.browseRealms(session, "demo")) .isInstanceOfSatisfying( WorldsCommandHandler.RealmBrowseResult.Success.class, @@ -678,7 +679,7 @@ void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt"); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(session, "demo", "production"); @@ -702,7 +703,7 @@ void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt"), "demo", "production"); @@ -802,7 +803,7 @@ void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEnt AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( accountClient.getTenantMembershipForRuntime(Mockito.any(PlayerExecutionContext.class))) - .thenReturn(RuntimeMembershipTestFixtures.missing(123L, 22L)); + .thenReturn(RuntimeMembershipTestFixtures.missing(ACCOUNT_ID, 22L)); Mockito.when( accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(false)); @@ -823,7 +824,7 @@ void browseCharactersDoesNotDispatchForUnavailableEntitlement() { AccountClient accountClient = Mockito.mock(AccountClient.class); Mockito.when( accountClient.getTenantMembershipForRuntime(Mockito.any(PlayerExecutionContext.class))) - .thenReturn(RuntimeMembershipTestFixtures.missing(123L, 22L)); + .thenReturn(RuntimeMembershipTestFixtures.missing(ACCOUNT_ID, 22L)); Mockito.when( accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -2174,11 +2175,11 @@ private void addPublicProductionAuthority(GameplayCatalogProperties properties) } private SessionContext authenticatedSession() { - return new SessionContext(7L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + return new SessionContext(7L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt"); } private GetTenantMembershipForRuntimeResponse activeMembership() { - return RuntimeMembershipTestFixtures.active(123L, 22L, "1"); + return RuntimeMembershipTestFixtures.active(ACCOUNT_ID, 22L, "1"); } private GetTenantMembershipForRuntimeResponse publicMembership( @@ -2188,7 +2189,7 @@ private GetTenantMembershipForRuntimeResponse publicMembership( long membershipAuthorityGeneration, String lifecycleState) { return RuntimeMembershipTestFixtures.incomplete( - 123L, + ACCOUNT_ID, 22L, membershipExists, lifecycleState, @@ -2214,7 +2215,7 @@ private GetTenantEntitlementsForRuntimeResponse publicEntitlement(boolean allowP private GetRealmAccessGrantForRuntimeResponse grant( String worldSlug, String realmSlug, boolean granted) { return GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setWorldSlug(worldSlug) .setRealmSlug(realmSlug) @@ -2349,7 +2350,15 @@ void charsPrivateOnlyWorldFailsBeforeEntityRead() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt"), "private-world", null); @@ -2396,7 +2405,7 @@ void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { Mockito.mock(AccountClient.class), DirectTextConnectScopeSessionStore.inMemoryForTest()); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt"); assertThat(localHandler.browseCharacters(context, "mixed-world", "secret")) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); @@ -2459,7 +2468,15 @@ void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { WorldsCommandHandler.CharacterBrowseResult result = handler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt"), "demo", "production"); 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 f80f038655..eb1e76554b 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 @@ -35,6 +35,10 @@ import org.mockito.Mockito; class WorldsTextCommandDispatchHandlerTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT_A_UUID = "d0c68a37-5126-42d2-9506-8df13e97699e"; + private static final String ACCOUNT_B_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = @@ -53,7 +57,15 @@ class WorldsTextCommandDispatchHandlerTest { void publishesCommandEventForGameplayScopedWorldsBrowse() { SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( @@ -180,7 +192,7 @@ void worldsDoesNotTranslateStoreIllegalArgumentExceptionToInvalidArgument() { .when(store) .replaceWorldSnapshot( Mockito.anyLong(), - Mockito.anyLong(), + Mockito.isNull(), Mockito.anyString(), Mockito.anyList(), Mockito.any(Instant.class)); @@ -198,7 +210,7 @@ void worldsDoesNotTranslateStoreIllegalArgumentExceptionToInvalidArgument() { Mockito.verify(store) .replaceWorldSnapshot( Mockito.eq(7L), - Mockito.eq(0L), + Mockito.isNull(), Mockito.anyString(), Mockito.anyList(), Mockito.any(Instant.class)); @@ -245,7 +257,15 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { scriptEventPublisher); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = scopedHandler.handle( @@ -301,7 +321,7 @@ void privateRealmsBrowseDoesNotPublishDespitePositiveLegacyGrant() { Mockito.anyString())) .thenReturn( GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId("41") + .setAccountId(ACCOUNT_A_UUID) .setTenantId("22") .setWorldSlug("sandbox") .setRealmSlug("production") @@ -318,7 +338,7 @@ void privateRealmsBrowseDoesNotPublishDespitePositiveLegacyGrant() { scriptEventPublisher); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, ACCOUNT_A_UUID, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = scopedHandler.handle( @@ -347,7 +367,15 @@ void closesPublicCharsBrowseBeforeAuthorityOrRosterReads() { AccountClient accountClient = Mockito.mock(AccountClient.class); SessionContext context = new SessionContext( - 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( @@ -391,7 +419,7 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { scriptEventPublisher); SessionContext context = new SessionContext( - 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, ACCOUNT_B_UUID, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult unknownRealm = scopedHandler.handle(charsRequest("guessed", context)); @@ -433,7 +461,7 @@ void routesExplicitPublicCharsBrowseToUnavailableBeforeAuthorityOrRosterReads() scriptEventPublisher); SessionContext context = new SessionContext( - 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, ACCOUNT_B_UUID, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = scopedHandler.handle( @@ -517,7 +545,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .setOutcomeCode("CREATED") .build()); SessionContext context = - new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + new SessionContext(7L, 22L, ACCOUNT_ID, "emberline@example.com", 0L, null, 0L, "jwt"); TextCommandInterpretationResult realmsResult = scopedHandler.handle( @@ -574,7 +602,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { org.mockito.ArgumentCaptor.forClass(DirectTextConnectScopeTarget.class); Mockito.verify(accountClient) .issueDirectTextConnectScope(callerCaptor.capture(), targetCaptor.capture()); - assertThat(callerCaptor.getValue().getAccountId()).isEqualTo("41"); + assertThat(callerCaptor.getValue().getAccountId()).isEqualTo(ACCOUNT_ID); assertThat(callerCaptor.getValue().getSessionId()).isEqualTo("7"); assertThat(targetCaptor.getValue().realmId()).isEqualTo(realmId.toString()); assertThat(targetCaptor.getValue().catalogRevision()).isEqualTo(7L); @@ -605,7 +633,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { assertThat(scopeIds.getLast()).isEqualTo(scopeIds.getFirst()); assertThat(scopeIds.get(1)).isEqualTo(scopeIds.getFirst()); assertThat(joinContexts.getFirst().getRequestId()).isEqualTo(requestIds.getFirst()); - assertThat(joinContexts.getFirst().getAccountId()).isEqualTo("41"); + assertThat(joinContexts.getFirst().getAccountId()).isEqualTo(ACCOUNT_ID); assertThat(joinContexts.getFirst().getSessionId()).isEqualTo("7"); assertThat(joinContexts.getFirst().getRealmId()).isEqualTo(realmId.toString()); assertThat(joinContexts.getLast()).isEqualTo(joinContexts.getFirst()); @@ -668,7 +696,7 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { .setOutcomeCode("MEMBERSHIP_RECONCILIATION_REQUIRED") .build()); SessionContext context = - new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + new SessionContext(7L, 22L, ACCOUNT_A_UUID, "emberline@example.com", 0L, null, 0L, "jwt"); scopedHandler.handle( new TextCommandDispatchRequest( @@ -918,7 +946,7 @@ private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); SessionContext context = - new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + new SessionContext(7L, 22L, ACCOUNT_A_UUID, "emberline@example.com", 0L, null, 0L, "jwt"); scopedHandler.handle( new TextCommandDispatchRequest( "7", @@ -988,7 +1016,7 @@ void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { scriptEventPublisher); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, ACCOUNT_A_UUID, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = scopedHandler.handle( @@ -1015,7 +1043,7 @@ void unavailableCharsDoesNotReadRosterOrPublishGameplayEvent() { .setPublicProductionRealm(true); SessionContext context = new SessionContext( - 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, ACCOUNT_B_UUID, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java index e4fa99b3a4..ffe8353637 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java @@ -42,7 +42,15 @@ void resolvesTenantThenGameInstanceCommandHistoryOverrides() { resolved = resolver.resolvedCommandHistory( new SessionContext( - 1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(resolved.effective()).isEqualTo(new FiremudCommandHistoryProperties(20)); assertThat(resolved.sources()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java index 758e1a504e..5e5aab3238 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java @@ -53,7 +53,16 @@ void absentPersistedReconnectionOverrideFallsBackToOperatorDefaults() { FiremudReconnectionProperties effective = resolver.reconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(effective.policy().resumeWindowMs()).isEqualTo(45_000L); assertThat(effective.policy().staleResumeFallsThroughToFreshEntry()).isTrue(); @@ -114,7 +123,16 @@ void disregardsInvalidSparseOverrideAndFallsBackToOperatorDefaultsWithDiagnostic EffectiveReconnectionSettingsResolver.ResolvedValue resolved = resolver.resolvedReconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(resolved.effective().buffer().softMaxBytes()).isEqualTo(16_384); assertThat(resolved.effective().buffer().hardMaxBytes()).isEqualTo(65_536); @@ -159,7 +177,16 @@ void invalidGameInstanceOverrideFallsBackToValidTenantLayer() { EffectiveReconnectionSettingsResolver.ResolvedValue resolved = resolver.resolvedReconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(resolved.effective().buffer().softMaxBytes()).isEqualTo(16_384); assertThat(resolved.effective().buffer().hardMaxBytes()).isEqualTo(80_000); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java index 47f6751780..49519354bf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java @@ -53,7 +53,16 @@ void presentationOverridesMergeTenantThenGameInstance() { PresentationProperties effective = resolver.presentation( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(effective.defaultLocaleTag()).isEqualTo("fr"); assertThat(effective.defaultColorMode()).isEqualTo(PresentationProperties.ColorMode.BASIC); @@ -87,7 +96,18 @@ void movementAndTopologyOverridesResolveAgainstBootstrapGameInstanceBeforePlay() authorityReader); SessionContext prePlay = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, null, null, 41L); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 0L, + null, + 0L, + null, + null, + null, + 41L); assertThat(resolver.movement(prePlay).postMoveLookEnabled()).isFalse(); assertThat(resolver.worldTopology(prePlay).scopeModel()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java index 6f9b8aa094..beab8b217c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java @@ -55,7 +55,17 @@ void setUp() { void effectiveSettingsUsesNormalizedPersistedSessionContext() { SessionContext cleared = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); PresentationProperties presentation = new PresentationProperties(); MovementProperties movement = new MovementProperties(); WorldTopologyProperties worldTopology = new WorldTopologyProperties(); 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 d817622c13..ccbc6e791d 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 @@ -21,7 +21,7 @@ class GameplayLocalPathReadinessProbeTest { private static final long PROBE_SESSION_ID_BASE = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_UUID = "ff36f51a-6cbd-4f26-8332-031535e2e3b4"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; @Test @@ -38,7 +38,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { new SessionContext( sessionId, 0L, - PROBE_ACCOUNT_ID, + PROBE_ACCOUNT_UUID, PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, @@ -74,7 +74,7 @@ void sessionContextProbeRejectsStoredSecret() { new SessionContext( sessionId, 0L, - PROBE_ACCOUNT_ID, + PROBE_ACCOUNT_UUID, PROBE_CHARACTER_ID, 0L, "readiness-room-" + (sessionId - PROBE_SESSION_ID_BASE), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java index a53b8fdb29..bf13e1d3a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java @@ -102,7 +102,16 @@ void scopedOverrideControlsPromptWindowWhenContextKnown() { List outputs = List.of(PlayerOutput.message("You say, \"hello\""), PlayerOutput.prompt("demo> ")); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Sora", 7L, "R-1", null); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Sora", + 7L, + "R-1", + null); coordinator.recordPromptEmission("1", outputs); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java index 8eaed1f1ea..39d3731ee0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java @@ -11,7 +11,16 @@ class PromptComposerTest { @Test void composeIncludesStructuredFieldsAlongsideClassicPromptText() { SessionContext context = - new SessionContext(41L, 22L, 77L, "demo@example.com", 123L, "Sora", 9L, "R-1021", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Sora", + 9L, + "R-1021", + "jwt"); PlayerOutput prompt = composer.compose(context).orElseThrow(); @@ -29,7 +38,16 @@ void composeIncludesStructuredFieldsAlongsideClassicPromptText() { @Test void composeFallsBackToBarePromptWhileStillPublishingIdentifiers() { SessionContext context = - new SessionContext(41L, 22L, 77L, null, 123L, null, 9L, "R-1021", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + null, + 123L, + null, + 9L, + "R-1021", + "jwt"); PlayerOutput prompt = composer.compose(context).orElseThrow(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index 536625bd11..305b32223c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -15,6 +15,8 @@ class TextPlayerOutputRendererTest { private static final String STRIDE_COMMAND_ID = "stride"; + private static final String SORA_ACCOUNT_ID = "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30"; + private static final String OTHER_FRIEND_ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; @Test void characterRosterExplainsCurrentNameOnlySelection() { @@ -1146,7 +1148,7 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + SORA_ACCOUNT_ID, "ONLINE", null, "Sora", @@ -1171,7 +1173,9 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { assertThat(rendered) .isEqualTo( "OK FRIENDS\n" - + "Friend Sora [acct #41]\n" + + "Friend Sora [acct #" + + SORA_ACCOUNT_ID + + "]\n" + "Link: #77\n" + "Status: online\n" + "Presence: online in Demo World / Ember Realm (active)\n" @@ -1202,11 +1206,26 @@ void rendersFilteredOnlineFriendsWithoutAggregateCounts() { 2, List.of( new FriendPresenceViewOutput.Entry( - 1, null, 77L, "active", null, "Sora", true, null, null, null, null, - null, null, null, null, null, "PUBLIC"))))); + 1, + null, + OTHER_FRIEND_ACCOUNT_ID, + "active", + null, + "Sora", + true, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "PUBLIC"))))); assertThat(rendered) - .contains("Friends ONLINE:\n", "1) Sora [acct #77] - online") + .contains("Friends ONLINE:\n", "1) Sora [acct #" + OTHER_FRIEND_ACCOUNT_ID + "] - online") .doesNotContain("[1/2]", "[0/2]"); } @@ -1248,7 +1267,7 @@ void rendersGenericLastSeenWithoutDisconnectDisposition() { new FriendPresenceViewOutput.Entry( 1, null, - 77L, + SORA_ACCOUNT_ID, "active", null, "Sora", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java index e9cdeade50..1484b59374 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java @@ -66,10 +66,29 @@ void tearDown() { @Test void deliverDropsStaleRecipientResolvedByGameplayIdentity() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext clearedRecipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -95,10 +114,29 @@ void deliverDropsStaleRecipientResolvedByGameplayIdentity() { @Test void deliverDropsStaleRecipientResolvedByGameplayName() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext clearedRecipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -124,7 +162,16 @@ void deliverDropsStaleRecipientResolvedByGameplayName() { @Test void deliverDoesNotFallbackToNameWhenRecipientIdIsMalformed() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -150,7 +197,16 @@ void deliverDoesNotFallbackToNameWhenRecipientIdIsMalformed() { @Test void deliverDoesNotFallbackToNameWhenRecipientIdIsNonPositive() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -174,7 +230,16 @@ void deliverDoesNotFallbackToNameWhenRecipientIdIsNonPositive() { @Test void deliverDoesNotFallbackToNameWhenStructuredRecipientIdDoesNotResolve() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -203,10 +268,29 @@ void deliverDoesNotFallbackToNameWhenStructuredRecipientIdDoesNotResolve() { @SuppressWarnings("unchecked") void deliverBuffersStructuredReplayEntryForRecipientCommunication() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext recipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 456L, + "Sora", + 1L, + "R-2", + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -252,10 +336,29 @@ void deliverBuffersStructuredReplayEntryForRecipientCommunication() { @Test void deliverDoesNotBufferNonReplayableRecipientOutput() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext recipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 456L, + "Sora", + 1L, + "R-2", + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 3d840f6efc..b715da48c4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -18,12 +18,14 @@ import tools.jackson.databind.ObjectMapper; class DirectTextConnectScopeSessionStoreTest { + private static final String ACCOUNT_UUID = "11111111-1111-4111-8111-111111111111"; + private static final String OTHER_ACCOUNT_UUID = "22222222-2222-4222-8222-222222222222"; private final DirectTextConnectScopeSessionStore store = DirectTextConnectScopeSessionStore.inMemoryForTest(); @Test void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, ACCOUNT_UUID); Instant now = Instant.now(); Instant expiry = now.plusSeconds(3600); store.replaceWorldScopes( @@ -36,13 +38,15 @@ void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { assertThat(store.publicProductionScope(caller, 22L, "demo-world", now)) .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("scope-secret")); - assertThat(store.publicProductionScope(session(8L, 41L), 22L, "demo-world", now)).isEmpty(); - assertThat(store.publicProductionScope(session(7L, 42L), 22L, "demo-world", now)).isEmpty(); + assertThat(store.publicProductionScope(session(8L, ACCOUNT_UUID), 22L, "demo-world", now)) + .isEmpty(); + assertThat(store.publicProductionScope(session(7L, OTHER_ACCOUNT_UUID), 22L, "demo-world", now)) + .isEmpty(); } @Test void refusesExpiredAndAmbiguousPublicScopes() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, ACCOUNT_UUID); Instant now = Instant.now(); store.replaceWorldScopes( caller, @@ -69,7 +73,7 @@ void refusesExpiredAndAmbiguousPublicScopes() { @Test void clearsPriorScopeBeforeReplacingTheWorldBinding() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, ACCOUNT_UUID); Instant now = Instant.now(); store.replaceWorldScopes( caller, @@ -86,7 +90,7 @@ void clearsPriorScopeBeforeReplacingTheWorldBinding() { @Test void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, ACCOUNT_UUID); Instant now = Instant.now(); Instant expiry = now.plusSeconds(3600); store.replaceRealmSnapshot( @@ -133,7 +137,7 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { @Test void clearingTransportLobbyRemovesScopeAndBoundJoinIdentityBeforeReuse() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, ACCOUNT_UUID); Instant now = Instant.now(); store.replaceRealmSnapshot( caller, @@ -174,12 +178,13 @@ void clearingTransportLobbyRemovesScopeAndBoundJoinIdentityBeforeReuse() { @Test void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.now(); DirectTextConnectScopeSessionStore.WorldOrdinalTarget target = new DirectTextConnectScopeSessionStore.WorldOrdinalTarget( 1, "demo-world", 22L, 13L, "target-fingerprint"); - store.replaceWorldSnapshot(caller.sessionId(), 0L, "catalog-fingerprint", List.of(target), now); + store.replaceWorldSnapshot( + caller.sessionId(), caller.accountId(), "catalog-fingerprint", List.of(target), now); assertThat(store.worldsSnapshot(caller, now)) .hasValueSatisfying( @@ -202,20 +207,19 @@ void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { store.publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now).orElseThrow(); assertThat(selected.scope().expiresAt()).isBeforeOrEqualTo(now.plusSeconds(901)); - assertThat(selected.scope().playerContext().getAccountId()).isEqualTo("7"); + assertThat(selected.scope().playerContext().getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); } @Test - @SuppressWarnings("unchecked") void readsLegacyLobbyJsonAcrossProductionStoreInstances() throws Exception { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.now(); long expiresAt = now.plusSeconds(600).toEpochMilli(); String worldKey = "22:ZGVtby13b3JsZA"; PlayerExecutionContext playerContext = PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId("7") .setSessionId(Long.toString(caller.sessionId())) .setTenantId(Long.toString(caller.tenantId())) .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") @@ -228,7 +232,7 @@ void readsLegacyLobbyJsonAcrossProductionStoreInstances() throws Exception { .writeValueAsString( Map.of( "sessionId", caller.sessionId(), - "accountId", caller.accountId(), + "accountId", "7", "worldsExpiresAtEpochMs", expiresAt, "catalogFingerprint", "catalog-fingerprint-v13", "ordinalTargets", List.of(), @@ -267,62 +271,74 @@ void readsLegacyLobbyJsonAcrossProductionStoreInstances() throws Exception { "ordinalTargets", List.of())))); AtomicReference sharedRedisValue = new AtomicReference<>(legacyJson); - StringRedisTemplate redisTemplate = Mockito.mock(StringRedisTemplate.class); - ValueOperations valueOperations = Mockito.mock(ValueOperations.class); - Mockito.when(redisTemplate.opsForValue()).thenReturn(valueOperations); - Mockito.when(valueOperations.get(Mockito.anyString())) - .thenAnswer(invocation -> sharedRedisValue.get()); - Mockito.doAnswer( - invocation -> { - Object[] arguments = - java.util.Arrays.copyOfRange( - invocation.getArguments(), 2, invocation.getArguments().length); - String expectedValue = "1".equals(arguments[0]) ? (String) arguments[1] : null; - if (!Objects.equals(sharedRedisValue.get(), expectedValue)) { - return 0L; - } - sharedRedisValue.set("1".equals(arguments[2]) ? (String) arguments[3] : null); - return 1L; - }) - .when(redisTemplate) - .execute(Mockito.any(RedisScript.class), Mockito.anyList(), Mockito.any(Object[].class)); + StringRedisTemplate redisTemplate = redisTemplate(sharedRedisValue); + + DirectTextConnectScopeSessionStore firstInstance = + new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); + DirectTextConnectScopeSessionStore replacementInstance = + new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); + assertThatThrownBy(() -> firstInstance.realmsSnapshot(caller, 22L, "demo-world", now)) + .isInstanceOf(DirectTextConnectScopeSessionStore.StoreUnavailableException.class); + assertThatThrownBy( + () -> + replacementInstance.publicProductionScopeForJoin( + caller, "1", 22L, "demo-world", now)) + .isInstanceOf(DirectTextConnectScopeSessionStore.StoreUnavailableException.class); + assertThat(sharedRedisValue.get()).isEqualTo(legacyJson); + } + + @Test + void readsUuidLobbySnapshotAcrossProductionStoreInstances() { + SessionContext caller = session(41L, ACCOUNT_UUID); + Instant now = Instant.now(); + AtomicReference sharedRedisValue = new AtomicReference<>(); + StringRedisTemplate redisTemplate = redisTemplate(sharedRedisValue); DirectTextConnectScopeSessionStore firstInstance = new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); DirectTextConnectScopeSessionStore replacementInstance = new DirectTextConnectScopeSessionStore(redisTemplate, new ObjectMapper()); + DirectTextConnectScopeSessionStore.RealmOrdinalTarget target = + new DirectTextConnectScopeSessionStore.RealmOrdinalTarget( + 1, "production", 22L, 29L, 3L, "uuid-realm-target-fingerprint"); + firstInstance.replaceRealmSnapshot( + caller, + "1", + 22L, + "demo-world", + "uuid-catalog-fingerprint", + List.of(target), + List.of(scopedRealm(caller, "production", "uuid-connect-scope", now.plusSeconds(600))), + now); - assertThat(firstInstance.realmsSnapshot(caller, 22L, "demo-world", now)) + assertThat(replacementInstance.realmsSnapshot(caller, 22L, "demo-world", now)) .hasValueSatisfying( snapshot -> { - assertThat(snapshot.tenantId()).isEqualTo(22L); - assertThat(snapshot.requestedWorldSelector()).isEqualTo("1"); + assertThat(snapshot.ordinalTargets()).containsExactly(target); + assertThat(snapshot.catalogFingerprint()).isEqualTo("uuid-catalog-fingerprint"); }); DirectTextConnectScopeSessionStore.JoinScope selected = replacementInstance .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now) .orElseThrow(); - assertThat(selected.scope().connectScopeId()).isEqualTo("account-connect-scope-legacy"); - assertThat(selected.scope().playerContext().getAccountId()).isEqualTo("7"); + assertThat(selected.scope().connectScopeId()).isEqualTo("uuid-connect-scope"); + assertThat(selected.scope().playerContext().getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(selected.scope().playerContext().getSessionId()).isEqualTo("41"); - assertThat(selected.scope().playerContext().getTenantId()).isEqualTo("22"); - assertThat(selected.requestId()).isEqualTo("join-request-already-bound"); assertThat( firstInstance .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now) .orElseThrow() .requestId()) - .isEqualTo("join-request-already-bound"); - assertThat(sharedRedisValue.get()).doesNotContain("worldBySelector"); + .isEqualTo(selected.requestId()); } @Test void sameWorldSlugInDifferentTenantsKeepsOrdinalScopesIsolated() { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.now(); store.replaceWorldSnapshot( caller.sessionId(), - 0L, + caller.accountId(), "catalog-fingerprint", List.of( new DirectTextConnectScopeSessionStore.WorldOrdinalTarget( @@ -368,7 +384,7 @@ void sameWorldSlugInDifferentTenantsKeepsOrdinalScopesIsolated() { @Test void storesRealmsResponseSnapshotOnlyForTheIssuingAccountAndBeforeExpiry() { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.now(); DirectTextConnectScopeSessionStore.RealmOrdinalTarget target = new DirectTextConnectScopeSessionStore.RealmOrdinalTarget( @@ -386,14 +402,14 @@ void storesRealmsResponseSnapshotOnlyForTheIssuingAccountAndBeforeExpiry() { assertThat(snapshot.ordinalTargets()).containsExactly(target); assertThat(snapshot.expiresAt()).isBeforeOrEqualTo(now.plusSeconds(301)); }); - assertThat(store.realmsSnapshot(session(41L, 8L), 22L, "demo", now)).isEmpty(); - assertThat(store.realmsSnapshot(session(42L, 7L), 22L, "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(session(41L, OTHER_ACCOUNT_UUID), 22L, "demo", now)).isEmpty(); + assertThat(store.realmsSnapshot(session(42L, ACCOUNT_UUID), 22L, "demo", now)).isEmpty(); assertThat(store.realmsSnapshot(caller, 22L, "demo", now.plusSeconds(301))).isEmpty(); } @Test void replacingWorldScopesClearsOnlyThatWorldsRealmsSnapshotAndKeepsJoinScopes() { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.now(); store.replaceRealmSnapshot( caller, "demo", 22L, "demo", "demo-catalog", List.of(), List.of(), now); @@ -424,7 +440,7 @@ void replacingWorldScopesClearsOnlyThatWorldsRealmsSnapshotAndKeepsJoinScopes() @Test void replacingWorldScopesUsesCallerTimeWhenPruningUnrelatedScopes() { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.parse("2000-01-01T00:00:00Z"); Instant scopeExpiry = now.plusSeconds(600); store.replaceRealmSnapshot( @@ -466,7 +482,7 @@ void replacingWorldScopesUsesCallerTimeWhenPruningUnrelatedScopes() { @Test void clearingWorldScopesUsesCallerTimeWhenPruningUnrelatedScopes() { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.parse("2000-01-01T00:00:00Z"); Instant scopeExpiry = now.plusSeconds(600); store.replaceRealmSnapshot( @@ -500,7 +516,7 @@ void clearingWorldScopesUsesCallerTimeWhenPruningUnrelatedScopes() { @Test void worldScopeMutationsRejectNullCallerTime() { - SessionContext caller = session(41L, 7L); + SessionContext caller = session(41L, ACCOUNT_UUID); assertThatThrownBy(() -> store.replaceWorldScopes(caller, "demo", 22L, "demo", List.of(), null)) .isInstanceOf(NullPointerException.class) @@ -512,8 +528,8 @@ void worldScopeMutationsRejectNullCallerTime() { @Test void replacingWorldScopesForAnotherAccountClearsPriorLobbyAuthority() { - SessionContext previousCaller = session(41L, 7L); - SessionContext currentCaller = session(41L, 8L); + SessionContext previousCaller = session(41L, ACCOUNT_UUID); + SessionContext currentCaller = session(41L, OTHER_ACCOUNT_UUID); Instant now = Instant.now(); Instant expiresAt = now.plusSeconds(60); store.replaceRealmSnapshot( @@ -556,19 +572,43 @@ void replacingWorldScopesForAnotherAccountClearsPriorLobbyAuthority() { void rejectsInvalidTransportIdsAndScopesBoundToAnotherIdentity() { assertThatThrownBy(() -> store.clearSession(0L)).isInstanceOf(IllegalArgumentException.class); - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, ACCOUNT_UUID); Instant now = Instant.now(); DirectTextConnectScopeSessionStore.ScopedRealm mismatchedScope = - scopedRealm(session(8L, 41L), "production", "scope-secret", now.plusSeconds(60)); + scopedRealm(session(8L, ACCOUNT_UUID), "production", "scope-secret", now.plusSeconds(60)); assertThatThrownBy( () -> store.replaceWorldScopes(caller, "demo", "demo", List.of(mismatchedScope), now)) .isInstanceOf(DirectTextConnectScopeSessionStore.ConflictingIdentityException.class); } - private static SessionContext session(long sessionId, long accountId) { + private static SessionContext session(long sessionId, String accountId) { return new SessionContext(sessionId, 22L, accountId, 7001L, 9L, "jwt"); } + @SuppressWarnings("unchecked") + private static StringRedisTemplate redisTemplate(AtomicReference sharedRedisValue) { + StringRedisTemplate redisTemplate = Mockito.mock(StringRedisTemplate.class); + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + Mockito.when(redisTemplate.opsForValue()).thenReturn(valueOperations); + Mockito.when(valueOperations.get(Mockito.anyString())) + .thenAnswer(invocation -> sharedRedisValue.get()); + Mockito.doAnswer( + invocation -> { + Object[] arguments = + java.util.Arrays.copyOfRange( + invocation.getArguments(), 2, invocation.getArguments().length); + String expectedValue = "1".equals(arguments[0]) ? (String) arguments[1] : null; + if (!Objects.equals(sharedRedisValue.get(), expectedValue)) { + return 0L; + } + sharedRedisValue.set("1".equals(arguments[2]) ? (String) arguments[3] : null); + return 1L; + }) + .when(redisTemplate) + .execute(Mockito.any(RedisScript.class), Mockito.anyList(), Mockito.any(Object[].class)); + return redisTemplate; + } + private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( SessionContext caller, String realmSlug, String scopeId, Instant expiry) { return scopedRealm(caller, 22L, realmSlug, scopeId, expiry); @@ -578,7 +618,7 @@ private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( SessionContext caller, long tenantId, String realmSlug, String scopeId, Instant expiry) { PlayerExecutionContext playerContext = PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) .setTenantId(Long.toString(tenantId)) .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java index 095ceed114..0bf2702baf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java @@ -11,11 +11,13 @@ import org.junit.jupiter.api.Test; class GameplayAdmissionPointerSnapshotsTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + @Test void admittedRoutingBundleReturnsNormalizedBundleWhenRoutingClaimsAreComplete() { SessionContext completeContext = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", "realm", 17L, + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", "realm", 17L, null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = @@ -33,7 +35,8 @@ void admittedRoutingBundleReturnsNormalizedBundleWhenRoutingClaimsAreComplete() void admittedRoutingBundleReturnsEmptyForPartialRoutingClaims() { SessionContext partialRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, + null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = GameplayAdmissionPointerSnapshots.admittedRoutingBundle(partialRouting); @@ -48,7 +51,7 @@ void admittedRoutingBundleReturnsEmptyForPartialRoutingClaims() { void admittedRoutingBundleReturnsEmptyWhenRoutingClaimsAreAbsent() { SessionContext missingRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = GameplayAdmissionPointerSnapshots.admittedRoutingBundle(missingRouting); @@ -63,7 +66,8 @@ void admittedRoutingBundleReturnsEmptyWhenRoutingClaimsAreAbsent() { void requireAdmittedRoutingBundleRejectsPartialRoutingClaimsWithCallerSpecificMessage() { SessionContext partialRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, + null); assertThatThrownBy( () -> @@ -77,7 +81,7 @@ void requireAdmittedRoutingBundleRejectsPartialRoutingClaimsWithCallerSpecificMe void requireAdmittedRoutingBundleRejectsMissingRoutingClaimsWithCallerSpecificMessage() { SessionContext missingRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); assertThatThrownBy( () -> @@ -452,7 +456,7 @@ void sameBootstrapRouteRejectsPlayableStateScopeChanges() { void sameBootstrapRouteRejectsFirstPartyConnectContextWhenRoutingIdentityChanges() { FirstPartyConnectContext existing = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); + ACCOUNT_ID, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); assertThat( GameplayAdmissionPointerSnapshots.sameBootstrapRoute( @@ -480,7 +484,7 @@ void sameBootstrapRouteAcceptsTwoContextsWithNoRoutingValues() { void sameBootstrapRouteAcceptsFirstPartyConnectContextWithCaseInsensitiveRoutingIdentity() { FirstPartyConnectContext existing = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); + ACCOUNT_ID, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); assertThat( GameplayAdmissionPointerSnapshots.sameBootstrapRoute( @@ -508,7 +512,7 @@ private static SessionContext bootstrapShell( return new SessionContext( 1L, tenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java index f572ac2758..a28242237e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java @@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test; class GameplayPresenceActivityResolverTest { + private static final String ACCOUNT_ID = "fd6f4d69-789b-4e0f-92f1-0c19b3bb1c17"; @Test void explicitAfkWinsOverDerivedAutoAfk() { @@ -23,7 +24,7 @@ void explicitAfkWinsOverDerivedAutoAfk() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -51,7 +52,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -68,7 +69,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -85,7 +86,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -111,7 +112,7 @@ void autoAfkFallsBackToConnectionTimeWhenNoGameplayActivityExists() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java index 208be9144e..b28200eb1b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java @@ -17,6 +17,7 @@ import org.mockito.Mockito; class SessionAuthenticationServiceTest { + private static final String ACCOUNT_ID = "7c116c4e-2332-4fea-9590-8fd704d56da6"; private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -45,7 +46,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -66,13 +67,13 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_ID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); assertEquals(0L, resolved.orElseThrow().characterId()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); - assertEquals(123L, captor.getValue().accountId()); + assertEquals(ACCOUNT_ID, captor.getValue().accountId()); assertEquals(0L, captor.getValue().gameInstanceId()); assertEquals(0L, captor.getValue().pointerVersion()); } @@ -81,7 +82,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { SessionContext incomplete = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); + 41L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(incomplete)); when(sessionContextService.findByTenantAndSessionId(22L, 41L)) .thenReturn(Optional.of(incomplete)); @@ -89,7 +90,7 @@ void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_ID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService) @@ -102,7 +103,7 @@ void resolveSessionContextClearsGameplayBindingWhenRuntimeTargetAuthorityIsAmbig new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -139,7 +140,7 @@ void resolveSessionContextKeepsCurrentGameplayBindingWhenPointerMatches() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -172,7 +173,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -192,7 +193,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { Optional resolved = service.resolveUnverifiedSessionContext(22L, 41L); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_ID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); @@ -204,7 +205,7 @@ void resolveUnverifiedSessionContextFailsClosedWhenTenantScopedSessionIsMissing( new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -260,7 +261,7 @@ void resolveByGameplayIdentityNormalizesResolvedContext() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -292,7 +293,7 @@ void resolveByGameplayNameKeepsCurrentContextWhenPointerMatches() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java index fee7ca2ce4..dd6aea6fd9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java @@ -2,25 +2,36 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class SessionContextTest { + private static final String ACCOUNT_ID = "5d7e83b0-e8c4-4edb-b3b7-5d99d4bbad9d"; @Test void preservesLegacyAndSyntheticRuntimeRoomIdsVerbatim() { SessionContext legacyNumeric = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); SessionContext legacyPrefixed = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); SessionContext legacyUppercasePrefixed = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); SessionContext syntheticProbe = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "readiness-room-1", "jwt"); + 1L, + 22L, + ACCOUNT_ID, + "demo@example.com", + 7001L, + "Emberline", + 41L, + "readiness-room-1", + "jwt"); assertEquals("1", legacyNumeric.roomInstanceId()); assertEquals("room-1", legacyPrefixed.roomInstanceId()); @@ -34,7 +45,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectRequest() { new SessionContext( 1L, 22L, - 123L, + ACCOUNT_ID, "first-party:123", 0L, null, @@ -60,7 +71,7 @@ void hasPartialPersistedFirstPartyConnectContextIgnoresStandardGameplaySession() new SessionContext( 1L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -85,7 +96,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { new SessionContext( 1L, 22L, - 123L, + ACCOUNT_ID, "first-party:123", 0L, null, @@ -106,12 +117,12 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { } @Test - void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity() { + void hasPartialPersistedFirstPartyConnectContextRequiresCanonicalAccountIdentity() { SessionContext context = new SessionContext( 1L, 22L, - 0L, + null, "first-party:123", 0L, null, @@ -135,11 +146,12 @@ void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity( void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { SessionContext complete = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingRoom = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayRegionBinding()); assertFalse(missingRoom.hasGameplayRegionBinding()); @@ -149,13 +161,14 @@ void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { @Test void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { SessionContext gameOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 41L, null, "jwt"); SessionContext characterOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); SessionContext roomOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "R-1", "jwt"); SessionContext blank = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "jwt"); assertTrue(gameOnly.hasGameplayBinding()); assertTrue(characterOnly.hasGameplayBinding()); @@ -167,14 +180,32 @@ void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { void hasGameplayIdentityRequiresPositiveGameInstanceAndCharacter() { SessionContext complete = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingGameInstance = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayIdentity()); assertFalse(missingGameInstance.hasGameplayIdentity()); assertFalse(missingCharacter.hasGameplayIdentity()); } + + @Test + void accountIdentityMustBeCanonicalNonNilUuidOrAbsent() { + SessionContext unauthenticated = new SessionContext(1L, 22L, null, null, 0L, null, 0L, null); + + assertFalse(unauthenticated.hasAccountIdentity()); + assertThrows( + IllegalArgumentException.class, + () -> new SessionContext(1L, 22L, "123", null, 0L, null, 0L, null)); + assertThrows( + IllegalArgumentException.class, + () -> + new SessionContext( + 1L, 22L, "00000000-0000-0000-0000-000000000000", null, 0L, null, 0L, null)); + assertTrue( + new SessionContext(1L, 22L, ACCOUNT_ID, null, 0L, null, 0L, null).hasAccountIdentity()); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java index 04c9c0108b..f501f4f910 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java @@ -31,7 +31,7 @@ void resolveProjectedSessionContextFailsClosedWhenTenantScopedSessionIsMissing() new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", @@ -77,7 +77,7 @@ void normalizeProjectedContextClearsPartialGameplayShellWhenAdmissionPointerCann new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", @@ -109,7 +109,7 @@ void normalizeProjectedContextClearsLegacyRuntimeRoomBindingBeforePointerChecks( new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java index 929f616c8c..bea1576742 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java @@ -20,6 +20,10 @@ import org.mockito.Mockito; class AccountPresenceQueryServiceImplTest { + private static final String CALLER_ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT_A = "550e8400-e29b-41d4-a716-446655440000"; + private static final String ACCOUNT_B = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; + @Test void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { GameplayPresenceService presenceService = Mockito.mock(GameplayPresenceService.class); @@ -35,13 +39,16 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of(3L, 4L)) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ACCOUNT_A, ACCOUNT_B)) + && ids.size() == 2))) .thenReturn( java.util.Map.of( - 4L, + ACCOUNT_B, new AccountRecentPresenceState( 1L, - 4L, + ACCOUNT_B, 2L, "SHARED", "sandbox", @@ -52,10 +59,13 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of(3L, 4L)) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ACCOUNT_A, ACCOUNT_B)) + && ids.size() == 2))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -65,7 +75,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -78,10 +88,10 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L, 4L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A, ACCOUNT_B)); assertEquals(2, result.size()); - assertEquals(3L, result.get(0).accountId()); + assertEquals(ACCOUNT_A, result.get(0).accountId()); assertEquals(true, result.get(0).online()); assertEquals(2L, result.get(0).gameInstanceId()); assertEquals("sandbox", result.get(0).worldSlug()); @@ -94,7 +104,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { net.firedevops.firemud.gamesession.service.GameplayPresenceActivityState.EXPLICIT_AFK, result.get(0).activityState()); assertEquals(null, result.get(0).recentDisposition()); - assertEquals(4L, result.get(1).accountId()); + assertEquals(ACCOUNT_B, result.get(1).accountId()); assertEquals(false, result.get(1).online()); assertEquals(2L, result.get(1).gameInstanceId()); assertEquals("sandbox", result.get(1).worldSlug()); @@ -122,13 +132,13 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 9L, "SHARED", "sandbox", @@ -139,10 +149,10 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -152,7 +162,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { "sandbox", "production", 18L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -165,7 +175,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -188,13 +198,13 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -205,10 +215,10 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -218,7 +228,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin "sandbox", "production", 0L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -231,7 +241,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -257,13 +267,13 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -274,10 +284,10 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -287,7 +297,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna " ", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -300,7 +310,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -326,15 +336,15 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -344,7 +354,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 18L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -360,7 +370,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 100L, "Ben", GameplayPresenceRole.PLAYER, @@ -373,7 +383,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -397,13 +407,13 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -414,10 +424,10 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -427,7 +437,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -441,7 +451,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L), pointer("sandbox", "Builder Sandbox", "preview", "Preview Realm", 1L, 2L, 18L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -467,13 +477,13 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -484,10 +494,10 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -497,7 +507,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -522,7 +532,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "", "ALLOW_NEW"))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -548,15 +558,15 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -566,7 +576,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { "Sandbox", "Production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -579,7 +589,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -604,13 +614,13 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(4L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_B) && ids.size() == 1))) .thenReturn( Map.of( - 4L, + ACCOUNT_B, new AccountRecentPresenceState( 1L, - 4L, + ACCOUNT_B, 2L, "SHARED", "Sandbox", @@ -621,14 +631,14 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(4L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_B) && ids.size() == 1))) .thenReturn(Map.of()); when(pointerAuthorityService.listByRuntimeTarget(1L, 2L)) .thenReturn( List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(4L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_B)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java index ed1e38edbf..f3b5b5e43a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java @@ -846,7 +846,7 @@ private static SessionContext gameplayContext(String roomId, String playableStat return new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java index 7cac76b022..2c5ddae381 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.verify; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; @@ -33,6 +34,8 @@ @ExtendWith(OutputCaptureExtension.class) class CommandServiceImplTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + @Test void rateLimitFailurePropagatesError() { TickService tickService = Mockito.mock(TickService.class); @@ -219,6 +222,8 @@ void enqueuePassesThroughWhenAllowed() { assertEquals("LOOK", accepted.getCommandName()); assertEquals("look", accepted.getSanitizedCommandText()); assertEquals(1L, accepted.getEnqueueSeq()); + assertNull(accepted.getAccountUuid()); + assertNull(accepted.getAccountId()); } @Test @@ -311,7 +316,17 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); CommandServiceImpl service = @@ -330,6 +345,13 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { verify(tickService, times(1)).enqueueCommand(9L, 99L, result.commandId(), "look", false); verify(scriptEventPublisher, times(1)) .publishCommandEvent(Mockito.any(SessionContext.class), Mockito.any(GameplayCommand.class)); + org.mockito.ArgumentCaptor commandCaptor = + org.mockito.ArgumentCaptor.forClass(GameplayCommand.class); + verify(commandRepository).save(commandCaptor.capture()); + GameplayCommand accepted = commandCaptor.getValue(); + assertEquals( + UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), accepted.getAccountUuid()); + assertNull(accepted.getAccountId()); } @Test @@ -350,7 +372,7 @@ void gameplayCommandsPersistCurrentRuntimeScopeForDurableCommandEventFallback() new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -403,7 +425,16 @@ void gameplayCommandFailsBeforePersistenceWhenRuntimeOwnershipIsNotEstablished() Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "region-99", + "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenReturn(Optional.empty()); CommandServiceImpl service = @@ -445,7 +476,16 @@ void gameplayCommandFailsClosedWhenRuntimeOwnershipReadFails() { Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "region-99", + "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenThrow(new IllegalStateException("runtime ownership unavailable")); CommandServiceImpl service = @@ -489,7 +529,7 @@ void bootstrapShellQueuesAgainstBootstrapRuntimeWhenSessionIdDiffers() { new SessionContext( 17L, 9L, - 0L, + null, null, 0L, null, @@ -536,7 +576,21 @@ void staleNormalizedGameplaySessionFailsClosedWithoutBootstrapRoutingBundle() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SessionContext cleared = new SessionContext( - 17L, 9L, 3L, "demo", 0L, null, 0L, null, "jwt", null, 99L, null, null, 0L, null); + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 0L, + null, + 0L, + null, + "jwt", + null, + 99L, + null, + null, + 0L, + null); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn(Optional.of(cleared)); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); @@ -579,7 +633,17 @@ void enqueueAddsGameplayLoggingContextWhenSessionIsBound() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doAnswer( invocation -> { @@ -629,7 +693,17 @@ void loginCommandsAreRedactedFromLogs(CapturedOutput output) { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); CommandServiceImpl service = newCommandService( @@ -668,7 +742,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 0L, null, @@ -732,7 +806,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromUnambiguousRuntimeAuthority GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_ID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -784,7 +858,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenRuntimeAuthorityIsAmbiguous() GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_ID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -849,7 +923,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenSingularRuntimeAuthorityIsInco GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_ID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -906,7 +980,7 @@ void gameplayCommandRepairsPartialSessionRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -973,7 +1047,20 @@ void gameplayCommandRepairsPointerOnlySessionRoutingMetadataFromRuntimeAuthority .thenReturn( Optional.of( new SessionContext( - 17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt", null, 99L, null, null, 17L, + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt", + null, + 99L, + null, + null, + 17L, "SHARED"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( @@ -1031,7 +1118,7 @@ void gameplayCommandUsesActiveGameplayRuntimeAuthorityBeforeBootstrapRuntime() { new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -1103,7 +1190,7 @@ void gameplayCommandRepairsStaleCompleteSessionRoutingMetadataFromCurrentAuthori new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 0L, null, @@ -1172,7 +1259,7 @@ void gameplayCommandDropsStaleCompleteSessionRoutingMetadataWhenCurrentAuthority new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 0L, null, @@ -1227,7 +1314,7 @@ void gameplayCommandDropsPartialSessionRoutingMetadataWhenAuthorityCannotRepairI new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -1282,7 +1369,7 @@ void gameplayCommandDropsSessionRoutingMetadataWhenCurrentSelectorPointerIsIncom new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -1347,7 +1434,17 @@ void queueValidationFailureMarksPersistedCommandFailed() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doThrow(new IllegalArgumentException("bad command")) .when(tickService) @@ -1471,14 +1568,14 @@ private SessionAuthenticationService identitySessionAuthenticationService() { private SessionContext bootstrapShell( long sessionId, long tenantId, long bootstrapGameInstanceId) { - return bootstrapShell(sessionId, tenantId, bootstrapGameInstanceId, 0L, null, null); + return bootstrapShell(sessionId, tenantId, bootstrapGameInstanceId, null, null, null); } private SessionContext bootstrapShell( long sessionId, long tenantId, long bootstrapGameInstanceId, - long accountId, + String accountId, String loginName, String jwt) { return new SessionContext( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java index ee91785206..56b49cd80e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java @@ -167,9 +167,27 @@ void executeDoesNotInferActionStateFromCombatMetadata() { @Test void executeReturnsReplayNoOpForIdempotentMoveReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); SessionContext moved = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-2", + "jwt-token"); GameplayCommand command = gameplayCommand("MOVE", "north"); TickEffect effect = tickEffect("tfx-1", "cmd-1"); PlayerOutput output = PlayerOutput.message("You move north."); @@ -203,9 +221,27 @@ void executeReturnsReplayNoOpForIdempotentMoveReplay() { @Test void executePublishesMovementLifecycleEventsAfterFirstApply() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); SessionContext moved = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-2", + "jwt-token"); GameplayCommand command = gameplayCommand("MOVE", "north"); TickEffect effect = tickEffect("tfx-9", "cmd-9"); when(parser.parse("north")) @@ -228,7 +264,16 @@ void executePublishesMovementLifecycleEventsAfterFirstApply() { @Test void executeAppliesDurableItemMutationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("GET", "GET torch"); TickEffect effect = tickEffect("tfx-2", "cmd-2"); TextCommand parsed = @@ -263,7 +308,16 @@ void executeAppliesDurableItemMutationAndDeliversOutput() { @Test void executeRejectsDurableItemMutationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("PUT", "PUT ration INTO torch"); TickEffect effect = tickEffect("tfx-3", "cmd-3"); TextCommand parsed = @@ -309,7 +363,16 @@ void executeRejectsDurableItemMutationAndDeliversOutput() { @Test void executeAppliesDurableCommunicationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); TickEffect effect = tickEffect("tfx-4", "cmd-4"); TextCommand parsed = @@ -338,7 +401,16 @@ void executeAppliesDurableCommunicationAndDeliversOutput() { @Test void executeNormalizesStaleSessionContextBeforeDurableGameplayHandling() { SessionContext cleared = - new SessionContext(42L, 22L, 7L, "demo@example.com", 0L, null, 0L, null, "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt-token"); GameplayCommand command = gameplayCommand("GET", "GET torch"); TickEffect effect = tickEffect("tfx-stale", "cmd-stale"); TextCommand parsed = @@ -369,7 +441,16 @@ void executeNormalizesStaleSessionContextBeforeDurableGameplayHandling() { @Test void executeResolvesAutomationCommandByGameplayIdentityWhenSessionIdIsUnset() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); command.setSessionId(0L); command.setTenantId(22L); @@ -445,7 +526,16 @@ void executeRejectsSessionlessCommandWhenTargetEntityIdIsNonPositive() { @Test void executeAppliesDurableAfkAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("BRB", "BRB"); TickEffect effect = tickEffect("tfx-5", "cmd-5"); TextCommand parsed = @@ -480,7 +570,16 @@ void executeAppliesDurableAfkAndDeliversOutput() { @Test void executeAppliesDurableBlockAndStoresReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("GUARD", "GUARD"); TickEffect effect = tickEffect("tfx-6", "cmd-6"); TextCommand parsed = @@ -509,7 +608,16 @@ void executeAppliesDurableBlockAndStoresReplay() { @Test void executeReplaysStoredCommunicationWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); TickEffect effect = tickEffect("tfx-6", "cmd-6"); TextCommand parsed = @@ -537,7 +645,16 @@ void executeReplaysStoredCommunicationWithoutInvokingHandler() { @Test void executeReplaysStoredRejectedAfkWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("AFK", "AFK"); TickEffect effect = tickEffect("tfx-7", "cmd-7"); TextCommand parsed = @@ -572,7 +689,16 @@ void executeReplaysStoredRejectedAfkWithoutInvokingHandler() { @Test void executeReplaysStoredBlockWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("BLOCK", "BLOCK"); TickEffect effect = tickEffect("tfx-7b", "cmd-7b"); TextCommand parsed = new TextCommand(TextCommandType.BLOCK, java.util.List.of(), "BLOCK"); @@ -600,7 +726,16 @@ void executeReplaysStoredBlockWithoutInvokingHandler() { @Test void executeAppliesPersistedAuthoredActionSnapshotWithoutLiveMetadata() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -642,7 +777,16 @@ void executeAppliesPersistedAuthoredActionSnapshotWithoutLiveMetadata() { @Test void executeReplaysPersistedAuthoredActionWithoutApplyingItsSnapshotAgain() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -695,7 +839,16 @@ void executeReplaysAuthoredSnapshotAgainstItsOriginalSessionAfterSessionResumpti playerOutputDeliveryService, scriptEventPublisher); SessionContext resumedContext = - new SessionContext(43L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 43L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -735,7 +888,16 @@ void executeReplaysAuthoredSnapshotAgainstItsOriginalSessionAfterSessionResumpti @Test void executeRejectsAuthoredActionWhenTheSessionSwitchedGameplayIdentity() { SessionContext switchedContext = - new SessionContext(42L, 22L, 7L, "demo@example.com", 92L, "Other", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 92L, + "Other", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -757,7 +919,16 @@ void executeRejectsAuthoredActionWhenTheSessionSwitchedGameplayIdentity() { @Test void executeRejectsMalformedAuthoredSnapshotBeforeReplayOrScriptPublication() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -781,7 +952,16 @@ void executeRejectsMalformedAuthoredSnapshotBeforeReplayOrScriptPublication() { @Test void executeRejectsAuthoredSnapshotWithAnInvalidModifierBeforeReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -823,7 +1003,16 @@ void executeRejectsAuthoredSnapshotWithAnInvalidModifierBeforeReplay() { @Test void executeRejectsAuthoredSnapshotAboveTheSharedDurationLimitBeforeReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); 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 b6df308271..2bbb2cf176 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 @@ -34,7 +34,15 @@ class DefaultGameplayPresenceLifecycleServiceTest { void registerConnectedUpdatesLiveAndRecentPresence() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); service.registerConnected(context); @@ -54,7 +62,15 @@ void recordActivityUpdatesLiveAndRecentPresence() { void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); service.clearGameplayBinding(context, "STALE_ADMISSION_POINTER"); @@ -71,7 +87,16 @@ void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting @Test void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { SessionContext context = - new SessionContext(41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext( + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + ""); service.clearGameplayBinding(context, "LOGIN_FAILED"); @@ -86,7 +111,15 @@ void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { whenGameplayContextPresent( new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", "")); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + "")); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); @@ -109,7 +142,15 @@ void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { void recordDisconnectedPreservesCanonicalLogoutEventId() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); whenGameplayContextPresent(context); service.recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); @@ -121,7 +162,15 @@ void recordDisconnectedPreservesCanonicalLogoutEventId() { void takeoverRemovesDisplacedSessionWithoutPublishingCharacterRegionExit() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); whenGameplayContextPresent(context); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TAKEOVER); @@ -136,7 +185,7 @@ void takeoverRemovesDisplacedSessionWithoutPublishingCharacterRegionExit() { @Test void recordDisconnectedSkipsLifecycleEventWithoutGameplayRegionBinding() { whenGameplayContextPresent( - new SessionContext(41L, 22L, 0L, "demo@example.com", 7001L, "Emberline", 0L, "", "")); + new SessionContext(41L, 22L, null, "demo@example.com", 7001L, "Emberline", 0L, "", "")); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); @@ -157,7 +206,16 @@ private void whenGameplayContextPresent(SessionContext context) { @Test void recordDisconnectedSkipsExitWhenNormalizationClearsStaleGameplayBinding() { SessionContext cleared = - new SessionContext(41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext( + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + ""); Mockito.when(sessionRoutingNormalizationService.resolveProjectedSessionContext("41")) .thenReturn(Optional.of(cleared)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java index 3c5b060849..acd1d61e4f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java @@ -56,6 +56,14 @@ private void whenInstance(long gameInstanceId, GameInstance instance) { private SessionContext gameplayContext() { return new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); } } 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 2e41d1f5cd..856e78574a 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 @@ -73,6 +73,8 @@ import org.mockito.Mockito; class GameSessionGrpcServiceTest { + private static final String ACCOUNT_VIEWER = "37bf660c-8de4-49ed-8f62-821455239d78"; + private static final String ACCOUNT_TARGET = "b693f855-e466-4eb7-bec9-c8892b530b2b"; private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; private static final String OTHER_ACCOUNT_UUID = "f720d1f5-7f16-4e02-9340-d0a5e2345f67"; @@ -259,12 +261,14 @@ void queryAccountPresenceTenantRoleReturnsMappedSnapshots() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); - Mockito.when(accountPresenceQueryService.queryAccountPresence(1L, 42L, List.of(7L))) + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); + Mockito.when( + accountPresenceQueryService.queryAccountPresence( + 1L, ACCOUNT_VIEWER, List.of(ACCOUNT_TARGET))) .thenReturn( List.of( new AccountPresenceSnapshot( - 7L, + ACCOUNT_TARGET, true, 9L, "ISOLATED", @@ -295,8 +299,8 @@ void queryAccountPresenceTenantRoleReturnsMappedSnapshots() { service.queryAccountPresence( QueryAccountPresenceRequest.newBuilder() .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("7") + .setViewerAccountId(ACCOUNT_VIEWER) + .addAccountIds(ACCOUNT_TARGET) .build(), new StreamObserver<>() { @Override @@ -314,7 +318,7 @@ public void onCompleted() {} }); assertEquals(1, ref.get().getPresencesCount()); - assertEquals("7", ref.get().getPresences(0).getAccountId()); + assertEquals(ACCOUNT_TARGET, ref.get().getPresences(0).getAccountId()); assertEquals(true, ref.get().getPresences(0).getOnline()); assertEquals("demo", ref.get().getPresences(0).getWorldSlug()); assertEquals("Demo World", ref.get().getPresences(0).getWorldDisplayName()); @@ -332,7 +336,7 @@ public void onCompleted() {} } @Test - void queryAccountPresenceDeniesNumericSelfServiceForCanonicalAccountSubject() { + void queryAccountPresenceRejectsNumericViewerBeforePresenceQuery() { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -343,7 +347,7 @@ void queryAccountPresenceDeniesNumericSelfServiceForCanonicalAccountSubject() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of()); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -361,7 +365,59 @@ void queryAccountPresenceDeniesNumericSelfServiceForCanonicalAccountSubject() { QueryAccountPresenceRequest.newBuilder() .setTenantId("1") .setViewerAccountId("42") - .addAccountIds("42") + .addAccountIds(ACCOUNT_TARGET) + .build(), + new StreamObserver<>() { + @Override + public void onNext(QueryAccountPresenceResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); + Mockito.verifyNoInteractions(accountPresenceQueryService); + } + + @Test + void queryAccountPresenceDeniesValidOtherAccountSelfBinding() { + PingService pingService = Mockito.mock(PingService.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); + TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + AccountPresenceQueryService accountPresenceQueryService = + Mockito.mock(AccountPresenceQueryService.class); + TickService tickService = Mockito.mock(TickService.class); + IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); + GameSessionGrpcService service = + newService( + pingService, + gameInstanceService, + featureFlagService, + textCommandInterpreter, + gameInstanceRepository, + accountPresenceQueryService, + tickService, + meterRegistry, + ipLimiter); + + AtomicReference ref = new AtomicReference<>(); + service.queryAccountPresence( + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(ACCOUNT_TARGET) + .addAccountIds(ACCOUNT_TARGET) .build(), new StreamObserver<>() { @Override @@ -379,7 +435,7 @@ public void onCompleted() {} }); assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); - assertEquals("Numeric account self-service is unavailable", ref.get().getError().getMessage()); + assertEquals("Account access required", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountPresenceQueryService); } @@ -395,7 +451,7 @@ void queryAccountPresenceRejectsMalformedAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -412,8 +468,8 @@ void queryAccountPresenceRejectsMalformedAccountId() { service.queryAccountPresence( QueryAccountPresenceRequest.newBuilder() .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("abc") + .setViewerAccountId(ACCOUNT_VIEWER) + .addAccountIds("not-a-uuid") .build(), new StreamObserver<>() { @Override @@ -431,7 +487,7 @@ public void onCompleted() {} }); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a number", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountPresenceQueryService); } @@ -447,7 +503,7 @@ void queryAccountPresenceRejectsZeroAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -464,8 +520,8 @@ void queryAccountPresenceRejectsZeroAccountId() { service.queryAccountPresence( QueryAccountPresenceRequest.newBuilder() .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("0") + .setViewerAccountId(ACCOUNT_VIEWER) + .addAccountIds("00000000-0000-0000-0000-000000000000") .build(), new StreamObserver<>() { @Override @@ -483,7 +539,7 @@ public void onCompleted() {} }); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountPresenceQueryService); } @@ -499,7 +555,7 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(OWNER_ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -513,9 +569,11 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { ipLimiter); QueryAccountPresenceRequest.Builder request = - QueryAccountPresenceRequest.newBuilder().setTenantId("1").setViewerAccountId("42"); + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(ACCOUNT_VIEWER); for (int index = 0; index < 101; index++) { - request.addAccountIds(index == 100 ? "not-a-number" : Long.toString(index + 1L)); + request.addAccountIds(index == 100 ? "not-a-uuid" : ACCOUNT_TARGET); } AtomicReference ref = new AtomicReference<>(); 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 195ca5e0e2..6790b36102 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 @@ -7,7 +7,7 @@ class GameplayPresenceRoleClassifierTest { @Test - void classifyRoleReturnsPlayerUntilFreshGameplayGrantEvidenceIsModeled() { + void classifyRoleRemainsPlayerUntilFreshGameplayGrantEvidenceIsModeled() { assertEquals(GameplayPresenceRole.PLAYER, GameplayPresenceRoleClassifier.classifyRole()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java index 750152a7c9..26f49e334d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java @@ -24,6 +24,7 @@ import org.springframework.data.redis.core.ValueOperations; class RedisAccountRecentPresenceServiceTest { + private static final String ACCOUNT_ID = "a8e3cf57-7d4e-44bd-8f4e-77c7fa18df10"; @Test void recordDisconnectPersistsRoutingBundleFromLivePresence() { @@ -43,7 +44,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -65,7 +66,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { "demo", "production", 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -90,12 +91,15 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); assertEquals(22L, state.tenantId()); - assertEquals(123L, state.accountId()); + assertEquals(ACCOUNT_ID, state.accountId()); assertEquals(101L, state.gameInstanceId()); assertEquals("demo", state.worldSlug()); assertEquals("production", state.realmSlug()); @@ -122,7 +126,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -144,7 +148,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() "demo", "production", 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -170,7 +174,10 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -198,7 +205,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -220,7 +227,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe "demo", "production", 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -246,7 +253,10 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -274,7 +284,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -296,7 +306,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() "demo", null, 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -322,7 +332,10 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java index 3ceca2deb6..e85e285595 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java @@ -22,6 +22,8 @@ @SuppressWarnings("unchecked") class RedisFirstPartyConnectContextRegistryTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private final ConcurrentMap store = new ConcurrentHashMap<>(); private final RedisTemplate redisTemplate = mock(RedisTemplate.class); private final ValueOperations valueOperations = mock(ValueOperations.class); @@ -56,7 +58,16 @@ void setUp() { void registerStoresContextWithShortTtl() { FirstPartyConnectContext context = new FirstPartyConnectContext( - 77L, 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + ACCOUNT_ID, + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); registry.register(91L, context); @@ -73,7 +84,16 @@ void registerStoresContextWithShortTtl() { void unregisterRemovesStoredContext() { FirstPartyConnectContext context = new FirstPartyConnectContext( - 77L, 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + ACCOUNT_ID, + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); registry.register(91L, context); registry.unregister(91L); 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 730ef45c72..9a2147a263 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,8 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.verify; @@ -16,14 +18,19 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class RedisGameplayPresenceServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String ACCOUNT_PLAYER = "6b56d98a-f6cd-4e39-9db9-111b9f8c6aa1"; + private static final String ACCOUNT_GOD = "4f41b943-39b1-4b0f-80f6-fc9229df0712"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -42,7 +49,8 @@ void setUp() { @Test void registerConnectedStoresPresenceAndIndexesByGameInstance() { SessionContext context = - new SessionContext(1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", null); + new SessionContext( + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", null); service.registerConnected(context); @@ -57,16 +65,17 @@ void registerConnectedStoresPresenceAndIndexesByGameInstance() { .equals("Ben")), org.mockito.Mockito.eq(TTL)); verify(setOperations).add("gameplaypresence:22:7:sessions", "1"); - verify(setOperations).add("gameplaypresence:22:account:102:sessions", "1"); + verify(setOperations).add("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", "1"); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", TTL); } @Test void registerConnectedClassifiesInvalidJwtAsPlayer() { SessionContext context = new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); service.registerConnected(context); @@ -86,17 +95,12 @@ void registerConnectedClassifiesInvalidJwtAsPlayer() { void registerConnectedDoesNotElevateTenantRoleClaimsWithoutGrantEvidence() { String tenantAdminJwt = jwtUtil.generateToken( - "102", - Map.of( - "accountId", - "102", - "scopedRoles", - Map.of("22", List.of("tenantAdmin", "moderator", "god")))); - SessionContext context = + ACCOUNT_GOD, + Map.of("accountId", ACCOUNT_GOD, "scopedRoles", Map.of("22", List.of("god")))); + SessionContext godContext = new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", tenantAdminJwt); - - service.registerConnected(context); + 1L, 22L, ACCOUNT_GOD, "god@example.com", 101L, "Aster", 7L, "R-1", tenantAdminJwt); + service.registerConnected(godContext); verify(valueOperations) .set( @@ -124,7 +128,7 @@ void listConnectedByGameInstanceDemotesCachedElevationAndPrunesMissingSessions() "demo", "production", 17L, - 1L, + ACCOUNT_GOD, 101L, "Aster", GameplayPresenceRole.GOD, @@ -163,7 +167,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { 7L, "demo", "production", - 1L, + ACCOUNT_GOD, 101L, "Aster", GameplayPresenceRole.PLAYER, @@ -179,6 +183,35 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { verify(setOperations).remove("gameplaypresence:22:7:sessions", "not-a-session"); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void listConnectedByGameInstancePreservesIndexForUnreadablePresence( + boolean serializationFailure) { + String indexKey = "gameplaypresence:22:7:sessions"; + when(setOperations.members(indexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenThrow(unreadablePresenceFailure(serializationFailure)); + + var result = service.listConnectedByGameInstance(22L, 7L); + + assertEquals(List.of(), result); + verify(setOperations, Mockito.never()).remove(indexKey, "5"); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void listConnectedByAccountIdsPreservesIndexForUnreadablePresence(boolean serializationFailure) { + String indexKey = "gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions"; + when(setOperations.members(indexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenThrow(unreadablePresenceFailure(serializationFailure)); + + var result = service.listConnectedByAccountIds(22L, List.of(ACCOUNT_PLAYER)); + + assertEquals(Map.of(), result); + verify(setOperations, Mockito.never()).remove(indexKey, "5"); + } + @Test void removeBySessionIdRemovesValueAndSetMembership() { when(valueOperations.get("gameplaypresence:session:3")) @@ -189,7 +222,7 @@ void removeBySessionIdRemovesValueAndSetMembership() { 7L, "demo", "production", - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -202,7 +235,54 @@ void removeBySessionIdRemovesValueAndSetMembership() { verify(redisTemplate).delete("gameplaypresence:session:3"); verify(setOperations).remove("gameplaypresence:22:7:sessions", "3"); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "3"); + verify(setOperations) + .remove("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", "3"); + } + + @Test + void removeBySessionIdPreservesUnreadableRetainedPresence() { + String key = "gameplaypresence:session:5"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + + assertThrows(SerializationException.class, () -> service.removeBySessionId(5L)); + + verifyNoPresenceMutations(key); + } + + @Test + void removeBySessionIdPreservesWrongTypeRetainedPresence() { + String key = "gameplaypresence:session:5"; + when(valueOperations.get(key)).thenReturn(42L); + + assertThrows(ClassCastException.class, () -> service.removeBySessionId(5L)); + + verifyNoPresenceMutations(key); + } + + @Test + void registerConnectedDoesNotOverwriteUnreadableRetainedPresence() { + String key = "gameplaypresence:session:1"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", null); + + assertThrows(SerializationException.class, () -> service.registerConnected(context)); + + verifyNoPresenceMutations(key); + } + + @Test + void registerConnectedDoesNotOverwriteWrongTypeRetainedPresence() { + String key = "gameplaypresence:session:1"; + when(valueOperations.get(key)).thenReturn(42L); + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", null); + + assertThrows(ClassCastException.class, () -> service.registerConnected(context)); + + verifyNoPresenceMutations(key); } @Test @@ -217,7 +297,7 @@ void findConnectedBySessionIdDemotesCachedElevationWithoutWritingOrRefreshingTtl "demo", "production", 17L, - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.ADMIN, @@ -243,6 +323,32 @@ void findConnectedBySessionIdDemotesCachedElevationWithoutWritingOrRefreshingTtl .expire(Mockito.anyString(), Mockito.any(Duration.class)); } + @Test + void unreadableLegacyPresenceFailsClosedWithoutDeletingRetainedValue() { + String key = "gameplaypresence:session:5"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + + var presence = service.findConnectedBySessionId(5L); + + assertFalse(presence.isPresent()); + Mockito.verify(redisTemplate, Mockito.never()).delete(key); + } + + private void verifyNoPresenceMutations(String presenceKey) { + verify(redisTemplate, Mockito.never()).delete(presenceKey); + verify(redisTemplate, Mockito.never()).expire(Mockito.anyString(), Mockito.any(Duration.class)); + verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + verify(setOperations, Mockito.never()).add(Mockito.anyString(), Mockito.any()); + verify(setOperations, Mockito.never()).remove(Mockito.anyString(), Mockito.any()); + } + + private static RuntimeException unreadablePresenceFailure(boolean serializationFailure) { + return serializationFailure + ? new SerializationException("legacy record") + : new ClassCastException("legacy record"); + } + @Test void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequested() { AtomicLong now = new AtomicLong(100L); @@ -255,7 +361,7 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest 7L, "demo", "production", - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.ADMIN, @@ -286,7 +392,8 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", TTL); } @Test @@ -301,7 +408,7 @@ void setExplicitAfkRefreshesPresenceRecord() { 7L, "demo", "production", - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.MODERATOR, @@ -335,12 +442,13 @@ void setExplicitAfkRefreshesPresenceRecord() { == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", TTL); } @Test void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("3", "4"))); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( @@ -352,7 +460,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.ADMIN, @@ -370,7 +478,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.GOD, @@ -379,15 +487,15 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of(102L)); + var result = service.listConnectedByAccountIds(22L, List.of(ACCOUNT_PLAYER)); assertEquals(1, result.size()); - assertEquals(2, result.get(102L).size()); + assertEquals(2, result.get(ACCOUNT_PLAYER).size()); + assertEquals(4L, result.get(ACCOUNT_PLAYER).get(0).sessionId()); + assertEquals(3L, result.get(ACCOUNT_PLAYER).get(1).sessionId()); assertTrue( - result.get(102L).stream() + result.get(ACCOUNT_PLAYER).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()) @@ -396,7 +504,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { @Test void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("bad-session", "4"))); when(valueOperations.get("gameplaypresence:session:4")) .thenReturn( @@ -408,7 +516,7 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { "demo", "production", 17L, - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -417,11 +525,12 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of(102L)); + var result = service.listConnectedByAccountIds(22L, List.of(ACCOUNT_PLAYER)); assertEquals(1, result.size()); - assertEquals(1, result.get(102L).size()); - assertEquals(4L, result.get(102L).get(0).sessionId()); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "bad-session"); + assertEquals(1, result.get(ACCOUNT_PLAYER).size()); + assertEquals(4L, result.get(ACCOUNT_PLAYER).get(0).sessionId()); + verify(setOperations) + .remove("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", "bad-session"); } } 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 e04525b15a..88e29513af 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 @@ -57,7 +57,7 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() throws Exception { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -103,7 +103,9 @@ void applyReturnsConflictWhenGameplayIdentityMismatch() { SessionContext current = baselineContext(); when(valueOperations.get("sessionctx:22:41:context")).thenReturn(current); when(valueOperations.get("sessionctx:22:41:movement-effect:tfx-1")).thenReturn(null); - MoveEffectApplyResult result = service.apply("tfx-1", withAccountId(current, 999L), "R-2045"); + MoveEffectApplyResult result = + service.apply( + "tfx-1", withAccountId(current, "11111111-1111-4111-8111-111111111111"), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); assertEquals(current.withoutJwt(), result.context()); @@ -171,7 +173,7 @@ private SessionContext baselineContext() { return new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -186,7 +188,7 @@ private SessionContext baselineContext() { "SHARED"); } - private SessionContext withAccountId(SessionContext context, long accountId) { + private SessionContext withAccountId(SessionContext context, String accountId) { return new SessionContext( context.sessionId(), context.tenantId(), 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 85ec4718f4..5f1f59c396 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 @@ -5,6 +5,7 @@ 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.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -23,11 +24,13 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; @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 static final String ACCOUNT_ID = "22b7315e-204f-4d9f-85df-975c3fce8e7f"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -49,7 +52,7 @@ void setUp() { @Test void saveStoresContextInSessionAndIdentityKeys() throws Exception { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); service.save(context); @@ -70,8 +73,8 @@ void saveStoresContextInSessionAndIdentityKeys() throws Exception { @Test void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { - SessionContext existing = new SessionContext(1L, 10L, 20L, 30L, 40L, "old-jwt"); - SessionContext replacement = new SessionContext(2L, 10L, 20L, 30L, 40L, "new-jwt"); + SessionContext existing = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, "old-jwt"); + SessionContext replacement = new SessionContext(2L, 10L, ACCOUNT_ID, 30L, 40L, "new-jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(existing); service.save(replacement); @@ -84,7 +87,7 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { @Test void findByTenantAndSessionIdProjectsLegacyJwtOut() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); Optional result = service.findByTenantAndSessionId(10L, 1L); @@ -95,7 +98,7 @@ void findByTenantAndSessionIdProjectsLegacyJwtOut() { @Test void findBySessionIdProjectsLegacyJwtOut() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(context); Optional result = service.findBySessionId(1L); @@ -106,7 +109,7 @@ void findBySessionIdProjectsLegacyJwtOut() { @Test void findByGameplayIdentityProjectsLegacyJwtOut() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(context); Optional result = service.findByGameplayIdentity(10L, 40L, 30L); @@ -121,7 +124,7 @@ void findByGameplayNameProjectsLegacyJwtOut() { new SessionContext( 1L, 10L, - 20L, + ACCOUNT_ID, "demo", 30L, "Hero", @@ -142,9 +145,19 @@ void findByGameplayNameProjectsLegacyJwtOut() { assertNull(result.orElseThrow().jwt()); } + @Test + void unreadableLegacyContextFailsClosedWithoutDeletingRetainedValue() { + String key = "sessionctx:10:1:context"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + + assertEquals(Optional.empty(), service.findByTenantAndSessionId(10L, 1L)); + + verify(redisTemplate, never()).delete(key); + } + @Test void deleteBySessionIdRemovesBothKeys() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); service.deleteBySessionId(10L, 1L); @@ -158,7 +171,7 @@ void deleteBySessionIdRemovesBothKeys() { @Test void savePreservesLocaleTagInStoredContext() { SessionContext context = - new SessionContext(1L, 10L, 20L, null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); + new SessionContext(1L, 10L, ACCOUNT_ID, null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); service.save(context); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java index 1a01de632f..6f12e16184 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java @@ -717,7 +717,7 @@ void pauseAndResumeTicksForGameInstanceBumpOwnershipEpochAndPauseFlag() { @Test void queryStateUsesSessionContextTenantFromSessionAuthority() { when(sessionAuthenticationService.resolveUnverifiedSessionContext("7")) - .thenReturn(Optional.of(new SessionContext(7L, 11L, 0L, 0L, 0L, null))); + .thenReturn(Optional.of(new SessionContext(7L, 11L, null, 0L, 0L, null))); when(valueOps.get("session:11:7")).thenReturn("{\"status\":\"ready\"}"); String state = service.queryState(7L); @@ -739,7 +739,7 @@ void queryStateFailsClosedWhenSessionContextMissing() { @Test void queryStateFailsClosedWhenSessionContextHasNoTenantAuthority() { when(sessionAuthenticationService.resolveUnverifiedSessionContext("7")) - .thenReturn(Optional.of(new SessionContext(7L, 0L, 0L, 0L, 0L, null))); + .thenReturn(Optional.of(new SessionContext(7L, 0L, null, 0L, 0L, null))); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> service.queryState(7L)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 30af581f9c..d9296dd529 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -14,6 +14,11 @@ import org.junit.jupiter.api.Test; class EntityManagementStubServerTest { + private static final String FIRST_LOAD_ACTOR_ACCOUNT_UUID = + "a9fb0a44-93f0-4db2-9cf5-4de573beefb0"; + private static final String SECOND_LOAD_ACTOR_ACCOUNT_UUID = + "dbbf7ca8-a01f-4f8f-8d82-669e7a083ae7"; + private static final String UNKNOWN_ACCOUNT_UUID = "eb8ad310-10e3-4c07-8aa5-bdcb50a78fb3"; @Test void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throws Exception { @@ -26,9 +31,9 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw for (FixtureCharacter fixture : List.of( - new FixtureCharacter("7", "Emberline"), - new FixtureCharacter("8", "Sora"), - new FixtureCharacter("9", "Nyx"))) { + new FixtureCharacter(ChatTestFixtures.ACCOUNT_UUID_EMBERLINE, "Emberline"), + new FixtureCharacter(ChatTestFixtures.ACCOUNT_UUID_SORA, "Sora"), + new FixtureCharacter(ChatTestFixtures.ACCOUNT_UUID_NYX, "Nyx"))) { ListCharactersByAccountResponse response = listCharacters( stub, "1", fixture.accountId(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -48,14 +53,14 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { Character.newBuilder() .setId("101") .setTenantId("1") - .setAccountId("101") + .setAccountId(FIRST_LOAD_ACTOR_ACCOUNT_UUID) .setName("player-1") .build(); Character secondPlayer = Character.newBuilder() .setId("102") .setTenantId("1") - .setAccountId("102") + .setAccountId(SECOND_LOAD_ACTOR_ACCOUNT_UUID) .setName("player-2") .build(); @@ -68,15 +73,27 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + FIRST_LOAD_ACTOR_ACCOUNT_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(firstPlayer)); assertThat( - listCharacters(stub, "1", "102", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + SECOND_LOAD_ACTOR_ACCOUNT_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(secondPlayer)); assertThat( - listCharacters(stub, "2", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "2", + FIRST_LOAD_ACTOR_ACCOUNT_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -86,7 +103,7 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { } @Test - void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { + void unknownAccountAndCrossTenantRequestsReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); @@ -95,11 +112,19 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "2", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "2", + ChatTestFixtures.ACCOUNT_UUID_EMBERLINE, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + UNKNOWN_ACCOUNT_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -118,11 +143,19 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + listCharacters( + stub, + "1", + ChatTestFixtures.ACCOUNT_UUID_EMBERLINE, + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + listCharacters( + stub, + "1", + ChatTestFixtures.ACCOUNT_UUID_EMBERLINE, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .getCharactersList()) .isEmpty(); } finally { 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 bce7cde3e0..e8634e3d6d 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 @@ -49,6 +49,8 @@ import org.springframework.web.socket.WebSocketSession; class GameSessionWebSocketHandlerTest { + private static final String FIRST_PARTY_ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private final TextCommandInterpreter interpreter = Mockito.mock(TextCommandInterpreter.class); private final LookCommandHandler lookHandler = Mockito.mock(LookCommandHandler.class); private final SessionAuthenticationService sessionAuthenticationService = @@ -139,7 +141,16 @@ void afterConnectionEstablishedRegistersValidFirstPartyConnectContext() { "token")); FirstPartyConnectContext connectContext = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); + FIRST_PARTY_ACCOUNT_ID, + 22L, + "demo", + "production", + 7L, + 3L, + "scope-1", + "jti", + "req-1", + "gw-1"); when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( @@ -216,7 +227,16 @@ void afterConnectionEstablishedClosesWithServiceUnavailableWhenPointerAuthorityF "token")); FirstPartyConnectContext connectContext = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); + FIRST_PARTY_ACCOUNT_ID, + 22L, + "demo", + "production", + 7L, + 3L, + "scope-1", + "jti", + "req-1", + "gw-1"); when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenThrow(new IllegalStateException("database unavailable")); @@ -472,7 +492,7 @@ void afterConnectionEstablishedDropsPartialRoutingTupleWhenRuntimeAuthorityIsAmb .save( eq( new SessionContext( - 41L, 22L, 0L, null, 0L, null, 0L, null, null, null, 7L, null, null, 0L, null, + 41L, 22L, null, null, 0L, null, 0L, null, null, null, 7L, null, null, 0L, null, null, null))); } @@ -603,7 +623,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "Emberline", @@ -652,7 +672,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority context -> context.sessionId() == 41L && context.tenantId() == 22L - && context.accountId() == 0L + && context.accountId() == null && context.bootstrapGameInstanceId() == 7L && "demo".equals(context.worldSlug()) && "production".equals(context.realmSlug()) @@ -667,7 +687,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "Emberline", @@ -729,7 +749,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority context -> context.sessionId() == 41L && context.tenantId() == 22L - && context.accountId() == 0L + && context.accountId() == null && context.bootstrapGameInstanceId() == 7L && context.worldSlug() == null && context.realmSlug() == null @@ -759,7 +779,17 @@ void handleMessageDoesNotAppendScreenBufferForNormalizedLoggedInShell() throws E PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -794,7 +824,17 @@ void handleMessageDoesNotAppendScreenBufferForPartialGameplayIdentityShell() thr PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext partialShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -829,7 +869,17 @@ void handleMessageForcesPromptBurstByUiActionMetadata() throws Exception { PlayerOutput output = PlayerOutput.message("Presence: online in Demo World / Live Realm"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(parser.parse("WHO")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -866,7 +916,17 @@ void handleMessageForcesPromptBurstForGameplayEntryMetadata() throws Exception { PlayerOutput output = PlayerOutput.message("Entering Demo World"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -910,7 +970,17 @@ void handleMessageDoesNotForcePromptBurstForPlayTypeWithoutGameplayEntryMetadata PlayerOutput output = PlayerOutput.message("Custom session response"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(parser.parse("CUSTOM-PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -947,7 +1017,17 @@ void handleMessageKeepsNonUiCommunicationUnderNormalPromptBurstPolicy() throws E WebSocketSession decoratedSession = Mockito.mock(WebSocketSession.class); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(session.getId()).thenReturn("session-41"); when(decoratedSession.getId()).thenReturn("session-41"); when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.of(decoratedSession)); @@ -995,7 +1075,17 @@ void handleMessageDoesNotReplayReconnectBufferForNormalizedLoggedInShell() throw TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1026,7 +1116,17 @@ void handleMessageDoesNotReplayReconnectBufferForPartialGameplayIdentityShell() TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext partialShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 1L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 1L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1057,7 +1157,17 @@ void freshFirstPartyPlayDoesNotReplayRetainedBufferFromAnEarlierLogout() throws 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); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(session.getAttributes()) .thenReturn( Map.of( @@ -1104,7 +1214,17 @@ void genericReconnectPlayEmitsFreshLookAndConfiguredPromptWithoutRetainedBufferR 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); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); PresentationProperties presentation = new PresentationProperties( "en-NZ", @@ -1169,7 +1289,17 @@ void reconnectPlayEmitsPromptOnlyWhenBothPromptSettingsAreEnabled( 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); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); PresentationProperties presentation = new PresentationProperties( "en-NZ", @@ -1227,7 +1357,17 @@ void handleMessageUsesTenantScopedSessionContextWhenTenantAttributePresent() thr PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1415,7 +1555,21 @@ void handleMessageRebootsGenericSessionContextWhenSessionIndexLookupIsMissing() "LOGIN demo@example.com swordfish"); SessionContext tenantScoped = new SessionContext( - 41L, 22L, 0L, null, 0L, null, 0L, null, null, null, 7L, "demo", "production", 3L, null); + 41L, + 22L, + null, + null, + 0L, + null, + 0L, + null, + null, + null, + 7L, + "demo", + "production", + 3L, + null); when(parser.parse("LOGIN demo@example.com swordfish")).thenReturn(command); when(sessionAuthenticationService.resolveUnverifiedSessionContext(22L, 41L)) .thenReturn(Optional.of(tenantScoped)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index 568f75a2b2..7fb6ded63a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -43,6 +43,10 @@ import org.springframework.web.socket.WebSocketSession; class WebSocketOutputProjectorTest { + private static final String SORA_ACCOUNT_ID = "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30"; + private static final String EMBERLINE_ACCOUNT_ID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + private static final String NYX_ACCOUNT_ID = "3a16e242-3467-4d98-906f-71d47b888b5e"; + private static final String REDACTED_FRIEND_ACCOUNT_ID = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; private final PresentationProperties presentation = new PresentationProperties(); private final ObjectMapper objectMapper = new ObjectMapper(); @@ -234,7 +238,15 @@ void firstPartyWebUsesAdmittedMetadataForAuthoredCommand() throws Exception { GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); AdmittedTextCommandRegistryResolver admittedResolver = mock(AdmittedTextCommandRegistryResolver.class); when(admittedResolver.resolveMetadata(context, "wave", "wave")) @@ -332,7 +344,7 @@ void genericWebSocketProjectsFriendViewThroughFriendsRenderer() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + SORA_ACCOUNT_ID, "ONLINE", null, "Sora", @@ -495,7 +507,7 @@ void firstPartyWebProjectsFriendsViewPayloads(String filter) throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + SORA_ACCOUNT_ID, "active", 1_744_336_000_000L, "Sora", @@ -536,8 +548,8 @@ void firstPartyWebProjectsFriendsViewPayloads(String filter) throws Exception { .path("friends") .get(0) .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo(SORA_ACCOUNT_ID); assertThat( json.path("outputs") .get(0) @@ -630,7 +642,7 @@ void firstPartyWebOmitsDisconnectDispositionForPublicAndFriendsOnlyPresence() th new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + EMBERLINE_ACCOUNT_ID, "active", null, "Public Friend", @@ -648,7 +660,7 @@ void firstPartyWebOmitsDisconnectDispositionForPublicAndFriendsOnlyPresence() th new FriendPresenceViewOutput.Entry( 2, 12L, - 4L, + NYX_ACCOUNT_ID, "active", null, "Friends-only Friend", @@ -695,7 +707,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + SORA_ACCOUNT_ID, "active", 1_744_336_000_000L, "Sora", @@ -716,7 +728,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + SORA_ACCOUNT_ID, "active", 1_744_336_000_000L, "Sora", @@ -744,8 +756,8 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { .path("payload") .path("friend") .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo(SORA_ACCOUNT_ID); assertThat( json.path("outputs") .get(0) @@ -776,10 +788,10 @@ void firstPartyWebOmitsRedactedFriendPresenceFields() throws Exception { new FriendPresenceViewOutput.Entry( 4, 12L, - 77L, + REDACTED_FRIEND_ACCOUNT_ID, "active", 1_744_336_000_000L, - "Friend #77", + "Friend #" + REDACTED_FRIEND_ACCOUNT_ID, null, null, null, @@ -800,10 +812,11 @@ void firstPartyWebOmitsRedactedFriendPresenceFields() throws Exception { JsonNode friend = objectMapper.readTree(payload).path("outputs").get(0).path("payload").path("friend"); - assertThat(friend.path("friendAccountId").asLong()).isEqualTo(77L); + assertThat(friend.path("friendAccountId").asText()).isEqualTo(REDACTED_FRIEND_ACCOUNT_ID); assertThat(friend.path("friendLinkId").asLong()).isEqualTo(12L); assertThat(friend.path("status").asText()).isEqualTo("active"); - assertThat(friend.path("displayName").asText()).isEqualTo("Friend #77"); + assertThat(friend.path("displayName").asText()) + .isEqualTo("Friend #" + REDACTED_FRIEND_ACCOUNT_ID); assertThat(friend.has("online")).isFalse(); assertThat(friend.has("worldSlug")).isFalse(); assertThat(friend.has("characterName")).isFalse(); @@ -888,7 +901,7 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); FriendMutationResultOutput payloadView = - new FriendMutationResultOutput("REMOVE", 77L, "Sora", "Sora", 1); + new FriendMutationResultOutput("REMOVE", SORA_ACCOUNT_ID, "Sora", "Sora", 1); String payload = projector.projectCommandResponse( @@ -906,8 +919,8 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { .isEqualTo("friend_mutation_result"); assertThat(json.path("outputs").get(0).path("payload").path("action").asText()) .isEqualTo("REMOVE"); - assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asLong()) - .isEqualTo(77L); + assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asText()) + .isEqualTo(SORA_ACCOUNT_ID); assertThat(json.path("outputs").get(0).path("payload").path("displayName").asText()) .isEqualTo("Sora"); assertThat(json.path("outputs").get(0).path("payload").path("ordinal").asInt()).isEqualTo(1); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index da1f1446c4..611ac65414 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -216,7 +216,7 @@ ModerationPolicyClient moderationPolicyClient() { ModerationPolicyClient client = org.mockito.Mockito.mock(ModerationPolicyClient.class); org.mockito.Mockito.when( client.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index ea04481043..3e33f9e3a4 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -22,21 +22,21 @@ public final class RuntimeMembershipTestFixtures { private RuntimeMembershipTestFixtures() {} public static GetTenantMembershipForRuntimeResponse active( - long accountId, long tenantId, String membershipVersion) { + String accountId, long tenantId, String membershipVersion) { return complete(accountId, tenantId, true, "ACTIVE", true, membershipVersion); } - public static GetTenantMembershipForRuntimeResponse missing(long accountId, long tenantId) { + public static GetTenantMembershipForRuntimeResponse missing(String accountId, long tenantId) { return complete(accountId, tenantId, false, "MISSING", false, "1"); } public static GetTenantMembershipForRuntimeResponse inactive( - long accountId, long tenantId, String membershipVersion) { + String accountId, long tenantId, String membershipVersion) { return complete(accountId, tenantId, true, "INACTIVE", false, membershipVersion); } public static GetTenantMembershipForRuntimeResponse left( - long accountId, long tenantId, List retainedRoles) { + String accountId, long tenantId, List retainedRoles) { return complete( accountId, tenantId, true, "INACTIVE", false, "3", "2", "2", "2", true, retainedRoles); } @@ -47,20 +47,20 @@ public static GetTenantMembershipForRuntimeResponse echoRequestId( } public static GetTenantMembershipForRuntimeResponse incomplete( - long accountId, + String accountId, long tenantId, boolean membershipExists, String lifecycle, boolean gameplayAdmissionAllowed, String membershipVersion, String evaluatedAt) { - String accountUuid = uuid(accountId); + String accountUuid = accountId; String tenantUuid = uuid(tenantId); GetTenantMembershipForRuntimeResponse.Builder response = GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(accountUuid) .setTenantId(tenantUuid) - .setRequestAccountId(Long.toString(accountId)) + .setRequestAccountId(accountId) .setRequestTenantId(Long.toString(tenantId)) .setMembershipExists(membershipExists) .setMembershipLifecycleState(lifecycle) @@ -73,7 +73,7 @@ public static GetTenantMembershipForRuntimeResponse incomplete( } public static GetTenantMembershipForRuntimeResponse advancedTenantWithZeroCheckpoint( - long accountId, long tenantId) { + String accountId, long tenantId) { GetTenantMembershipForRuntimeResponse response = active(accountId, tenantId, "1"); return response.toBuilder() .setAuthorityTuple( @@ -83,7 +83,7 @@ public static GetTenantMembershipForRuntimeResponse advancedTenantWithZeroCheckp } private static GetTenantMembershipForRuntimeResponse complete( - long accountId, + String accountId, long tenantId, boolean exists, String lifecycle, @@ -104,7 +104,7 @@ private static GetTenantMembershipForRuntimeResponse complete( } private static GetTenantMembershipForRuntimeResponse complete( - long accountId, + String accountId, long tenantId, boolean exists, String lifecycle, @@ -115,7 +115,7 @@ private static GetTenantMembershipForRuntimeResponse complete( String outboxSequence, boolean callerBoundAuthorityInvalidated, List roles) { - String accountUuid = uuid(accountId); + String accountUuid = accountId; String tenantUuid = uuid(tenantId); String membershipStream = STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; List checkpoints = @@ -144,7 +144,7 @@ private static GetTenantMembershipForRuntimeResponse complete( GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(accountUuid) .setTenantId(tenantUuid) - .setRequestAccountId(Long.toString(accountId)) + .setRequestAccountId(accountId) .setRequestTenantId(Long.toString(tenantId)) .setAuthorityAvailability("AVAILABLE") .setMembershipExists(exists) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java index 5c92ce6ff3..7804fbbd36 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java @@ -11,6 +11,9 @@ public final class ChatTestFixtures { public static final String PLAYER_EMBERLINE = "7"; public static final String PLAYER_SORA = "8"; public static final String PLAYER_NYX = "9"; + public static final String ACCOUNT_UUID_EMBERLINE = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + public static final String ACCOUNT_UUID_SORA = "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30"; + public static final String ACCOUNT_UUID_NYX = "3a16e242-3467-4d98-906f-71d47b888b5e"; private ChatTestFixtures() {} @@ -57,7 +60,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_EMBERLINE) .setTenantId("1") - .setAccountId("7") + .setAccountId(ACCOUNT_UUID_EMBERLINE) .setName("Emberline") .build(); } @@ -65,7 +68,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_SORA) .setTenantId("1") - .setAccountId("8") + .setAccountId(ACCOUNT_UUID_SORA) .setName("Sora") .build(); } @@ -73,7 +76,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_NYX) .setTenantId("1") - .setAccountId("9") + .setAccountId(ACCOUNT_UUID_NYX) .setName("Nyx") .build(); } 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 c93a05d1cb..5ae98413a6 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 @@ -6,6 +6,9 @@ import java.io.IOException; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.ContainerItem; @@ -68,6 +71,8 @@ public final class EntityManagementStubServer implements AutoCloseable { new AtomicReference<>(LookTestFixtures.sampleEntities()); private final AtomicReference lastListCharactersByAccountRequest = new AtomicReference<>(); + private final ConcurrentMap + syntheticCharactersByAccountUuid = new ConcurrentHashMap<>(); private final AtomicReference actorState = new AtomicReference<>(QueryActorStateResponse.getDefaultInstance()); private boolean torchOnGround = true; @@ -269,10 +274,54 @@ public void resetCharacterRosterState() { lastListCharactersByAccountRequest.set(null); } + public void registerCharacterForAccountUuid( + String accountUuid, net.firedevops.firemud.entitymanagement.v1.Character character) { + String canonicalAccountUuid = requireCanonicalAccountUuid(accountUuid); + if (character == null + || !canonicalAccountUuid.equals(character.getAccountId()) + || character.getId().isBlank()) { + throw new IllegalArgumentException("synthetic character must be bound to its Account UUID"); + } + syntheticCharactersByAccountUuid.put(canonicalAccountUuid, character.toBuilder().build()); + } + + public void resetSyntheticAccountCharacters() { + syntheticCharactersByAccountUuid.clear(); + } + public Optional lastListCharactersByAccountRequest() { return Optional.ofNullable(lastListCharactersByAccountRequest.get()); } + private net.firedevops.firemud.entitymanagement.v1.Character characterForAccount( + String accountUuid) { + net.firedevops.firemud.entitymanagement.v1.Character fixedCharacter = + switch (accountUuid) { + case ChatTestFixtures.ACCOUNT_UUID_EMBERLINE -> + ChatTestFixtures.characterByName("Emberline"); + case ChatTestFixtures.ACCOUNT_UUID_SORA -> ChatTestFixtures.characterByName("Sora"); + case ChatTestFixtures.ACCOUNT_UUID_NYX -> ChatTestFixtures.characterByName("Nyx"); + default -> null; + }; + if (fixedCharacter != null) { + return fixedCharacter; + } + return syntheticCharactersByAccountUuid.get(requireCanonicalAccountUuid(accountUuid)); + } + + private static String requireCanonicalAccountUuid(String accountUuid) { + try { + UUID parsed = UUID.fromString(accountUuid); + if ((parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) + || !parsed.toString().equals(accountUuid)) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil"); + } + return accountUuid; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil", exception); + } + } + private static List defaultCharacters() { return List.of("Emberline", "Sora", "Nyx").stream() .map(ChatTestFixtures::characterByName) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 8f492d97ce..bc5f3e3270 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -64,7 +64,7 @@ public final class GameplayCrossServiceStack implements AutoCloseable { private final net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse baselineRoomEntities; private final ListFriendPresenceResponse baselineFriendPresenceResponse; - private final Map syntheticManagementOwnerUuids = new HashMap<>(); + private final Map syntheticManagementOwnerUuidsBySelector = new HashMap<>(); private CrossServiceAppHarness.GameLogicHolder gameLogic; private final CrossServiceAppHarness.GameSessionHolder gameSession; private final boolean useDefaultDemoCatalogFixture; @@ -97,7 +97,7 @@ public static Builder builder() { } public static Builder defaultDemoBuilder( - PostgreSQLContainer postgres, GenericContainer redis, long defaultAccountId) { + PostgreSQLContainer postgres, GenericContainer redis, String defaultAccountUuid) { Builder builder = builder() .withPostgres( @@ -107,7 +107,7 @@ public static Builder defaultDemoBuilder( postgres.getUsername(), postgres.getPassword()) .withRedis(redis.getHost(), redis.getMappedPort(6379)) - .withDefaultAccountId(defaultAccountId); + .withDefaultAccountUuid(defaultAccountUuid); builder.useDefaultDemoCatalogFixture = true; return builder; } @@ -190,6 +190,7 @@ public void resetScenarioState() { socialStub.setFriendPresenceResponse(baselineFriendPresenceResponse); } } + entityStub.resetSyntheticAccountCharacters(); } public void clearScreenBuffers(long tenantId, long gameInstanceId, long... characterIds) { @@ -202,7 +203,7 @@ public void clearScreenBuffers(long tenantId, long gameInstanceId, long... chara public long freshGameplayBaseline( long tenantId, long gameplayInstanceId, - long ownerAccountId, + long managementOwnerSelector, long gameTemplateId, long... characterIds) { resetScenarioState(); @@ -222,7 +223,7 @@ public long freshGameplayBaseline( jdbc, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); if (useDefaultDemoCatalogFixture) { - bindDefaultDemoPointer(tenantId, gameInstanceId, ownerAccountId, gameTemplateId); + bindDefaultDemoPointer(tenantId, gameInstanceId, managementOwnerSelector, gameTemplateId); } return gameInstanceId; } @@ -855,7 +856,7 @@ public void seedLiveSession(SessionContext context) { public void seedLiveSession( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -878,7 +879,7 @@ public void seedLiveSession( public void seedLiveSession( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -909,7 +910,7 @@ public void seedLiveSession( } public long insertRunningGameInstance( - long tenantId, long accountId, long gameTemplateId, boolean clearExisting) { + long tenantId, long managementOwnerSelector, long gameTemplateId, boolean clearExisting) { JdbcTemplate jdbc = jdbc(); if (clearExisting) { clearRedis(); @@ -920,8 +921,8 @@ public long insertRunningGameInstance( GameInstanceTestFixtures.insertRunningGameInstance( jdbc, tenantId, - syntheticManagementOwnerUuids.computeIfAbsent( - accountId, ignored -> UUID.randomUUID().toString()), + syntheticManagementOwnerUuidsBySelector.computeIfAbsent( + managementOwnerSelector, ignored -> UUID.randomUUID().toString()), gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); return gameInstanceId; @@ -975,12 +976,12 @@ public static final class Builder { private String postgresPassword; private String redisHost; private int redisPort; - private long defaultAccountId = 7L; + private String defaultAccountUuid = "a7e0feac-60ab-4fd1-9002-0ad38d585db0"; private String defaultRoomId = LookTestFixtures.ROOM_ID; private net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse initialRoomEntities; private ListFriendPresenceResponse initialFriendPresenceResponse; private boolean includeSocial; - private final Map accountMappings = new LinkedHashMap<>(); + private final Map accountUuidMappings = new LinkedHashMap<>(); private final Map gameLogicProps = new LinkedHashMap<>(); private final Map gameSessionProps = new LinkedHashMap<>(); private Class[] gameLogicConfigs = new Class[0]; @@ -1005,13 +1006,13 @@ public Builder withRedis(String host, int port) { return this; } - public Builder withDefaultAccountId(long accountId) { - this.defaultAccountId = accountId; + public Builder withDefaultAccountUuid(String accountUuid) { + this.defaultAccountUuid = accountUuid; return this; } - public Builder mapAccountId(String email, long accountId) { - this.accountMappings.put(email, accountId); + public Builder mapAccountUuid(String email, String accountUuid) { + this.accountUuidMappings.put(email, accountUuid); return this; } @@ -1059,8 +1060,8 @@ public Builder withGameSessionConfigs(Class... configs) { public GameplayCrossServiceStack start() throws IOException { requireConfigured(); AccountRuntimeStubServer accountStub = new AccountRuntimeStubServer(0); - accountStub.setDefaultAccountId(defaultAccountId); - accountMappings.forEach(accountStub::mapAccountId); + accountStub.setDefaultAccountUuid(defaultAccountUuid); + accountUuidMappings.forEach(accountStub::mapAccountUuid); GameDesignStubServer gameDesignStub = new GameDesignStubServer(0); WorldManagementStubServer worldStub = new WorldManagementStubServer(0); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index cd9a886fa2..9306b876ca 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; @@ -20,37 +21,39 @@ public static List seedPlayers( GameplayCrossServiceStack stack, long tenantId, long gameplayInstanceId, - long firstAccountId, + long firstCharacterId, int count, long gameTemplateId) { long[] characterIds = new long[count]; for (int i = 0; i < count; i++) { - characterIds[i] = firstAccountId + i + 1; + characterIds[i] = firstCharacterId + i + 1; } stack.freshGameplayBaseline( - tenantId, gameplayInstanceId, firstAccountId, gameTemplateId, characterIds); + tenantId, gameplayInstanceId, firstCharacterId, gameTemplateId, characterIds); // Cross-service test bootstraps reserve runtime target 2 for the built-in sandbox pointer. // Skip that id so demo-player bootstrap instances do not inherit unrelated sandbox authority. - stack.insertRunningGameInstance(tenantId, firstAccountId, gameTemplateId, false); + stack.insertRunningGameInstance(tenantId, firstCharacterId, gameTemplateId, false); List players = new ArrayList<>(); List characters = new ArrayList<>(); for (int i = 0; i < count; i++) { - long accountId = characterIds[i]; + long characterId = characterIds[i]; + String accountUuid = UUID.randomUUID().toString(); String label = "player-" + (i + 1); long bootstrapGameInstanceId = - stack.insertRunningGameInstance(tenantId, accountId, gameTemplateId, false); + stack.insertRunningGameInstance(tenantId, characterId, gameTemplateId, false); // Admission pointers are uniquely identified by world/realm and runtime target. Give each // isolated player target its own world and retain the persisted pointer version for the // matching WebSocket bootstrap headers. - String bootstrapWorldSlug = GameplayCrossServiceStack.SYNTHETIC_LOAD_WORLD_PREFIX + accountId; + String bootstrapWorldSlug = + GameplayCrossServiceStack.SYNTHETIC_LOAD_WORLD_PREFIX + characterId; GameplayAdmissionPointerSnapshot pointer = stack .gameSessionBean(GameplayAdmissionPointerAuthorityService.class) .upsertPointer( new GameplayAdmissionPointerMutation( bootstrapWorldSlug, - "Demo Player " + accountId, + "Demo Player " + characterId, DEFAULT_REALM_SLUG, "Live Realm", tenantId, @@ -62,25 +65,26 @@ public static List seedPlayers( "ALLOW_NEW", GameplayCrossServiceStack.SYNTHETIC_LOAD_ACTOR, "Seed per-player load-test admission pointer", - "load-test:" + accountId, + "load-test:" + characterId, 0L, 0L, null)); - long sessionId = firstAccountId + 10_000L + i + 1; + long sessionId = firstCharacterId + 10_000L + i + 1; String email = "player" + (i + 1) + "@example.com"; - stack.accountStub().mapAccountId(email, accountId); + stack.accountStub().mapAccountUuid(email, accountUuid); characters.add( Character.newBuilder() - .setId(Long.toString(accountId)) + .setId(Long.toString(characterId)) .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountUuid) .setName(label) .build()); players.add( new PlayerSeed( sessionId, bootstrapGameInstanceId, - accountId, + characterId, + accountUuid, email, label, bootstrapWorldSlug, @@ -117,7 +121,8 @@ public static GameplayWebSocketDriver openReadyPlayer( public record PlayerSeed( long sessionId, long bootstrapGameInstanceId, - long accountId, + long characterId, + String accountUuid, String username, String label, String bootstrapWorldSlug, diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java index 9ace5c0d3e..81555f8240 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java @@ -132,7 +132,12 @@ public static GameplayWebSocketDriver connectFirstPartyWeb( String jwtSecret, Map connectClaims) { return connectFirstPartyWeb( - uri, waitTimeout, transportSessionId, jwtSecret, "123", connectClaims); + uri, + waitTimeout, + transportSessionId, + jwtSecret, + "f2ed193b-12c1-4c96-bcad-c162229af440", + connectClaims); } public static GameplayWebSocketDriver connectFirstPartyWeb( 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 f19e0de765..5c2424ce72 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 @@ -66,11 +66,15 @@ class TelnetGatewayGameSessionAccountCrossServiceIntegrationTest { private static final String CROSS_SERVICE_TEST_JWT_SECRET = "stub-secret-key-for-tests-1234567890"; private static final long TENANT_ID = 1L; - private static final long ACCOUNT_ID = 7L; + private static final String ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_EMBERLINE; + private static final long MANAGEMENT_OWNER_SELECTOR = 7L; + private static final long EMBERLINE_CHARACTER_ID = + Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); 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 SORA_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_SORA; + private static final long SORA_CHARACTER_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 String NYX_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_NYX; private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; @@ -127,7 +131,8 @@ static synchronized void stopTestServices() { @BeforeEach void clearSharedRuntimeState() throws Exception { ensureTestServicesStarted(); - STACK.freshGameplayBaseline(TENANT_ID, DEFAULT_GAME_INSTANCE_ID, ACCOUNT_ID, 7L, ACCOUNT_ID); + STACK.freshGameplayBaseline( + TENANT_ID, DEFAULT_GAME_INSTANCE_ID, MANAGEMENT_OWNER_SELECTOR, 7L, EMBERLINE_CHARACTER_ID); } @Test @@ -523,7 +528,7 @@ void telnetReconnectAfterStaleSessionFreshEntersGameplay() throws Exception { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); long activeGameplaySessionId = sessionContextService - .findByGameplayIdentity(TENANT_ID, DEMO_WORLD_INSTANCE_ID, ACCOUNT_ID) + .findByGameplayIdentity(TENANT_ID, DEMO_WORLD_INSTANCE_ID, EMBERLINE_CHARACTER_ID) .orElseThrow(() -> new IllegalStateException("Expected active gameplay binding")) .sessionId(); sessionContextService.deleteBySessionId(TENANT_ID, activeGameplaySessionId); @@ -726,9 +731,9 @@ private static synchronized void ensureTestServicesStarted() { GatewayHolder gateway = null; try { stack = - GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) - .mapAccountId(SORA_EMAIL, SORA_ACCOUNT_ID) - .mapAccountId(NYX_EMAIL, NYX_ACCOUNT_ID) + GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_UUID) + .mapAccountUuid(SORA_EMAIL, SORA_ACCOUNT_UUID) + .mapAccountUuid(NYX_EMAIL, NYX_ACCOUNT_UUID) .withSocialEnabled(true) .withGameLogicProps( Map.of( @@ -749,7 +754,8 @@ private static synchronized void ensureTestServicesStarted() { GatewayBackedGameSessionTestOverrides.class, NestedReadinessOverrides.class) .start(); long defaultGameInstanceId = - stack.freshGameplayBaseline(TENANT_ID, 1L, ACCOUNT_ID, 7L, ACCOUNT_ID); + stack.freshGameplayBaseline( + TENANT_ID, 1L, MANAGEMENT_OWNER_SELECTOR, 7L, EMBERLINE_CHARACTER_ID); awaitGameSessionReadiness(stack.gameSessionPort()); gateway = startGateway(stack.gameSessionPort()); @@ -797,9 +803,9 @@ private void seedLiveTargetSession() { STACK.seedLiveSession( 90210L, TENANT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + SORA_ACCOUNT_UUID, "sora@example.com", - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + SORA_CHARACTER_ID, "Sora", DEMO_WORLD_INSTANCE_ID, LookTestFixtures.ROOM_ID,