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/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a345dcfe0d..2c1f737aa4 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -103,7 +103,10 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. The current direct gRPC read requires the verified Social Groups peer and a non-internal caller account subject equal to the requested account before its existing membership check. - `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails and permits account holders to select `PUBLIC`, `FRIENDS_ONLY`, or `PRIVATE`, while `HIDDEN_STAFF` remains reserved for the staff-visibility owner. The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. The direct gRPC mutation has the same verified Social Groups peer and exact caller-account guard. -- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 account IDs. Social projections consume this authority at read time; unknown or unavailable entries are intentionally omitted so callers apply complete `PRIVATE` redaction. The current direct gRPC read requires the verified Social Groups peer. +- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical non-nil Account UUID selectors. Account resolves persisted UUID provenance, tenant membership, and profile ownership before returning UUID-keyed policies; private numeric row keys do not cross this boundary. Social projections consume this authority at read time; unknown or missing entries are intentionally omitted so callers apply complete `PRIVATE` redaction. Contradictory ownership/provenance fails the read closed. The current direct gRPC read requires the verified Social Groups peer. + +Profile gRPC read payloads carry the exact persisted canonical `accountId` and integral `tenantId`. A successful `UpdateProfileResponse` echoes that same persisted Account UUID and tenant; a contradictory or missing readback cannot produce success. Social verifies both fields before trusting profile data or a visibility update. These echoes are identity evidence, not additional caller authorization. + - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The legacy account-ID gRPC method currently fails closed before reading data because it cannot establish that caller/operation binding; the local export substrate is not the canonical route. - `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 1c9ef57cab..68e22eec2a 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -55,7 +55,7 @@ Expected response: - `Ping(PingRequest) returns (PingResponse)` is the basic connectivity check defined in [`game_logic_service.proto`](../../../../protos/game-logic/v1/game_logic_service.proto). - `ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse)` evaluates a parsed gameplay command and returns the outcome. -- `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires `account_id` to be present, positive, and numeric; malformed, missing, or non-positive account identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. +- `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter requires `account_id` to be the exact canonical non-nil Account UUID under the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions); numeric, malformed, missing, nil, uppercase or whitespace-normalized identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It projects the flat request to Social & Groups as `tenant_id`, that unchanged Account UUID as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never substitutes `character_id` for Account identity. Character-recipient metadata remains distinct from an Account UUID and is not an authenticated character-to-Account mapping; the complete typed recipient plan and real Social delivery remain unproved. The adapter does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. - `PickupVisibleRoomItem` and `DropCarriedItem` are the player-facing item selector RPCs for the current `GET` and `DROP` command path. Game Session sends the current session/game/room context, raw item reference, and quantity; Game Logic resolves names, visible refs, container identities, and stack-family refs against the appropriate visible holder before delegating the concrete mutation to Entity Management. - `ApplyActorCondition` is the current self-scoped gameplay orchestration path for the first actor-state mutation. It is not the target-state generic cross-actor effect API. - gRPC outcome selection follows the [canonical outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification): successfully produced gameplay/domain outcomes use the typed response contract, while a failure that prevents producing that result uses canonical non-OK status with bounded details. Exact RPC mappings remain implementation work. diff --git a/design/architecture/microservices/social-groups-service/api-contracts.md b/design/architecture/microservices/social-groups-service/api-contracts.md index 5894635e65..74d066f22c 100644 --- a/design/architecture/microservices/social-groups-service/api-contracts.md +++ b/design/architecture/microservices/social-groups-service/api-contracts.md @@ -14,6 +14,8 @@ The target chat write contract derives `senderAccountId` from authenticated call ## Implementation Status +Account selectors in the Social REST/gRPC boundary are canonical non-nil UUID strings, carried unchanged to Account and Game Session; tenant, guild, private row, character, and runtime instance selectors are distinct identities. Profile reads and successful updates require an exact Account UUID and tenant readback. This local convergence does not enable removed Gateway routes or close the broader relationship, replay, or moderation gaps below. Cutover and proof limits are recorded in the [player-experience tracker](../../../project-management/implementation-tracking/player-experience-commands-and-communication.md#current-status). + The friend-presence slice currently implements non-pageable friend-roster and presence reads over tenant-scoped mutually accepted reciprocal links whose two directed rows are both `active`; that is implementation status, not the target relationship authority. The player-facing Gateway `/api/social/friends` route is removed/unavailable because the current endpoint path has no directional block-state model or block revalidation. The direct service-local implementation remains available for direct-service and future non-edge use and retains reciprocal-active filtering, but it does not claim the target player-facing safety boundary. The target distinguishes tenant-free account-pair relationships from separate tenant-local records and binds each group to one declared membership subject type. One-way links, inactive reciprocal links, and links stored under another tenant are not endpoint-visible; focused integration proof covers those boundaries in [SocialGroupsApplicationIntegrationTest.java](../../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java). It does not create snapshots, continuations, or paginated bulk pages. Snapshot-bound continuation, continuation-time relationship and block revalidation, bounded paginated bulk reads, and the failure-precedence contract below remain target behavior; this document does not claim that the current implementation or existing tests prove those target obligations. The current chat writer paths remain internal/non-player-safe: the Gateway `/api/social/chat` edge route is removed/unavailable, while service-local `/chat` and gRPC `SendMessage` still use the request-body `senderAccountId` with the Social access guard. The synchronous `EvaluateModerationPolicy` read at `CHAT_SEND` remains the current Logging & Admin hot-path compatibility seam and is consumed only after a cache/replay miss. Replay storage and lookup remain tenant/effect-only and occur before that policy check, with no authenticated-caller or full request-digest binding. The duplicate-effect catch also queries after a unique violation in the same outer transaction, so PostgreSQL transaction-abort/rollback-only behavior is not a reliable replay result; conflict-safe insert or isolated transaction handling and real concurrent proof remain required. Owner-local restriction state, essential notices, independent stacking, expiry/reordering, appeal handling, and the target gate are not yet implemented or proved; these writers therefore remain nonconformant to the target contract above. @@ -55,7 +57,7 @@ Current internal/non-player-safe chat request (the Gateway `/api/social/chat` ed curl -X POST http://localhost:8080/chat \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ - -d '{"tenantId":7,"senderAccountId":100,"content":"hello"}' + -d '{"tenantId":7,"senderAccountId":"550e8400-e29b-41d4-a716-446655440000","content":"hello"}' ``` Example voice-token request: @@ -64,7 +66,7 @@ Example voice-token request: curl -X POST http://localhost:8080/voice/token \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ - -d '{"tenantId":7,"accountId":100,"channelId":"guild-10"}' + -d '{"tenantId":7,"accountId":"550e8400-e29b-41d4-a716-446655440000","channelId":"guild-10"}' ``` ## gRPC APIs diff --git a/design/architecture/microservices/social-groups-service/runtime-and-data.md b/design/architecture/microservices/social-groups-service/runtime-and-data.md index 4a67a079d6..29e7be4c19 100644 --- a/design/architecture/microservices/social-groups-service/runtime-and-data.md +++ b/design/architecture/microservices/social-groups-service/runtime-and-data.md @@ -41,6 +41,8 @@ The current live moderation seam is the synchronous `EvaluateModerationPolicy` r ## Data Model +The account-bearing columns in `guilds`, `guild_members`, `chat_messages`, `mail_messages`, `account_friend_links`, and `friend_links` use PostgreSQL UUIDs; private primary keys and non-Account identities remain separate. Forward migration V10 locks all six tables against concurrent writes and permits conversion only when the complete set is empty. A retained row refuses the entire migration without conversion or deletion and requires Account-owned authoritative recovery; no numeric-to-UUID mapping is inferred. Published V1–V9 migrations remain unchanged. Deployment must retain the publication/admission block until the actual database boundary and affected callers are proved; see the [implementation tracker](../../../project-management/implementation-tracking/player-experience-commands-and-communication.md#current-status). + - Type-specific Social history tables/rows persist only communication classes that promise player-visible history; live world speech is not a permanent archive by default - Separate finite protected safety-evidence records and content-free idempotency receipts are not player history and have their own retention/access lifecycle - **Current implementation gap:** Social currently persists chat in one `chat_messages` table and mail in one `mail_messages` table. The schema has no implemented type-specific history-retention lifecycle, legal/operational hold state, separate safety-evidence disposition, or content-free receipt family; the chat-only `{tenantId,effectId}` uniqueness index is not the target full request-digest/effect replay contract. Current chat/mail tests prove bounded persistence and service behavior only, not expiry, hold, erasure/tombstone, receipt-after-content-expiry, or concurrent/replayed idempotency. The target storage, retention, hold, evidence, acknowledgement, and receipt requirements remain owned by [ADR 0149](../../decisions/adr-0149-communication-type-specific-history-and-retention.md) and are not restated here. 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 b2e1365e14..d9625b1071 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,9 +12,11 @@ The corrected composed Account, Game Session, TCP Proxy, Common Test Support and 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 canonical profile/management-owner front is published as [#2929](https://github.com/benhook1013/FireMUD/pull/2929) at `ce057022f48137b861025a47795640a90a4a82de`, 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. Start locks tenant rows lacking a canonical owner with any status other than exact `STOPPED` and rejects active or uncertain legacy ownership with `OWNER_ACCOUNT_IDENTITY_UNAVAILABLE`; it never infers which Account owns that evidence. Restart rejects a missing or noncanonical owner UUID before row or Redis mutation. Stop, readback and pre-termination compensation preserve raw numeric evidence. The closed version-2 retained-tenant snapshot binds both truthful owner slots; source locks, exact approval and immutable association readback remain required. Before enablement, fence all older numeric-owner writers, inventory deployed migration history and read back the exact retained numeric and UUID owner slots; these deployment gates are not established here. Demo seeding no longer invents an Account owner without an authoritative source. The full front gate passed166tasks(18executed/148up-to-date), with2253fresh Game Session unit cases(17skips) and no failures; PostgreSQL cases skipped without Docker. This does not activate catalog enrollment, the membership RPC or credentials, nor implement Account operator-reference/digest authorization. Shared JWT and #2932 gameplay carriers remain distinct proof boundaries; publication does 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. +The current Game Session migration order preserves V7 catalog-revision audit, V8 legacy-bootstrap repair, V9 initial-admission ledger and V10 run-owned launch ledger. Authored-world source intake, retained tenant association and command UUID storage occupy V7.1, V8.1 and V9.1; the byte-identical owner UUID migration follows at V10.1. Filename reconciliation resolves source-tree collisions only. Dependent catalog or command activation requires exact deployed-history inventory and owner-readback of retained source, snapshot, association and command rows. Unknown provenance stays unresolved; do not use Flyway repair, out-of-order execution, identity casting or data cleanup to reconcile history. No deployed-history or retained-row readback proof is claimed here. + +The shared-auth successor [#2969](https://github.com/benhook1013/FireMUD/pull/2969) is published at `783dd1ea6bcd3b76cae474a032f0a551066a00ee`. It 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 distinct types. A genuinely account-free internal workload omits `accountId`; an internal flag cannot discard a present malformed identity. The focused Common Security full check passed34tasks with all122unit cases executed and no failures or skips, including callback-context cleanup and malformed internal-identity denial. Its final ten-module gate, three service JARs and docs passed357tasks(17executed/340up-to-date); other service reports were reused and PostgreSQL cases remain skipped. This is local helper/interceptor proof, not fresh-image or live authentication proof. #2969's interim legacy numeric presence-viewer containment is superseded here by #2932's canonical UUID self-service; exact tenant-role and response predicates remain. Interim Social numeric self-service and sender-bound mail remain unavailable pending the approved complete Social UUID storage/API/consumer child after #2932. No retained rows or published migrations are rewritten and no admission path is enabled. ### Earlier Checkpoint Evidence @@ -34,6 +36,7 @@ The local Game Session Account-UUID carrier candidate normally incorporates publ 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. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 6970fc04c1..7dc233635b 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -Shared ordinary Account JWT identity now uses the exact canonical Account UUID in the shared-auth successor to #2929. Legacy numeric Social self-service and sender-bound mail cannot prove that caller identity and remain unavailable; existing genuine tenant-role access and internal service/storage behavior are separate boundaries. The approved Social UUID child after [#2932](https://github.com/benhook1013/FireMUD/pull/2932) must converge all account-bearing storage, APIs and affected consumers without numeric aliases or guessed retained mappings. Local shared-helper proof is not positive Social delivery or authentication/activation proof. Preserve existing friend privacy/redaction and removed Gateway routes; this interim containment does not close EA-2.1/EA-2.2/EA-2.3 target gaps. +Shared ordinary Account JWT identity uses the exact canonical Account UUID in [#2969](https://github.com/benhook1013/FireMUD/pull/2969), the shared-auth child of #2929. The Social front after [#2932](https://github.com/benhook1013/FireMUD/pull/2932) converges account-bearing Social storage/API selectors and Account, Game Session, and Social-to-Logging caller boundaries without numeric aliases or guessed retained mappings. Its immediately stacked Logging receiver child carries the moderation/report UUID receiver and storage changes; the Social front alone does not provide that receiver capability. Exact UUID self access and authenticated sender-bound mail replace the interim numeric-caller containment only in the Social front; genuine tenant-role checks and all removed Gateway routes remain separate and unchanged. Account bulk policies resolve persisted provenance and membership, while profile reads/updates verify exact Account UUID and tenant echoes. Social V10 locks all six affected tables and refuses retained data unchanged; the Logging child's V6 independently fences both affected moderation/report tables. Retained-data recovery remains Account-owned and unimplemented. Local generation, affected compilation, unit tests, formatting/analyzers, and packaged JAR checks cover the composed candidate; each extracted stage requires its own proof. Migration tests compile but skip without Docker; real PostgreSQL cutover, fresh-image and live-delivery proof remain required. Game Session filters ONLINE/RECENT roster matches after final privacy redaction, with negative proof that backend match metadata cannot disclose suppressed presence through inclusion. Moderation/report operations remain unavailable in both stages; installing the receiver child does not activate them. No successful Social deployment, cross-pod delivery, moderation/report activation, or end-to-end authentication is claimed, and this correction does not close EA-2.1/EA-2.2/EA-2.3 target gaps. + +Game Logic now forwards the canonical sender UUID, but its legacy gameplay recipient field still denotes a character selector. That field must not be guessed into an Account UUID: numeric recipients fail closed at Social until the separately owned typed-recipient/owner-delivery convergence is implemented. Existing gameplay-connected communication tests use the regression Social stub; they are not positive proof of real Social `WHISPER`/`TELL` delivery. Owner-local restrictions, authenticated full-request replay, and type-specific retention remain unfinished independently of this UUID repair. This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable post-logout episode fencing, and broader client consumption are not yet proven. Authenticated text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects. Focused Game Session proof asserts this negative/no-side-effect boundary and that fresh first-party `PLAY` does not read retained screen-buffer rows solely from connect-token context; neither proves successful logout or durable episode fencing; concurrent and delayed replay still require durable episode-fence proof. 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/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index c542794aec..b1d86ecbee 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -273,12 +273,14 @@ message GetProfileResponse { } // Internal bounded bulk read used by Social Groups when projecting friend presence. +// Account identities are canonical non-nil UUIDs, never private Account row keys. message ListPresenceVisibilityPoliciesRequest { string tenant_id = 1; repeated string account_ids = 2; } message PresenceVisibilityPolicyEntry { + // Exact requested Account UUID whose persisted source was verified by Account. string account_id = 1; string policy = 2; } @@ -298,6 +300,9 @@ message UpdateProfileRequest { message UpdateProfileResponse { bool success = 1; shared.v1.ErrorDetail error = 2; + // Successful writes echo the exact persisted Account UUID and tenant selector. + string account_id = 3; + string tenant_id = 4; } message ExportAccountRequest { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 35988d7afd..f4b943d352 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -80,8 +80,9 @@ RealmAccessGrantResult getRealmAccessGrantForRuntime( /** Reads a tenant profile with an Account-local storage selector after owner-side UUID proof. */ ProfileDto getProfile(Long tenantId, Long accountId); - java.util.Map listPresenceVisibilityPolicies( - Long tenantId, java.util.List accountIds); + /** Reads policies by canonical Account UUID; private numeric row keys remain Account-local. */ + java.util.Map listPresenceVisibilityPolicies( + Long tenantId, java.util.List accountUuids); /** Updates a profile using an Account-local selector and the request's canonical Account UUID. */ ProfileDto updateProfile(Long accountStorageId, UpdateProfileRequest request); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 77bbdf7547..c5303d773a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -882,20 +882,20 @@ public void listPresenceVisibilityPolicies( throw new InvalidRequestException( "accountIds must contain at most " + MAX_ACCOUNT_IDS_PER_REQUEST + " entries", null); } - java.util.List accountIds = + java.util.List accountUuids = request.getAccountIdsList().stream() - .map(accountId -> requirePositiveRequestId(accountId, "accountId")) + .map(accountId -> requireCanonicalAccountUuid(accountId).toString()) .distinct() .toList(); var builder = net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder(); accountService - .listPresenceVisibilityPolicies(tenantId, accountIds) + .listPresenceVisibilityPolicies(tenantId, accountUuids) .forEach( - (accountId, policy) -> + (accountUuid, policy) -> builder.addPolicies( net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry.newBuilder() - .setAccountId(Long.toString(accountId)) + .setAccountId(accountUuid) .setPolicy(policy.name()) .build())); responseObserver.onNext(builder.build()); @@ -943,18 +943,29 @@ public void updateProfile( String displayName = node.path("displayName").asText(null); String bio = node.path("bio").asText(null); String presenceVisibilityPolicy = node.path("presenceVisibilityPolicy").asText(null); - accountService.updateProfile( - accountId, - new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - tenantId, - accountUuid.toString(), - displayName, - bio, - ProfilePresenceVisibilityPolicy.valueOf( - presenceVisibilityPolicy == null - ? ProfilePresenceVisibilityPolicy.FRIENDS_ONLY.name() - : presenceVisibilityPolicy))); - UpdateProfileResponse response = UpdateProfileResponse.newBuilder().setSuccess(true).build(); + var updatedProfile = + accountService.updateProfile( + accountId, + new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( + tenantId, + accountUuid.toString(), + displayName, + bio, + ProfilePresenceVisibilityPolicy.valueOf( + presenceVisibilityPolicy == null + ? ProfilePresenceVisibilityPolicy.FRIENDS_ONLY.name() + : presenceVisibilityPolicy))); + if (updatedProfile == null + || !accountUuid.toString().equals(updatedProfile.accountId()) + || !Long.valueOf(tenantId).equals(updatedProfile.tenantId())) { + throw new IllegalStateException("Profile update readback did not match its request"); + } + UpdateProfileResponse response = + UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(updatedProfile.accountId()) + .setTenantId(updatedProfile.tenantId().toString()) + .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 83b68a3a01..49d83cdcbf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -2382,22 +2382,71 @@ public ProfileDto getProfile(Long tenantId, Long accountId) { @Override @Transactional(readOnly = true) @Timed(value = "account.list_presence_visibility_policies") - public Map listPresenceVisibilityPolicies( - Long tenantId, List accountIds) { - if (accountIds == null || accountIds.isEmpty()) { + public Map listPresenceVisibilityPolicies( + Long tenantId, List accountUuids) { + if (tenantId == null || tenantId <= 0L) { + throw new IllegalArgumentException("tenantId must be positive"); + } + if (accountUuids == null || accountUuids.isEmpty()) { return Map.of(); } - return profileRepository.findByTenantIdAndAccountIds(tenantId, accountIds).stream() - .filter( - profile -> - profile.getAccount() != null - && profile.getAccount().getId() != null - && profile.getPresenceVisibilityPolicy() != null) - .collect( - java.util.stream.Collectors.toUnmodifiableMap( - profile -> profile.getAccount().getId(), - profile -> profile.getPresenceVisibilityPolicy(), - (left, right) -> left)); + List canonicalAccountUuids = + accountUuids.stream() + .map(this::requireProfileAccountUuid) + .map(UUID::toString) + .distinct() + .toList(); + + Map accountUuidsByStorageId = new HashMap<>(); + List accountStorageIds = new java.util.ArrayList<>(); + for (String canonicalAccountUuid : canonicalAccountUuids) { + UUID accountUuid = UUID.fromString(canonicalAccountUuid); + Account account = accountRepository.findByAccountUuid(accountUuid).orElse(null); + if (account == null) { + continue; + } + requireAuthenticationPersistedIdentity(account); + if (!accountUuid.equals(account.getAccountUuid())) { + throw new IllegalStateException( + "Account UUID readback did not match the requested persisted identity"); + } + + Long accountStorageId = account.getId(); + String priorAccountUuid = + accountUuidsByStorageId.putIfAbsent(accountStorageId, canonicalAccountUuid); + if (priorAccountUuid != null && !priorAccountUuid.equals(canonicalAccountUuid)) { + throw new IllegalStateException( + "Account UUID lookup returned a conflicting private storage row"); + } + if (accountTenantMembershipRepository.existsByAccountIdAndTenantId( + accountStorageId, tenantId)) { + accountStorageIds.add(accountStorageId); + } else { + accountUuidsByStorageId.remove(accountStorageId); + } + } + + if (accountStorageIds.isEmpty()) { + return Map.of(); + } + + Map policies = new HashMap<>(); + for (Profile profile : + profileRepository.findByTenantIdAndAccountIds(tenantId, accountStorageIds)) { + Long profileAccountId = profile.getAccount() == null ? null : profile.getAccount().getId(); + String accountUuid = accountUuidsByStorageId.get(profileAccountId); + if (accountUuid == null) { + throw new IllegalStateException( + "Profile source does not match a requested persisted Account identity"); + } + requireProfileBelongsTo(profile, profileAccountId, tenantId); + if (profile.getPresenceVisibilityPolicy() != null + && policies.putIfAbsent(accountUuid, profile.getPresenceVisibilityPolicy()) != null) { + throw new IllegalStateException( + "Multiple profile rows matched one persisted Account identity"); + } + } + return Map.copyOf(policies); } @Override diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 0db10aec79..decb435d0e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -1219,11 +1219,13 @@ void getProfileRejectsMissingCallerAccountSubjectBeforeLookup() { void listPresenceVisibilityPoliciesMapsPersistedPolicies() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L, 3L))) + Mockito.when( + accountService.listPresenceVisibilityPolicies( + 1L, List.of(ACCOUNT_UUID, OTHER_ACCOUNT_UUID))) .thenReturn( Map.of( - 2L, ProfilePresenceVisibilityPolicy.PRIVATE, - 3L, ProfilePresenceVisibilityPolicy.HIDDEN_STAFF)); + ACCOUNT_UUID, ProfilePresenceVisibilityPolicy.PRIVATE, + OTHER_ACCOUNT_UUID, ProfilePresenceVisibilityPolicy.HIDDEN_STAFF)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -1234,9 +1236,9 @@ void listPresenceVisibilityPoliciesMapsPersistedPolicies() { service.listPresenceVisibilityPolicies( ListPresenceVisibilityPoliciesRequest.newBuilder() .setTenantId("1") - .addAccountIds("2") - .addAccountIds("3") - .addAccountIds("2") + .addAccountIds(ACCOUNT_UUID) + .addAccountIds(OTHER_ACCOUNT_UUID) + .addAccountIds(ACCOUNT_UUID) .build(), observer)); @@ -1245,15 +1247,19 @@ void listPresenceVisibilityPoliciesMapsPersistedPolicies() { assertTrue( observer.response().getPoliciesList().stream() .anyMatch( - entry -> entry.getAccountId().equals("2") && entry.getPolicy().equals("PRIVATE"))); + entry -> + entry.getAccountId().equals(ACCOUNT_UUID) + && entry.getPolicy().equals("PRIVATE"))); assertTrue( observer.response().getPoliciesList().stream() .anyMatch( entry -> - entry.getAccountId().equals("3") && entry.getPolicy().equals("HIDDEN_STAFF"))); + entry.getAccountId().equals(OTHER_ACCOUNT_UUID) + && entry.getPolicy().equals("HIDDEN_STAFF"))); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); - Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); + Mockito.verify(accountService) + .listPresenceVisibilityPolicies(1L, List.of(ACCOUNT_UUID, OTHER_ACCOUNT_UUID)); } @Test @@ -1292,28 +1298,61 @@ void listPresenceVisibilityPoliciesRejectsMissingOrWrongPeerBeforeLookup() { } @Test - void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { + void listPresenceVisibilityPoliciesRejectsMalformedAccountUuidsBeforeLookup() { + for (String malformedAccountId : + List.of( + "2", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT))) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = + new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds(malformedAccountId) + .build(), + observer)); + + assertNotNull(observer.response()); + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertEquals( + "accountId must be a canonical non-nil UUID", + observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void listPresenceVisibilityPoliciesRejectsMoreThanOneHundredSelectorsBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + ListPresenceVisibilityPoliciesRequest.Builder request = + ListPresenceVisibilityPoliciesRequest.newBuilder().setTenantId("1"); + for (int index = 0; index < 101; index++) { + request.addAccountIds(ACCOUNT_UUID); + } RecordingObserver observer = new RecordingObserver<>(); withPeer( SOCIAL_GROUPS_PEER, - () -> - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("0") - .build(), - observer)); + () -> service.listPresenceVisibilityPolicies(request.build(), observer)); - assertNotNull(observer.response()); assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); - assertEquals("accountId must be positive", observer.response().getError().getMessage()); + assertEquals( + "accountIds must contain at most 100 entries", observer.response().getError().getMessage()); assertTrue(observer.completed()); - assertFalse(observer.receivedTransportError()); Mockito.verifyNoInteractions(accountService); } @@ -1324,7 +1363,7 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) + Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(ACCOUNT_UUID))) .thenThrow(new IllegalArgumentException("Tenant not found")); RecordingObserver notFoundObserver = new RecordingObserver<>(); @@ -1334,7 +1373,7 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors service.listPresenceVisibilityPolicies( ListPresenceVisibilityPoliciesRequest.newBuilder() .setTenantId("1") - .addAccountIds("2") + .addAccountIds(ACCOUNT_UUID) .build(), notFoundObserver)); @@ -1343,7 +1382,7 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors assertFalse(notFoundObserver.receivedTransportError()); Mockito.reset(accountService); - Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) + Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(ACCOUNT_UUID))) .thenThrow(new IllegalStateException("Policy lookup unavailable")); RecordingObserver internalObserver = new RecordingObserver<>(); @@ -1353,7 +1392,7 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors service.listPresenceVisibilityPolicies( ListPresenceVisibilityPoliciesRequest.newBuilder() .setTenantId("1") - .addAccountIds("2") + .addAccountIds(ACCOUNT_UUID) .build(), internalObserver)); @@ -1612,6 +1651,10 @@ void updateProfileAllowsExactSocialPeerWithMatchingSubject() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) .thenReturn(2L); + Mockito.when(accountService.updateProfile(Mockito.eq(2L), Mockito.any())) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.ProfileDto( + 10L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); @@ -1630,6 +1673,8 @@ void updateProfileAllowsExactSocialPeerWithMatchingSubject() { observer)); assertTrue(observer.response().getSuccess()); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("1", observer.response().getTenantId()); assertTrue(observer.completed()); org.mockito.ArgumentCaptor captor = @@ -1642,6 +1687,52 @@ void updateProfileAllowsExactSocialPeerWithMatchingSubject() { assertEquals("demo", captor.getValue().displayName()); } + @Test + void updateProfileRejectsMismatchedPersistedIdentityEchoes() { + for (var mismatchedProfile : + List.of( + new net.firedevops.firemud.accountservice.dto.ProfileDto( + 10L, + 1L, + OTHER_ACCOUNT_UUID, + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE), + new net.firedevops.firemud.accountservice.dto.ProfileDto( + 10L, 2L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE))) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.updateProfile(Mockito.eq(2L), Mockito.any())) + .thenReturn(mismatchedProfile); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertFalse(observer.response().getSuccess()); + assertEquals("INTERNAL", observer.response().getError().getCode()); + assertEquals("Profile source validation failed", observer.response().getError().getMessage()); + assertEquals("", observer.response().getAccountId()); + assertEquals("", observer.response().getTenantId()); + assertTrue(observer.completed()); + Mockito.verify(accountService).updateProfile(Mockito.eq(2L), Mockito.any()); + } + } + @Test void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 768faf2608..f61f52c3a8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -7072,16 +7072,115 @@ void getProfileRejectsForeignAccountRelationBeforeMapping() { void listPresenceVisibilityPoliciesOmitsProfilesWithoutAPolicy() { Account account = new Account(); account.setId(2L); + setPersistedAuthenticationIdentity(account); Profile profile = new Profile(); profile.setAccount(account); + profile.setTenantId(1L); profile.setPresenceVisibilityPolicy(null); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); + when(profileRepository.findByTenantIdAndAccountIds(1L, java.util.List.of(2L))) + .thenReturn(java.util.List.of(profile)); + + Map policies = + service.listPresenceVisibilityPolicies( + 1L, java.util.List.of(account.getAccountUuid().toString())); + + assertTrue(policies.isEmpty()); + } + + @Test + void listPresenceVisibilityPoliciesKeysResultsByVerifiedAccountUuid() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + Profile profile = new Profile(); + profile.setAccount(account); + profile.setTenantId(1L); + profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.PRIVATE); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); when(profileRepository.findByTenantIdAndAccountIds(1L, java.util.List.of(2L))) .thenReturn(java.util.List.of(profile)); - Map policies = - service.listPresenceVisibilityPolicies(1L, java.util.List.of(2L)); + String accountUuid = account.getAccountUuid().toString(); + Map policies = + service.listPresenceVisibilityPolicies(1L, java.util.List.of(accountUuid)); + + assertEquals(Map.of(accountUuid, ProfilePresenceVisibilityPolicy.PRIVATE), policies); + verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + } + + @Test + void listPresenceVisibilityPoliciesRejectsMalformedUuidBeforeLookup() { + assertThrows( + IllegalArgumentException.class, + () -> service.listPresenceVisibilityPolicies(1L, java.util.List.of("2"))); + + verifyNoInteractions(accountRepository, accountTenantMembershipRepository, profileRepository); + } + + @Test + void listPresenceVisibilityPoliciesOmitsUnknownAccountUuids() { + String unknownAccountUuid = UUID.randomUUID().toString(); + + Map policies = + service.listPresenceVisibilityPolicies(1L, java.util.List.of(unknownAccountUuid)); assertTrue(policies.isEmpty()); + verify(accountRepository).findByAccountUuid(UUID.fromString(unknownAccountUuid)); + verifyNoInteractions(accountTenantMembershipRepository, profileRepository); + } + + @Test + void listPresenceVisibilityPoliciesFailsClosedOnContradictoryAccountProvenance() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + account.setAccountUuidSourceNumericId(3L); + + assertThrows( + IllegalStateException.class, + () -> + service.listPresenceVisibilityPolicies( + 1L, java.util.List.of(account.getAccountUuid().toString()))); + + verifyNoInteractions(accountTenantMembershipRepository, profileRepository); + } + + @Test + void listPresenceVisibilityPoliciesOmitsAccountsWithoutTenantMembership() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(false); + + Map policies = + service.listPresenceVisibilityPolicies( + 1L, java.util.List.of(account.getAccountUuid().toString())); + + assertTrue(policies.isEmpty()); + verifyNoInteractions(profileRepository); + } + + @Test + void listPresenceVisibilityPoliciesRejectsForeignProfileOwner() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + Account foreignAccount = new Account(); + foreignAccount.setId(3L); + Profile profile = new Profile(); + profile.setAccount(foreignAccount); + profile.setTenantId(1L); + profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.PRIVATE); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); + when(profileRepository.findByTenantIdAndAccountIds(1L, java.util.List.of(2L))) + .thenReturn(java.util.List.of(profile)); + + assertThrows( + IllegalStateException.class, + () -> + service.listPresenceVisibilityPolicies( + 1L, java.util.List.of(account.getAccountUuid().toString()))); } @Test 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 a3a3befc92..4307c428f3 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 @@ -10,18 +10,23 @@ import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetProfileResponse; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.UpdateProfileRequest; +import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.common.account.AccountProfileJson; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; 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"; + private static final JsonMapper JSON_MAPPER = JsonMapper.builder().build(); @Test void authenticationCanonicalizesEmailAndRuntimeAuthoritySnapshotsAreFreshAndComplete() @@ -209,38 +214,50 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); + GetProfileResponse initialProfileResponse = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build()); + assertProfileIdentity(initialProfileResponse, ACCOUNT_UUID, 1L); AccountProfileJson initialProfile = - AccountProfileJson.parse( - stub.getProfile( - GetProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId(ACCOUNT_UUID) - .build()) - .getProfileJson(), - "FRIENDS_ONLY"); + AccountProfileJson.parse(initialProfileResponse.getProfileJson(), "FRIENDS_ONLY"); assertThat(initialProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); - assertThat( - stub.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId(ACCOUNT_UUID) - .setProfileJson( - "{\"displayName\":\"Demo-%s\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}" - .formatted(ACCOUNT_UUID)) - .build()) - .getSuccess()) - .isTrue(); + UpdateProfileResponse updateResponse = + stub.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"Demo-%s\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}" + .formatted(ACCOUNT_UUID)) + .build()); + assertThat(updateResponse.getSuccess()).isTrue(); + assertThat(updateResponse.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(updateResponse.getTenantId()).isEqualTo("1"); + UpdateProfileResponse wrongTenantUpdate = + stub.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("2") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"Wrong tenant\",\"bio\":null,\"presenceVisibilityPolicy\":\"PUBLIC\"}") + .build()); + assertThat(wrongTenantUpdate.getSuccess()).isFalse(); + assertThat(wrongTenantUpdate.getAccountId()).isEmpty(); + assertThat(wrongTenantUpdate.getTenantId()).isEmpty(); + + GetProfileResponse wrongTenantRead = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("2").setAccountId(ACCOUNT_UUID).build()); + assertThat(wrongTenantRead.getProfileJson()).isEmpty(); + + GetProfileResponse updatedProfileResponse = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build()); + assertProfileIdentity(updatedProfileResponse, ACCOUNT_UUID, 1L); AccountProfileJson updatedProfile = - AccountProfileJson.parse( - stub.getProfile( - GetProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId(ACCOUNT_UUID) - .build()) - .getProfileJson(), - "FRIENDS_ONLY"); + AccountProfileJson.parse(updatedProfileResponse.getProfileJson(), "FRIENDS_ONLY"); assertThat(updatedProfile.presenceVisibilityPolicy()).isEqualTo("PRIVATE"); } finally { channel.shutdownNow(); @@ -273,10 +290,11 @@ void rejectsInvalidAccountSelectorsForRegistrationAndProfileMutation() throws Ex assertThatThrownBy( () -> server.setPresenceVisibilityPolicy(invalidAccountUuid, "PRIVATE")) .isInstanceOf(IllegalArgumentException.class); - assertThat( - stub.updateProfile(profileUpdate(invalidAccountUuid, "Overwritten profile")) - .getSuccess()) - .isFalse(); + UpdateProfileResponse invalidAccountUpdate = + stub.updateProfile(profileUpdate(invalidAccountUuid, "Overwritten profile")); + assertThat(invalidAccountUpdate.getSuccess()).isFalse(); + assertThat(invalidAccountUpdate.getAccountId()).isEmpty(); + assertThat(invalidAccountUpdate.getTenantId()).isEmpty(); } assertThatThrownBy(() -> server.mapAccountUuid("candidate@example.com", null)) @@ -356,4 +374,13 @@ private static UpdateProfileRequest profileUpdate(String accountUuid, String dis .formatted(displayName)) .build(); } + + private static void assertProfileIdentity( + GetProfileResponse response, String accountUuid, long tenantId) throws Exception { + JsonNode profile = JSON_MAPPER.readTree(response.getProfileJson()); + assertThat(profile.path("accountId").isTextual()).isTrue(); + assertThat(profile.path("accountId").asString()).isEqualTo(accountUuid); + assertThat(profile.path("tenantId").isIntegralNumber()).isTrue(); + assertThat(profile.path("tenantId").asLong()).isEqualTo(tenantId); + } } 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 0414f443d6..a0d417c7dd 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 @@ -44,6 +44,10 @@ import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase @@ -53,6 +57,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe 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 ObjectMapper PROFILE_JSON_MAPPER = JsonMapper.builder().build(); private static final Set IMPLEMENTED_RUNTIME_METHODS = Set.of( "Ping", @@ -535,15 +540,15 @@ public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { try { String accountUuid = requireCanonicalAccountUuid(request.getAccountId()); - StubProfile profile = - profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); + long tenantId = requirePositiveTenantId(request.getTenantId()); + StubProfile profile = bindProfileToTenant(accountUuid, tenantId); + if (!profile.belongsToTenant(tenantId)) { + responseObserver.onNext(GetProfileResponse.newBuilder().build()); + responseObserver.onCompleted(); + return; + } responseObserver.onNext( - GetProfileResponse.newBuilder() - .setProfileJson( - new AccountProfileJson( - profile.displayName(), profile.bio(), profile.presenceVisibilityPolicy()) - .toJson()) - .build()); + GetProfileResponse.newBuilder().setProfileJson(profileJson(profile)).build()); responseObserver.onCompleted(); } catch (Exception ex) { responseObserver.onNext(GetProfileResponse.newBuilder().build()); @@ -556,19 +561,31 @@ public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { String accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + long tenantId = requirePositiveTenantId(request.getTenantId()); AccountProfileJson profile = AccountProfileJson.parse(request.getProfileJson(), StubProfile.DEFAULT_VISIBILITY_POLICY); - StubProfile existing = - profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); - profilesByAccountUuid.put( - accountUuid, + StubProfile existing = bindProfileToTenant(accountUuid, tenantId); + if (!existing.belongsToTenant(tenantId)) { + responseObserver.onNext(UpdateProfileResponse.newBuilder().setSuccess(false).build()); + responseObserver.onCompleted(); + return; + } + StubProfile updated = new StubProfile( + existing.accountUuid(), + existing.tenantId(), profile.displayName(), profile.bio(), profile.presenceVisibilityPolicy() == null ? existing.presenceVisibilityPolicy() - : profile.presenceVisibilityPolicy())); - responseObserver.onNext(UpdateProfileResponse.newBuilder().setSuccess(true).build()); + : profile.presenceVisibilityPolicy()); + profilesByAccountUuid.put(accountUuid, updated); + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(updated.accountUuid()) + .setTenantId(Long.toString(updated.tenantId())) + .build()); responseObserver.onCompleted(); } catch (Exception ex) { responseObserver.onNext(UpdateProfileResponse.newBuilder().setSuccess(false).build()); @@ -581,15 +598,85 @@ public void close() { server.shutdownNow(); } - private record StubProfile(String displayName, String bio, String presenceVisibilityPolicy) { + private StubProfile bindProfileToTenant(String accountUuid, long tenantId) { + return profilesByAccountUuid.compute( + accountUuid, + (ignored, profile) -> { + if (profile == null) { + return StubProfile.defaultFor(accountUuid, tenantId); + } + return profile.bindTo(tenantId); + }); + } + + private static long requirePositiveTenantId(String tenantId) { + try { + long parsed = Long.parseLong(tenantId); + if (parsed <= 0L) { + throw new IllegalArgumentException("tenantId must be positive"); + } + return parsed; + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("tenantId must be numeric", ex); + } + } + + private static String profileJson(StubProfile profile) { + ObjectNode json = PROFILE_JSON_MAPPER.createObjectNode(); + json.put("accountId", profile.accountUuid()); + json.put("tenantId", profile.tenantId()); + putNullableText(json, "displayName", profile.displayName()); + putNullableText(json, "bio", profile.bio()); + putNullableText(json, "presenceVisibilityPolicy", profile.presenceVisibilityPolicy()); + try { + return PROFILE_JSON_MAPPER.writeValueAsString(json); + } catch (JacksonException ex) { + throw new IllegalStateException("Could not serialize stub Account profile", ex); + } + } + + private static void putNullableText(ObjectNode json, String fieldName, String value) { + if (value == null) { + json.putNull(fieldName); + } else { + json.put(fieldName, value); + } + } + + private record StubProfile( + String accountUuid, + Long tenantId, + String displayName, + String bio, + String presenceVisibilityPolicy) { private static final String DEFAULT_VISIBILITY_POLICY = "FRIENDS_ONLY"; private static StubProfile defaultFor(String accountUuid) { - return new StubProfile("Demo-" + accountUuid, null, DEFAULT_VISIBILITY_POLICY); + return new StubProfile( + accountUuid, null, "Demo-" + accountUuid, null, DEFAULT_VISIBILITY_POLICY); + } + + private static StubProfile defaultFor(String accountUuid, long tenantId) { + return new StubProfile( + accountUuid, tenantId, "Demo-" + accountUuid, null, DEFAULT_VISIBILITY_POLICY); + } + + private StubProfile bindTo(long tenantId) { + if (tenantId() != null) { + return this; + } + return new StubProfile( + accountUuid(), tenantId, displayName(), bio(), presenceVisibilityPolicy()); + } + + private boolean belongsToTenant(long requestedTenantId) { + return tenantId() != null && tenantId() == requestedTenantId; } private StubProfile withPresenceVisibilityPolicy(String visibilityPolicy) { return new StubProfile( + accountUuid, + tenantId, displayName, bio, visibilityPolicy == null ? DEFAULT_VISIBILITY_POLICY : visibilityPolicy); diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java index 926dee9c20..0af2070bf6 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java @@ -9,6 +9,7 @@ import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.settings.EffectiveCommandCapabilitiesSettingsResolver; import net.firedevops.firemud.common.settings.PlayerCommandCapability; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; @@ -56,10 +57,10 @@ public SendCommunicationResponse send(SendCommunicationRequest request) { SendCommunicationResponse.newBuilder() .setType(request.getType()) .setMessage(normalizedText); - String validatedAccountId = parsePositiveAccountId(request.getAccountId()); + String validatedAccountId = parseCanonicalAccountId(request.getAccountId()); if (validatedAccountId == null) { return errorResponse( - builder, "INVALID_ARGUMENT", "account_id must be a positive numeric account id"); + builder, "INVALID_ARGUMENT", "account_id must be a canonical non-nil Account UUID"); } if (tenantId != null && !isSocialCapabilityEnabled(tenantId, gameInstanceId)) { @@ -396,15 +397,10 @@ private Long parseTenantId(String tenantId) { } } - private String parsePositiveAccountId(String accountId) { - if (!StringUtils.hasText(accountId)) { - return null; - } - String normalized = accountId.trim(); + private String parseCanonicalAccountId(String accountId) { try { - long parsed = Long.parseLong(normalized); - return parsed > 0L ? Long.toString(parsed) : null; - } catch (NumberFormatException ignored) { + return JwtClaims.requireAccountId(accountId, "account_id"); + } catch (IllegalArgumentException ignored) { return null; } } diff --git a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java index 5091a32be2..883365c5ef 100644 --- a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java +++ b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java @@ -41,7 +41,7 @@ @ExtendWith(MockitoExtension.class) class CommunicationAggregationServiceTest { - private static final String VALID_ACCOUNT_ID = "42"; + private static final String VALID_ACCOUNT_ID = "cc51ef2c-9a14-4c56-98bd-af7f8e4c60c1"; @Mock private SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialStub; @@ -125,14 +125,18 @@ void unavailableSocialCapabilityAuthorityFailsClosedWithoutCallingDownstreamServ } @Test - void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { + void rejectsMissingMalformedAndNoncanonicalAccountIdsBeforeDownstreamCalls() { for (String[] accountIdCase : new String[][] { {"empty", ""}, {"whitespace-only", " "}, - {"malformed", "not-a-number"}, + {"malformed", "not-a-uuid"}, + {"numeric", "42"}, {"zero", "0"}, {"negative", "-1"}, + {"nil", "00000000-0000-0000-0000-000000000000"}, + {"uppercase", VALID_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT)}, + {"padded", " " + VALID_ACCOUNT_ID + " "}, }) { String accountIdCaseDescription = accountIdCase[0]; String accountId = accountIdCase[1]; @@ -154,7 +158,7 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { .isEqualTo("INVALID_ARGUMENT"); assertThat(resp.getError().getMessage()) .as(accountIdCaseDescription) - .isEqualTo("account_id must be a positive numeric account id"); + .isEqualTo("account_id must be a canonical non-nil Account UUID"); } verify(entityStub, never()).listRoomEntities(any()); @@ -162,7 +166,7 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { } @Test - void normalizesPaddedNoncanonicalAccountIdForSocialSender() { + void preservesCanonicalAccountUuidForSocialSenderWithoutUsingCharacterIdentity() { when(socialStub.sendMessage(any())) .thenReturn(SendMessageResponse.newBuilder().setSuccess(true).build()); @@ -172,7 +176,7 @@ void normalizesPaddedNoncanonicalAccountIdForSocialSender() { .setTenantId("tenant-1") .setSessionId("sess-1") .setCharacterId("player-0") - .setAccountId(" 0042 ") + .setAccountId(VALID_ACCOUNT_ID) .setType(CommunicationType.TELL) .setTargetCharacterId("player-9") .setTargetCharacterName("Sora") @@ -182,7 +186,8 @@ void normalizesPaddedNoncanonicalAccountIdForSocialSender() { assertThat(resp.getSuccess()).isTrue(); ArgumentCaptor captor = ArgumentCaptor.forClass(SendMessageRequest.class); verify(socialStub).sendMessage(captor.capture()); - assertThat(captor.getValue().getSenderId()).isEqualTo("42"); + assertThat(captor.getValue().getSenderId()).isEqualTo(VALID_ACCOUNT_ID); + assertThat(captor.getValue().getSenderId()).isNotEqualTo("player-0"); } @Test 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 85e0d3d5e8..1964598731 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 @@ -420,13 +420,10 @@ private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendList return toEntry(ordinal, entry); }) .toList(); - boolean canonicalFiltered = - filter == FriendListFilter.ALL - || response.getFilter() == mapRosterFilter(filter) - || response.getMatchCount() > 0 - || response.getTotalCount() > 0; + // Filtering must use the final disclosed projection, not backend membership in a filter. + // A redacted subject must not reveal online/recent state through its inclusion alone. List mapped = - canonicalFiltered ? allEntries : allEntries.stream().filter(filter::matches).toList(); + allEntries.stream().filter(filter::matches).toList(); int totalCount = response.getTotalCount() > 0 ? response.getTotalCount() : allEntries.size(); return new FriendPresenceViewOutput(filter.name(), totalCount, mapped); } 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 bc085d3988..5ba48232aa 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -36,7 +36,7 @@ class CommunicationWebSocketCrossServiceTest { 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 MANAGEMENT_OWNER_SELECTOR = 900_001L; 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"; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidenceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidenceTest.java new file mode 100644 index 0000000000..b1a11cf2b4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AccountAuthorityEvidenceTest.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.gamesession.command.text; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import org.junit.jupiter.api.Test; + +class AccountAuthorityEvidenceTest { + private static final String ACCOUNT_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private static final String OTHER_ACCOUNT_UUID = "b0ad193b-12c1-4c96-bcad-c162229af440"; + private static final Instant NOW = Instant.parse("2026-10-04T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + + @Test + void acceptsFreshGrantForExactCanonicalAccountAndTenant() { + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + validGrant(), ACCOUNT_UUID, 22L, "demo", "production", CLOCK)) + .isTrue(); + } + + @Test + void rejectsMalformedNilNumericAndWrongAccountIdentities() { + assertInvalidAccount("malformed"); + assertInvalidAccount("00000000-0000-0000-0000-000000000000"); + assertInvalidAccount("123"); + assertInvalidAccount(ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT)); + assertInvalidAccount(OTHER_ACCOUNT_UUID); + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + validGrant(), "123", 22L, "demo", "production", CLOCK)) + .isFalse(); + } + + @Test + void rejectsExpiredGrantEvidence() { + var expired = validGrant().toBuilder().setEvaluatedAt(NOW.minusSeconds(16).toString()).build(); + + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + expired, ACCOUNT_UUID, 22L, "demo", "production", CLOCK)) + .isFalse(); + } + + @Test + void retainsTenantWorldRealmAndVersionChecks() { + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + validGrant().toBuilder().setTenantId("23").build(), + ACCOUNT_UUID, + 22L, + "demo", + "production", + CLOCK)) + .isFalse(); + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + validGrant(), ACCOUNT_UUID, 22L, "other", "production", CLOCK)) + .isFalse(); + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + validGrant(), ACCOUNT_UUID, 22L, "demo", "other", CLOCK)) + .isFalse(); + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + validGrant().toBuilder().setGrantVersion(0L).build(), + ACCOUNT_UUID, + 22L, + "demo", + "production", + CLOCK)) + .isFalse(); + } + + private static void assertInvalidAccount(String accountId) { + assertThat( + AccountAuthorityEvidence.isValidRealmAccessGrant( + validGrant().toBuilder().setAccountId(accountId).build(), + ACCOUNT_UUID, + 22L, + "demo", + "production", + CLOCK)) + .isFalse(); + } + + private static GetRealmAccessGrantForRuntimeResponse validGrant() { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("22") + .setWorldSlug("demo") + .setRealmSlug("production") + .setGrantVersion(1L) + .setEvaluatedAt(NOW.toString()) + .build(); + } +} 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 9e13ddfb27..1e1131164e 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 @@ -34,6 +34,8 @@ import net.firedevops.firemud.socialgroups.v1.RemoveFriendResponse; import net.firedevops.firemud.socialgroups.v1.UpdateFriendPresencePolicyResponse; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class FriendsCommandHandlerTest { @@ -377,6 +379,63 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } + @ParameterizedTest + @ValueSource(strings = {"ONLINE", "RECENT"}) + void friendsFilteredRedactedMatchesKeepRosterTotalOutOfPlayerText(String filter) { + FriendRosterFilter rosterFilter = + "ONLINE".equals(filter) + ? FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE + : FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT; + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + FriendsCommandHandler handler = + newHandler( + socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID, rosterFilter)) + .thenReturn( + ListFriendsResponse.newBuilder() + .setFilter(rosterFilter) + .setTotalCount(2) + .setMatchCount(1) + .addFriends( + FriendRosterEntry.newBuilder() + .setOrdinal(2) + .setFriendAccountId(SECOND_FRIEND_ACCOUNT_ID) + .setPresence( + FriendPresenceEntry.newBuilder() + .setFriendAccountId(SECOND_FRIEND_ACCOUNT_ID) + .setOnline("ONLINE".equals(filter)) + .setLastSeenAtMs(1_744_336_000_000L) + .setCharacterName("Secret") + .setVisibilityPolicy( + net.firedevops.firemud.socialgroups.v1 + .FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE) + .build()) + .build()) + .build()); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, java.util.List.of(filter), "FRIENDS " + filter), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isTrue(); + FriendPresenceViewOutput view = + (FriendPresenceViewOutput) result.outputs().getFirst().payload(); + assertThat(view.filter()).isEqualTo(filter); + assertThat(view.totalCount()).isEqualTo(2); + assertThat(view.friends()).isEmpty(); + assertThat( + new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()) + .render(result.outputs().getFirst())) + .contains("Friends " + filter + ": no matching friends.") + .doesNotContain("Secret", SECOND_FRIEND_ACCOUNT_ID, "[1/2]", "[0/2]", "[0/0]"); + Mockito.verify(socialGroupsClient).listFriends(1L, CALLER_ACCOUNT_ID, rosterFilter); + } + @Test void friendsOnlineWithNoMatchesKeepsRosterTotalOutOfPlayerText() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); 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 697dd3ce43..34e9d25828 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 @@ -644,7 +644,6 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi .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))); @@ -665,7 +664,10 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi verify(sessionContextService, Mockito.times(2)).save(captor.capture()); List savedContexts = captor.getAllValues(); SessionContext credentialContext = savedContexts.get(0); + assertEquals(22L, credentialContext.tenantId()); assertEquals(ACCOUNT_99, credentialContext.accountId()); + assertEquals("other@example.com", credentialContext.loginName()); + assertEquals(AUTH_TOKEN, credentialContext.jwt()); assertEquals(1L, credentialContext.bootstrapGameInstanceId()); assertEquals("demo", credentialContext.worldSlug()); assertEquals("production", credentialContext.realmSlug()); 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 e8fa35924f..e6650e365a 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 @@ -19,7 +19,7 @@ class LogoutCommandHandlerTest { private final LogoutCommandHandler handler = new LogoutCommandHandler(sessionContextService); @Test - void authenticatedSharedRuntimeLogoutFailsWithoutMutatingContext() { + void authenticatedSharedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { when(sessionContextService.findBySessionId(41L)) .thenReturn(Optional.of(context(41L, ACCOUNT_UUID, 1L, "SHARED"))); @@ -30,7 +30,7 @@ void authenticatedSharedRuntimeLogoutFailsWithoutMutatingContext() { } @Test - void authenticatedIsolatedRuntimeLogoutFailsWithoutMutatingContext() { + void authenticatedIsolatedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { when(sessionContextService.findBySessionId(41L)) .thenReturn(Optional.of(context(41L, ACCOUNT_UUID, 7L, "ISOLATED"))); @@ -41,22 +41,13 @@ void authenticatedIsolatedRuntimeLogoutFailsWithoutMutatingContext() { } @Test - void loggedOutContextRemainsNotLoggedInWithoutMutation() { + void unauthenticatedContextStillReturnsNotLoggedInWithoutMutation() { when(sessionContextService.findBySessionId(41L)) .thenReturn(Optional.of(context(41L, null, 1L, "SHARED"))); 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."); - assertThat(result.outputs()) - .singleElement() - .satisfies( - output -> { - assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); - assertThat(output.text()).isEqualTo("ERROR NOT_LOGGED_IN You are not logged in."); - }); + assertNotLoggedIn(result); verify(sessionContextService).findBySessionId(41L); verifyNoMoreInteractions(sessionContextService); } @@ -67,9 +58,7 @@ void missingSessionRemainsNotLoggedIn() { 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."); + assertNotLoggedIn(result); verify(sessionContextService).findBySessionId(41L); verifyNoMoreInteractions(sessionContextService); } @@ -78,8 +67,7 @@ void missingSessionRemainsNotLoggedIn() { void invalidSessionIdDoesNotLookUpOrMutateContext() { LogoutCommandHandlingResult result = handler.handle("not-a-session", logoutCommand()); - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + assertNotLoggedIn(result); verifyNoMoreInteractions(sessionContextService); } @@ -110,6 +98,19 @@ private static void assertUnavailable(LogoutCommandHandlingResult result) { }); } + private static void assertNotLoggedIn(LogoutCommandHandlingResult result) { + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + assertThat(result.commandResult().errorMessage()).isEqualTo("You are not logged in."); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); + assertThat(output.text()).isEqualTo("ERROR NOT_LOGGED_IN You are not logged in."); + }); + } + private static TextCommand logoutCommand() { return new TextCommand(TextCommandType.LOGOUT, java.util.List.of(), "LOGOUT"); } 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 7693d63e5d..8a35a71095 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 @@ -67,6 +67,7 @@ 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 String OTHER_ACCOUNT_ID = "00000000-0000-0000-0000-000000000999"; private static final ObjectMapper JSON = new ObjectMapper(); private static final UUID ADMISSION_REALM_ID = UUID.fromString("00000000-0000-0000-0000-000000000001"); @@ -202,14 +203,7 @@ void setUp() { void playPromotesSessionIntoGameplay() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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()); @@ -225,7 +219,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -243,7 +237,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -261,7 +255,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -280,7 +274,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -352,7 +346,11 @@ void playRejectsSameNameCharacterFromAnotherAccountBeforeBinding() { "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "8008", + "demo", + "22", + OTHER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1433,14 +1431,7 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", @@ -1467,14 +1458,7 @@ void playRejectsModerationPolicyDeniedAdmission() { void playUsesPersistedAccountRosterCharacterForSelectedTarget() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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", PLAYER_ACCOUNT_ID, "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -1502,7 +1486,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -1520,7 +1504,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -1540,7 +1524,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -1561,14 +1545,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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()); @@ -1658,20 +1635,17 @@ void playRejectsMalformedPersistedRosterCharacterId() { void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "8008", + "demo", + "22", + OTHER_ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1685,14 +1659,7 @@ void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -1716,14 +1683,7 @@ void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = characterRoster( @@ -1859,14 +1819,7 @@ void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { void playRejectsUnavailableCharacterRosterBeforeBinding() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -1892,7 +1845,7 @@ void playResumeRejectsChangedRosterIdentityWithoutBinding() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -1923,14 +1876,7 @@ void playResumeRejectsChangedRosterIdentityWithoutBinding() { void playRejectsEntityRosterErrorWithoutBinding() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); Mockito.doReturn( ListCharactersByAccountResponse.newBuilder() @@ -1950,14 +1896,7 @@ void playRejectsEntityRosterErrorWithoutBinding() { void playReadsMembershipGrantAndEntitlementBeforeActorRoster() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "41", @@ -2001,7 +1940,7 @@ void playResumeDoesNotPublishSpawnEvent() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -2044,26 +1983,10 @@ void playResumeDoesNotPublishSpawnEvent() { void playIgnoresStaleExistingBindingAfterNormalization() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext clearedExisting = new SessionContext( - 9L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - null, - "old-jwt", - 1L); + 9L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(clearedExisting)); @@ -2078,7 +2001,7 @@ void playIgnoresStaleExistingBindingAfterNormalization() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -2101,19 +2024,12 @@ void playIgnoresStaleExistingBindingAfterNormalization() { void playIgnoresExistingBindingWithoutRoomRegion() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext existingWithoutRoom = new SessionContext( 9L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -2140,7 +2056,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -2162,16 +2078,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { void firstPartyPlayRejectsMismatchedConnectScope() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "first-party:123", - 0L, - null, - 0L, - null, - null, - 41L); + 1L, 22L, PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -2204,16 +2111,7 @@ void firstPartyPlayRejectsMismatchedConnectScope() { void firstPartyPlayRejectsMismatchedWorldSlug() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "first-party:123", - 0L, - null, - 0L, - null, - null, - 1L); + 1L, 22L, PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -2242,16 +2140,7 @@ void firstPartyPlayRejectsStalePointerVersion() { gameplayCatalogProperties.getWorlds().get(0).getRealms().get(0).setPointerVersion(9L); SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "first-party:123", - 0L, - null, - 0L, - null, - null, - 1L); + 1L, 22L, PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -2279,16 +2168,7 @@ void firstPartyPlayRejectsStalePointerVersion() { void firstPartyPlayRejectsConnectContextMissingRealmSlug() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "first-party:123", - 0L, - null, - 0L, - null, - null, - 1L); + 1L, 22L, PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -2378,16 +2258,7 @@ void firstPartyPlayRejectsUnreadableRegistryContextWithoutPersistedFallback( void firstPartyPlayRejectsConnectContextMissingConnectScope() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "first-party:123", - 0L, - null, - 0L, - null, - null, - 1L); + 1L, 22L, PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -2415,16 +2286,7 @@ void firstPartyPlayRejectsConnectContextMissingConnectScope() { void firstPartyPlayRejectsConnectContextMissingConnectRequest() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "first-party:123", - 0L, - null, - 0L, - null, - null, - 1L); + 1L, 22L, PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -2461,8 +2323,7 @@ void playWithoutSessionReturnsLoginRequired() { @Test void playWithoutArgumentsReturnsInvalidArgument() { - SessionContext context = - new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 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 = @@ -2474,8 +2335,7 @@ void playWithoutArgumentsReturnsInvalidArgument() { @Test void unknownWorldReturnsSelectionGuidance() { - SessionContext context = - new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 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 = @@ -2601,8 +2461,7 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { @Test void sandboxWithoutCharacterReturnsSelectionRequired() { - SessionContext context = - new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 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 = @@ -2623,8 +2482,7 @@ void sandboxWithoutCharacterReturnsSelectionRequired() { @Test void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { - SessionContext context = - new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 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 = @@ -2664,8 +2522,7 @@ void playRejectsIsolatedStateRealm() { .getRealms() .get(1) .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - SessionContext context = - new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 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 = @@ -2689,16 +2546,7 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "first-party:123", - 0L, - null, - 0L, - null, - null, - 41L); + 1L, 22L, PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, 0L, null, null, 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( @@ -2749,7 +2597,7 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, @@ -2797,7 +2645,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "first-party:123", 0L, null, @@ -2936,14 +2784,7 @@ void playDeniedDoesNotClearCrossTenantSameSlugBinding() { void playRejectsMalformedActiveMembershipEvidenceWithoutGameplaySideEffects() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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))) @@ -2954,7 +2795,7 @@ void playRejectsMalformedActiveMembershipEvidenceWithoutGameplaySideEffects() { freshMembership( net.firedevops.firemud.gamesession.support .RuntimeMembershipTestFixtures.active( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "2")) + PLAYER_ACCOUNT_ID, 22L, "2")) .toBuilder() .setGameplayAdmissionAllowed(false) .build(), @@ -2990,15 +2831,7 @@ void playRejectsMalformedActiveMembershipEvidenceWithoutGameplaySideEffects() { void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3008,7 +2841,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), + .missing(PLAYER_ACCOUNT_ID, 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = @@ -3042,7 +2875,7 @@ void playNonPublicLeftMembershipRequiresEnrollment() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); + PLAYER_ACCOUNT_ID, 22L, List.of("designer", "player"))); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( @@ -3080,7 +2913,7 @@ void playBoundNonPublicLeftMembershipRequiresEnrollmentAndClearsBinding() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); + PLAYER_ACCOUNT_ID, 22L, List.of("designer", "player"))); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( @@ -3491,15 +3324,7 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -3629,14 +3454,7 @@ void playPublicMissingMembershipReturnsJoinRequiredBeforeCharacterRosterLookup() void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleState) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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))) @@ -3645,7 +3463,7 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); + .missing(PLAYER_ACCOUNT_ID, 22L)); var malformedLifecycle = response.toBuilder() .setMembershipLifecycleState(lifecycleState) @@ -3672,14 +3490,7 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleState) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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))) @@ -3689,10 +3500,10 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt "INACTIVE".equals(lifecycleState) ? freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3")) + .inactive(PLAYER_ACCOUNT_ID, 22L, "3")) : freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); + .missing(PLAYER_ACCOUNT_ID, 22L)); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( response.toBuilder().setGameplayAdmissionAllowed(true).build(), @@ -3713,7 +3524,7 @@ void playLeftMembershipRequiresJoinForPublicProduction() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); + PLAYER_ACCOUNT_ID, 22L, List.of("designer", "player"))); var leftEvent = MembershipAuthorityEventV1Codec.verify( leftMembership.getOutboxSourceEvidence(0).getCanonicalEventJson()); @@ -3917,19 +3728,11 @@ void playPublicJoinRequiresFreshEntitlementEvidence(String evidence) { void playBoundLeftMembershipRequiresJoinAndClearsBindingForPublicProduction() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); + PLAYER_ACCOUNT_ID, 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))) @@ -4103,14 +3906,7 @@ void playAuthorityFreshnessUsesInjectedClockAtExactInclusiveBoundaries() { void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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))) @@ -4120,7 +3916,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), + .missing(PLAYER_ACCOUNT_ID, 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -4149,14 +3945,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { void playBillingDenialMasksMissingPublicMembership() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -4185,18 +3974,11 @@ void playBillingDenialMasksMissingPublicMembership() { void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); + PLAYER_ACCOUNT_ID, 22L)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -4231,14 +4013,7 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", @@ -4266,14 +4041,7 @@ void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEntityCalls() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 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))) @@ -4283,7 +4051,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), + .missing(PLAYER_ACCOUNT_ID, 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -4315,15 +4083,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4332,7 +4092,7 @@ void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")) + .active(PLAYER_ACCOUNT_ID, 22L, "1")) .toBuilder() .setEvaluatedAt( switch (defect) { @@ -4365,15 +4125,7 @@ void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4385,7 +4137,7 @@ void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { freshMembership( net.firedevops.firemud.gamesession.support .RuntimeMembershipTestFixtures.active( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), + PLAYER_ACCOUNT_ID, 22L, "1")), invocation.getArgument(0)); return response.toBuilder().setRequestId("wrong-request-id").build(); }); @@ -4426,7 +4178,7 @@ void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { switch (invalidEvidence) { case "stale" -> response.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); case "future" -> response.setEvaluatedAt(Instant.now().plusSeconds(1).toString()); - case "wrong-account" -> response.setAccountId("00000000-0000-0000-0000-000000000999"); + case "wrong-account" -> response.setAccountId(OTHER_ACCOUNT_ID); case "wrong-tenant" -> response.setTenantId("00000000-0000-0000-0000-000000000023"); case "unknown-lifecycle" -> response.setMembershipLifecycleState("UNKNOWN"); case "inactive-admitting" -> { @@ -4518,7 +4270,7 @@ void playRejectsInvalidPositiveGrantAuthority(String invalidEvidence) { switch (invalidEvidence) { case "stale" -> grant.setEvaluatedAt(Instant.now().minusSeconds(16).toString()); case "future" -> grant.setEvaluatedAt(Instant.now().plusSeconds(1).toString()); - case "wrong-account" -> grant.setAccountId("999"); + case "wrong-account" -> grant.setAccountId(OTHER_ACCOUNT_ID); case "wrong-realm" -> grant.setRealmSlug("production"); default -> throw new IllegalArgumentException(invalidEvidence); } @@ -4543,15 +4295,7 @@ void playRejectsInvalidPositiveGrantAuthority(String invalidEvidence) { void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4563,7 +4307,7 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { freshMembership( net.firedevops.firemud.gamesession.support .RuntimeMembershipTestFixtures.active( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), + PLAYER_ACCOUNT_ID, 22L, "1")), invocation.getArgument(0)); return response.toBuilder().clearMembershipAuthorityGeneration().build(); }); @@ -4626,15 +4370,7 @@ void playWhenMembershipAuthorityTupleHasUnknownFieldsIsDeniedBeforeAdmission() { void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4643,7 +4379,7 @@ void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); + .active(PLAYER_ACCOUNT_ID, 22L, "1")); String changedCanonicalJson = resealWithMembershipVersion( response.getOutboxSourceEvidence(0).getCanonicalEventJson(), "2"); @@ -4678,15 +4414,7 @@ void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4695,7 +4423,7 @@ void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); + .active(PLAYER_ACCOUNT_ID, 22L, "1")); String changedCanonicalJson = changeCanonicalEventWithoutResealing( response.getOutboxSourceEvidence(0).getCanonicalEventJson()); @@ -4730,15 +4458,7 @@ void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4747,7 +4467,7 @@ void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); + .active(PLAYER_ACCOUNT_ID, 22L, "1")); var source = response.getOutboxSourceEvidence(0).toBuilder().clearCanonicalEventJson(); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures @@ -4784,15 +4504,7 @@ void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -4801,7 +4513,7 @@ void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); + .active(PLAYER_ACCOUNT_ID, 22L, "1")); var mismatchedResponse = response.toBuilder() .putMembershipVersion("00000000-0000-0000-0000-000000000022", "2") @@ -4839,14 +4551,7 @@ void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { void unsafeEntitlementSnapshotFailsClosed(String defect) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "jwt-token"); + 1L, 22L, PLAYER_ACCOUNT_ID, "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; @@ -4886,15 +4591,7 @@ void unsafeEntitlementSnapshotFailsClosed(String defect) { void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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( @@ -4924,15 +4621,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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( @@ -4964,15 +4653,7 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { void playWhenMembershipAuthorityUnavailableFailsClosed() { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -5016,15 +4697,7 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforePublicOutcomes( String lifecycle, String availability) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -5034,13 +4707,13 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforePublicOutcomes( switch (lifecycle) { case "ACTIVE" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1"); + .active(PLAYER_ACCOUNT_ID, 22L, "1"); case "MISSING" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L); + .missing(PLAYER_ACCOUNT_ID, 22L); case "INACTIVE" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3"); + .inactive(PLAYER_ACCOUNT_ID, 22L, "3"); default -> throw new IllegalArgumentException("Unexpected lifecycle: " + lifecycle); }; @@ -5087,9 +4760,9 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforeNonPublicOutcome( var membership = "MISSING".equals(lifecycle) ? net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L) + .missing(PLAYER_ACCOUNT_ID, 22L) : net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3"); + .inactive(PLAYER_ACCOUNT_ID, 22L, "3"); var builder = freshMembership(membership).toBuilder(); if (!"ABSENT".equals(availability)) { builder.setAuthorityAvailability(availability); @@ -5125,15 +4798,7 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforeNonPublicOutcome( void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding(String errorCode) { SessionContext context = new SessionContext( - 1L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1", - "jwt-token"); + 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( @@ -5170,28 +4835,66 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding(String erro void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { SessionContext context = new SessionContext( - 1L, 22L, PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, + 22L, + PLAYER_ACCOUNT_ID, + "demo@example.com", + 7001L, + "demo", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) - .build()); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) + .thenReturn(Optional.empty()); 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()) + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isTrue(); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); + SessionContext expectedContext = + new SessionContext( + 1L, + 22L, + PLAYER_ACCOUNT_ID, + "demo@example.com", + 7001L, + "demo", + 1L, + gameLogicProperties.getDefaultRoomId(), + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); + Mockito.verify(sessionContextService).save(expectedContext); + assertThat( + meterRegistry + .counter( + "gamesession.session.fresh_entry_fallback", + "reason", + "stale_or_missing_context") + .count()) + .isEqualTo(1.0); + Mockito.verify(sessionAuthenticationService).resolveByGameplayIdentity(22L, 1L, 7001L); + Mockito.verify(entityManagementClient) .listCharactersByAccount( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.any(PlayableStateScope.class)); + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(scriptEventPublisher) + .publishCommandEvent( + expectedContext, command("play-command:1:1:7001:1", PLAY_COMMAND_NAME, "PLAY demo")); + Mockito.verify(scriptEventPublisher) + .publishSpawnEvent(expectedContext, "play_entry", "play-spawn:1:1:7001:1"); } @Test @@ -5228,7 +4931,7 @@ void staleRoomContextFallsBackToFreshEntry() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -5258,7 +4961,7 @@ void staleRoomContextFallsBackToFreshEntry() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -5277,7 +4980,7 @@ void staleRoomContextFallsBackToFreshEntry() { new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -5444,7 +5147,7 @@ private static GetTenantMembershipForRuntimeResponse freshMembership( private static GetTenantMembershipForRuntimeResponse leftMembershipWithDefect(String defect) { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player")); + PLAYER_ACCOUNT_ID, 22L, List.of("designer", "player")); var builder = response.toBuilder(); switch (defect) { case "membership-generation" -> { @@ -5644,7 +5347,7 @@ private SessionContext previewRealmContext() { return new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 123L, "Emberline", @@ -5663,7 +5366,7 @@ private SessionContext unboundContext() { return new SessionContext( 1L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, @@ -6076,7 +5779,7 @@ void playRejectsAnotherAccountsActorEvenWhenNameMatches() { Character foreign = actorForTenant("22", "7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() - .setAccountId("999") + .setAccountId(OTHER_ACCOUNT_ID) .build(); Mockito.doReturn(roster(foreign)) .when(entityManagementClient) 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 b715da48c4..774d520826 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 @@ -212,6 +212,7 @@ void storesExactPublicOrdinalSnapshotAndBoundsAccountScopeExpiry() { } @Test + @SuppressWarnings("unchecked") void readsLegacyLobbyJsonAcrossProductionStoreInstances() throws Exception { SessionContext caller = session(41L, ACCOUNT_UUID); Instant now = Instant.now(); @@ -324,6 +325,7 @@ void readsUuidLobbySnapshotAcrossProductionStoreInstances() { 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( firstInstance .publicProductionScopeForJoin(caller, "1", 22L, "demo-world", now) 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 856e78574a..ee3aded5e3 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 @@ -249,8 +249,9 @@ public void onCompleted() {} assertEquals("pong", ref.get().getError().getMessage()); } - @Test - void queryAccountPresenceTenantRoleReturnsMappedSnapshots() { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void queryAccountPresenceCurrentAccountOrTenantRoleReturnsMappedSnapshots(boolean tenantRole) { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -261,10 +262,12 @@ void queryAccountPresenceTenantRoleReturnsMappedSnapshots() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); + String viewerAccountId = tenantRole ? OWNER_ACCOUNT_UUID : ACCOUNT_VIEWER; + SessionContext.setContext( + viewerAccountId, List.of(), tenantRole ? Map.of("1", List.of("tenantAdmin")) : Map.of()); Mockito.when( accountPresenceQueryService.queryAccountPresence( - 1L, ACCOUNT_VIEWER, List.of(ACCOUNT_TARGET))) + 1L, viewerAccountId, List.of(ACCOUNT_TARGET))) .thenReturn( List.of( new AccountPresenceSnapshot( @@ -299,7 +302,7 @@ void queryAccountPresenceTenantRoleReturnsMappedSnapshots() { service.queryAccountPresence( QueryAccountPresenceRequest.newBuilder() .setTenantId("1") - .setViewerAccountId(ACCOUNT_VIEWER) + .setViewerAccountId(viewerAccountId) .addAccountIds(ACCOUNT_TARGET) .build(), new StreamObserver<>() { 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 bc5f3e3270..51cb661a76 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 @@ -218,12 +218,13 @@ public long freshGameplayBaseline( if (characterIds.length > 0) { clearScreenBuffers(tenantId, gameplayInstanceId, characterIds); } + String ownerAccountUuid = GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID; long gameInstanceId = GameInstanceTestFixtures.insertRunningGameInstance( - jdbc, tenantId, GameInstanceTestFixtures.TEST_OWNER_ACCOUNT_UUID, gameTemplateId); + jdbc, tenantId, ownerAccountUuid, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); if (useDefaultDemoCatalogFixture) { - bindDefaultDemoPointer(tenantId, gameInstanceId, managementOwnerSelector, gameTemplateId); + bindDefaultDemoPointer(tenantId, gameInstanceId, ownerAccountUuid, gameTemplateId); } return gameInstanceId; } @@ -550,7 +551,7 @@ private static String defaultDemoRequestId(long tenantId) { } private void bindDefaultDemoPointer( - long tenantId, long gameInstanceId, long ownerAccountId, long gameTemplateId) { + long tenantId, long gameInstanceId, String ownerAccountUuid, long gameTemplateId) { InitialAdmissionBindOwnerService owner = gameSession.bean(InitialAdmissionBindOwnerService.class); GameplayAdmissionPointerAuthorityService pointerAuthority = @@ -575,7 +576,7 @@ private void bindDefaultDemoPointer( requestId, tenantId, gameTemplateId, - ownerAccountId, + ownerAccountUuid, catalog, gameInstanceId, versionId, @@ -728,7 +729,7 @@ private static String defaultDemoRequestDigest( String operationId, long tenantId, long gameTemplateId, - long ownerAccountId, + String ownerAccountUuid, InitialAdmissionBindCatalog catalog, long gameInstanceId, long versionId, @@ -738,7 +739,7 @@ private static String defaultDemoRequestDigest( appendDigestField(canonical, "operationId", operationId); appendDigestField(canonical, "tenantId", Long.toString(tenantId)); appendDigestField(canonical, "gameTemplateId", Long.toString(gameTemplateId)); - appendDigestField(canonical, "ownerAccountId", Long.toString(ownerAccountId)); + appendDigestField(canonical, "ownerAccountId", ownerAccountUuid); appendDigestField(canonical, "worldSlug", "demo"); appendDigestField(canonical, "worldDisplayName", "Demo World"); appendDigestField(canonical, "realmSlug", "production"); 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 9306b876ca..4aba1ccb59 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 @@ -65,20 +65,22 @@ public static List seedPlayers( "ALLOW_NEW", GameplayCrossServiceStack.SYNTHETIC_LOAD_ACTOR, "Seed per-player load-test admission pointer", - "load-test:" + characterId, + "load-test:" + accountUuid, 0L, 0L, null)); long sessionId = firstCharacterId + 10_000L + i + 1; String email = "player" + (i + 1) + "@example.com"; stack.accountStub().mapAccountUuid(email, accountUuid); - characters.add( + Character character = Character.newBuilder() .setId(Long.toString(characterId)) .setTenantId(Long.toString(tenantId)) .setAccountId(accountUuid) .setName(label) - .build()); + .build(); + stack.entityStub().registerCharacterForAccountUuid(accountUuid, character); + characters.add(character); players.add( new PlayerSeed( sessionId, diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java index e92a7cc0b6..36bdbefbc3 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java @@ -24,10 +24,13 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; @Component public final class AccountClient @@ -59,38 +62,38 @@ void init() throws SSLException { } public Optional getPresenceVisibilityPolicy( - long tenantId, long accountId) { + long tenantId, String accountId) { return getProfileSnapshot(tenantId, accountId) .map(AccountProfileSnapshot::presenceVisibilityPolicy); } /** Returns only current persisted policies; callers must fail closed for absent entries. */ - public Map getPresenceVisibilityPolicies( - long tenantId, Collection accountIds) { - if (stub() == null || accountIds == null || accountIds.isEmpty()) { + public Map getPresenceVisibilityPolicies( + long tenantId, Collection accountIds) { + if (accountIds == null || accountIds.isEmpty()) { return Map.of(); } - List requestedAccountIds = + List requestedAccountIds = accountIds.stream() - .filter(accountId -> accountId != null && accountId > 0) + .map(accountId -> JwtClaims.requireAccountId(accountId, "accountId")) .distinct() .toList(); - if (requestedAccountIds.isEmpty()) { + if (stub() == null) { return Map.of(); } try { - Map policies = new LinkedHashMap<>(); + Map policies = new LinkedHashMap<>(); for (int offset = 0; offset < requestedAccountIds.size(); offset += PRESENCE_VISIBILITY_POLICY_BATCH_SIZE) { - List batch = + List batch = requestedAccountIds.subList( offset, Math.min( offset + PRESENCE_VISIBILITY_POLICY_BATCH_SIZE, requestedAccountIds.size())); ListPresenceVisibilityPoliciesRequest.Builder request = ListPresenceVisibilityPoliciesRequest.newBuilder().setTenantId(Long.toString(tenantId)); - batch.forEach(accountId -> request.addAccountIds(Long.toString(accountId))); + request.addAllAccountIds(batch); ListPresenceVisibilityPoliciesResponse response = callStub().listPresenceVisibilityPolicies(request.build()); @@ -105,8 +108,9 @@ public Map getPresenceVisibilityPolic .forEach( entry -> { try { - long accountId = Long.parseLong(entry.getAccountId()); - if (accountId > 0 && batch.contains(accountId)) { + String accountId = + JwtClaims.requireAccountId(entry.getAccountId(), "accountId"); + if (batch.contains(accountId)) { policies.put( accountId, FriendPresenceVisibilityPolicyValue.valueOf(entry.getPolicy())); @@ -128,7 +132,8 @@ public Map getPresenceVisibilityPolic } public boolean updatePresenceVisibilityPolicy( - long tenantId, long accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy) { + long tenantId, String accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy) { + JwtClaims.requireAccountId(accountId, "accountId"); if (stub() == null || visibilityPolicy == null) { return false; } @@ -142,13 +147,16 @@ public boolean updatePresenceVisibilityPolicy( .updateProfile( UpdateProfileRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setProfileJson( new AccountProfileJson( snapshot.displayName(), snapshot.bio(), visibilityPolicy.name()) .toJson()) .build()); - return response.getSuccess() && !response.hasError(); + return response.getSuccess() + && !response.hasError() + && accountId.equals(response.getAccountId()) + && Long.toString(tenantId).equals(response.getTenantId()); } catch (Exception ex) { logger.warn( "Failed to update account presence visibility policy tenantId={} accountId={} policy={}", @@ -176,20 +184,31 @@ protected AccountServiceGrpc.AccountServiceBlockingStub buildStub( return applyStubCustomizer(AccountServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - private Optional getProfileSnapshot(long tenantId, long accountId) { + private Optional getProfileSnapshot(long tenantId, String accountId) { + JwtClaims.requireAccountId(accountId, "accountId"); if (stub() == null) { return Optional.empty(); } GetProfileRequest request = GetProfileRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build(); try { GetProfileResponse response = callStub().getProfile(request); if (response.hasError() || response.getProfileJson().isBlank()) { return Optional.empty(); } + JsonNode profileIdentity = JsonMapper.builder().build().readTree(response.getProfileJson()); + JsonNode returnedAccountId = profileIdentity.path("accountId"); + JsonNode returnedTenantId = profileIdentity.path("tenantId"); + if (!returnedAccountId.isTextual() + || !accountId.equals(returnedAccountId.asString()) + || !returnedTenantId.isIntegralNumber() + || !returnedTenantId.canConvertToLong() + || returnedTenantId.asLong() != tenantId) { + return Optional.empty(); + } AccountProfileJson profile = AccountProfileJson.parse( response.getProfileJson(), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY.name()); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/GameSessionClient.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/GameSessionClient.java index 8c42eee553..e4ab359e7d 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/GameSessionClient.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/GameSessionClient.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; import net.firedevops.firemud.gamesession.v1.QueryAccountPresenceRequest; import net.firedevops.firemud.gamesession.v1.QueryAccountPresenceResponse; @@ -49,15 +50,14 @@ protected GameSessionServiceGrpc.GameSessionServiceBlockingStub buildStub( } public QueryAccountPresenceResponse queryAccountPresence( - long tenantId, long viewerAccountId, List accountIds) { + long tenantId, String viewerAccountId, List accountIds) { + JwtClaims.requireAccountId(viewerAccountId, "viewerAccountId"); QueryAccountPresenceRequest.Builder request = QueryAccountPresenceRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setViewerAccountId(Long.toString(viewerAccountId)); - for (Long accountId : accountIds) { - if (accountId != null) { - request.addAccountIds(Long.toString(accountId)); - } + .setViewerAccountId(viewerAccountId); + for (String accountId : accountIds) { + request.addAccountIds(JwtClaims.requireAccountId(accountId, "accountId")); } return stub().queryAccountPresence(request.build()); } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java index 25ba4bfbcc..24ada6255c 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.GrpcClientAuth; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.loggingadmin.v1.CreateReportRequest; import net.firedevops.firemud.loggingadmin.v1.CreateReportResponse; @@ -64,12 +65,13 @@ protected ReportServiceGrpc.ReportServiceBlockingStub buildStub(io.grpc.ManagedC * @param accountId account that sent the message * @param description details of the violation */ - public void reportChatViolation(long tenantId, long accountId, String description) { + public void reportChatViolation(long tenantId, String accountId, String description) { + JwtClaims.requireAccountId(accountId, "accountId"); CreateReportRequest request = CreateReportRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setReporterAccountId(Long.toString(accountId)) - .setTargetAccountId(Long.toString(accountId)) + .setReporterAccountId(accountId) + .setTargetAccountId(accountId) .setType("CHAT_PROFANITY") .setDescription(description) .build(); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/ModerationPolicyClient.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/ModerationPolicyClient.java index 0bc6701166..1267302bfb 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/ModerationPolicyClient.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/ModerationPolicyClient.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.GrpcClientAuth; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyRequest; import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse; @@ -61,11 +62,12 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( runtimeIdentityProvider.getIfAvailable()); } - public EvaluateModerationPolicyResponse evaluateChatSend(long tenantId, long accountId) { + public EvaluateModerationPolicyResponse evaluateChatSend(long tenantId, String accountId) { + JwtClaims.requireAccountId(accountId, "accountId"); EvaluateModerationPolicyRequest request = EvaluateModerationPolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setScope(SCOPE_CHAT_SEND) .build(); return stub().evaluateModerationPolicy(request); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java index df8e564940..19577f1084 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java @@ -5,6 +5,7 @@ import java.util.function.Supplier; import net.firedevops.firemud.common.ApiResponse; import net.firedevops.firemud.common.ErrorDetail; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.socialgroups.dto.AddFriendRequest; import net.firedevops.firemud.socialgroups.dto.FriendLinkDto; @@ -62,7 +63,7 @@ public ResponseEntity> removeFriend( @RequestParam String accountId) { return withBadRequest( () -> { - long parsedFriendAccountId = requireFriendAccountId(friendAccountId); + String parsedFriendAccountId = requireFriendAccountId(friendAccountId); AccountScope scope = requireAccountScope(tenantId, accountId); socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); friendService.removeFriend(scope.tenantId(), scope.accountId(), parsedFriendAccountId); @@ -77,7 +78,7 @@ public ResponseEntity> getFriend( @RequestParam String accountId) { return withBadRequest( () -> { - long parsedFriendAccountId = requireFriendAccountId(friendAccountId); + String parsedFriendAccountId = requireFriendAccountId(friendAccountId); AccountScope scope = requireAccountScope(tenantId, accountId); socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); return friendService @@ -214,8 +215,8 @@ public ResponseEntity> updateFriendPres } } - private long requireFriendAccountId(String friendAccountId) { - return RequestIdValidation.requirePositiveLong(friendAccountId, "friendAccountId"); + private String requireFriendAccountId(String friendAccountId) { + return JwtClaims.requireAccountId(friendAccountId, "friendAccountId"); } private int requireOrdinal(String ordinal) { @@ -225,7 +226,7 @@ private int requireOrdinal(String ordinal) { private AccountScope requireAccountScope(String tenantId, String accountId) { return new AccountScope( RequestIdValidation.requirePositiveLong(tenantId, "tenantId"), - RequestIdValidation.requirePositiveLong(accountId, "accountId")); + JwtClaims.requireAccountId(accountId, "accountId")); } private ResponseEntity> withBadRequest( @@ -247,5 +248,5 @@ private ResponseEntity> unavailable(IllegalStateException ex) .body(ApiResponse.error(new ErrorDetail("UNAVAILABLE", ex.getMessage()))); } - private record AccountScope(long tenantId, long accountId) {} + private record AccountScope(long tenantId, String accountId) {} } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java index 13006867a6..bd271aae4f 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/MailController.java @@ -2,6 +2,8 @@ import jakarta.validation.Valid; import net.firedevops.firemud.common.ApiResponse; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.socialgroups.dto.MailMessageDto; import net.firedevops.firemud.socialgroups.dto.SendMailRequest; import net.firedevops.firemud.socialgroups.service.MailService; @@ -25,14 +27,14 @@ public MailController(MailService mailService) { @PostMapping public ResponseEntity> sendMail( @Valid @RequestBody SendMailRequest request) { - rejectUnmappedSenderIdentity(); + String senderAccountId = + JwtClaims.requireAccountId(request.senderAccountId(), "senderAccountId"); + JwtClaims.requireAccountId(request.recipientAccountId(), "recipientAccountId"); + if (!SessionContext.isCurrentAccount(senderAccountId)) { + throw new ResponseStatusException( + HttpStatus.FORBIDDEN, "Mail sender must match the authenticated account"); + } MailMessageDto dto = mailService.sendMail(request); return ResponseEntity.ok(ApiResponse.success(dto)); } - - private static void rejectUnmappedSenderIdentity() { - throw new ResponseStatusException( - HttpStatus.SERVICE_UNAVAILABLE, - "Mail sender authorization is unavailable until Social account UUID migration is complete"); - } } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AccountFriendLinkDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AccountFriendLinkDto.java index 37efb96df6..5e708e4bee 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AccountFriendLinkDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AccountFriendLinkDto.java @@ -7,7 +7,7 @@ public record AccountFriendLinkDto( Long id, @NotNull Long tenantId, - @NotNull Long accountId, - @NotNull Long friendAccountId, + @NotNull String accountId, + @NotNull String friendAccountId, String status, Instant createdAt) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddFriendRequest.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddFriendRequest.java index 3b9fb08a9a..989e7f5aa1 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddFriendRequest.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddFriendRequest.java @@ -1,9 +1,10 @@ package net.firedevops.firemud.socialgroups.dto; +import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; public record AddFriendRequest( @NotNull @Positive Long tenantId, - @NotNull @Positive Long accountId, - @NotNull @Positive Long friendAccountId) {} + @NotBlank String accountId, + @NotBlank String friendAccountId) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddGuildMemberRequest.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddGuildMemberRequest.java index cf374c2ada..82311491ee 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddGuildMemberRequest.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/AddGuildMemberRequest.java @@ -7,5 +7,5 @@ public record AddGuildMemberRequest( @NotNull @Positive Long tenantId, @NotNull @Positive Long guildId, - @NotNull @Positive Long accountId, + @NotNull String accountId, @NotBlank String role) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/ChatMessageDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/ChatMessageDto.java index 4c2aefdd57..1cf195437c 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/ChatMessageDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/ChatMessageDto.java @@ -5,11 +5,11 @@ public record ChatMessageDto( Long id, Long tenantId, - Long senderAccountId, + String senderAccountId, String content, Instant timestamp, Long guildId, Long cityId, - Long recipientAccountId, + String recipientAccountId, net.firedevops.firemud.socialgroups.enums.ChatType type, String effectId) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/CreateGuildRequest.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/CreateGuildRequest.java index 826711321d..4c9eee2f02 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/CreateGuildRequest.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/CreateGuildRequest.java @@ -6,6 +6,4 @@ /** Request body for creating a guild. */ public record CreateGuildRequest( - @NotNull @Positive Long tenantId, - @NotNull @Positive Long ownerAccountId, - @NotBlank String name) {} + @NotNull @Positive Long tenantId, @NotBlank String ownerAccountId, @NotBlank String name) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendLinkDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendLinkDto.java index 2503964b76..1cb3d2d74f 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendLinkDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendLinkDto.java @@ -6,7 +6,7 @@ public record FriendLinkDto( Long id, @NotNull Long tenantId, - @NotNull Long accountId, - @NotNull Long friendAccountId, + @NotNull String accountId, + @NotNull String friendAccountId, String status, Instant createdAt) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendPresenceDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendPresenceDto.java index c01cf298b6..3071cc7262 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendPresenceDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendPresenceDto.java @@ -3,7 +3,7 @@ import java.time.Instant; public record FriendPresenceDto( - Long friendAccountId, + String friendAccountId, boolean online, Long gameInstanceId, String playableStateScope, @@ -19,7 +19,7 @@ public record FriendPresenceDto( Instant lastSeenAt, FriendRecentPresenceDisposition recentDisposition) { public FriendPresenceDto( - Long friendAccountId, + String friendAccountId, boolean online, Long gameInstanceId, String worldSlug, @@ -48,7 +48,7 @@ public FriendPresenceDto( } public FriendPresenceDto( - Long friendAccountId, + String friendAccountId, boolean online, Long gameInstanceId, String worldSlug, @@ -80,7 +80,7 @@ public FriendPresenceDto( } public FriendPresenceDto( - Long friendAccountId, + String friendAccountId, boolean online, Long gameInstanceId, String playableStateScope, @@ -113,7 +113,7 @@ public FriendPresenceDto( } public FriendPresenceDto( - Long friendAccountId, + String friendAccountId, boolean online, Long gameInstanceId, String playableStateScope, diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendRosterEntryDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendRosterEntryDto.java index 5afee1e147..ca93cfe442 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendRosterEntryDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/FriendRosterEntryDto.java @@ -6,8 +6,8 @@ public record FriendRosterEntryDto( int ordinal, Long friendLinkId, Long tenantId, - Long accountId, - Long friendAccountId, + String accountId, + String friendAccountId, String status, Instant createdAt, FriendPresenceDto presence) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildDto.java index bc8893add7..53e7551b0b 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildDto.java @@ -9,5 +9,5 @@ public record GuildDto( Long id, @NotNull Long tenantId, @NotBlank String name, - @NotNull Long ownerAccountId, + @NotBlank String ownerAccountId, Instant createdAt) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildMemberDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildMemberDto.java index 0e25b5fda8..01ed511da1 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildMemberDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/GuildMemberDto.java @@ -8,5 +8,5 @@ public record GuildMemberDto( Long id, @NotNull Long tenantId, @NotNull Long guildId, - @NotNull Long accountId, + @NotNull String accountId, @NotBlank String role) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/MailMessageDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/MailMessageDto.java index 6ed408ef76..23f580997b 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/MailMessageDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/MailMessageDto.java @@ -5,8 +5,8 @@ public record MailMessageDto( Long id, Long tenantId, - Long senderAccountId, - Long recipientAccountId, + String senderAccountId, + String recipientAccountId, String subject, String content, Instant sentAt, diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMailRequest.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMailRequest.java index 4e8bae709a..fa2334ab48 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMailRequest.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMailRequest.java @@ -6,7 +6,7 @@ public record SendMailRequest( @NotNull @Positive Long tenantId, - @NotNull @Positive Long senderAccountId, - @NotNull @Positive Long recipientAccountId, + @NotBlank String senderAccountId, + @NotBlank String recipientAccountId, @NotBlank String subject, @NotBlank String content) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMessageRequestDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMessageRequestDto.java index eab47dedaa..f92c118dd5 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMessageRequestDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/SendMessageRequestDto.java @@ -7,10 +7,10 @@ public record SendMessageRequestDto( @NotNull @Positive Long tenantId, - @NotNull @Positive Long senderAccountId, + @NotBlank String senderAccountId, ChatType type, String channelId, - @Positive Long recipientAccountId, + String recipientAccountId, @Positive Long guildId, @Positive Long cityId, @NotBlank String content, diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateFriendPresencePolicyRequest.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateFriendPresencePolicyRequest.java index f5c75a3e78..84a920e9ab 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateFriendPresencePolicyRequest.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateFriendPresencePolicyRequest.java @@ -1,9 +1,10 @@ package net.firedevops.firemud.socialgroups.dto; +import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; public record UpdateFriendPresencePolicyRequest( @Positive long tenantId, - @Positive long accountId, + @NotBlank String accountId, @NotNull FriendPresenceVisibilityPolicyValue visibilityPolicy) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateGuildMemberRoleRequest.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateGuildMemberRoleRequest.java index ef0f0f8f9f..67b80c384c 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateGuildMemberRoleRequest.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/UpdateGuildMemberRoleRequest.java @@ -7,5 +7,5 @@ public record UpdateGuildMemberRoleRequest( @NotNull @Positive Long tenantId, @NotNull @Positive Long guildId, - @NotNull @Positive Long accountId, + @NotNull String accountId, @NotBlank String role) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/VoiceTokenRequestDto.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/VoiceTokenRequestDto.java index 7dba3d1235..29743b5349 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/VoiceTokenRequestDto.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/dto/VoiceTokenRequestDto.java @@ -6,6 +6,4 @@ /** Request to obtain a temporary WebRTC token for voice chat. */ public record VoiceTokenRequestDto( - @NotNull @Positive Long tenantId, - @NotNull @Positive Long accountId, - @NotBlank String channelId) {} + @NotNull @Positive Long tenantId, @NotBlank String accountId, @NotBlank String channelId) {} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/AccountFriendLink.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/AccountFriendLink.java index ab43795ad1..cc439cca8e 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/AccountFriendLink.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/AccountFriendLink.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.socialgroups.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; /** Entity representing an account-level friendship. */ @@ -8,8 +9,8 @@ public class AccountFriendLink { private Long id; private Long tenantId; - private Long accountId; - private Long friendAccountId; + private UUID accountId; + private UUID friendAccountId; private String status; private Instant createdAt; } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/ChatMessage.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/ChatMessage.java index c89a8925be..29782050a8 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/ChatMessage.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/ChatMessage.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.socialgroups.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; import net.firedevops.firemud.socialgroups.enums.ChatType; @@ -8,7 +9,7 @@ public class ChatMessage { private Long id; private Long tenantId; - private Long senderAccountId; + private UUID senderAccountId; private String content; private Instant timestamp; @@ -16,7 +17,7 @@ public class ChatMessage { private Long cityId; - private Long recipientAccountId; + private UUID recipientAccountId; private String effectId; private ChatType type; } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/Guild.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/Guild.java index bd6e9dbce1..c80479c7b3 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/Guild.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/Guild.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.socialgroups.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -8,6 +9,6 @@ public class Guild { private Long id; private Long tenantId; private String name; - private Long ownerAccountId; + private UUID ownerAccountId; private Instant createdAt; } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/GuildMember.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/GuildMember.java index 3bb64ad2c1..2ca48cef1b 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/GuildMember.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/GuildMember.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.entity; +import java.util.UUID; import lombok.Data; @Data @@ -7,6 +8,6 @@ public class GuildMember { private Long id; private Long tenantId; private Long guildId; - private Long accountId; + private UUID accountId; private String role; } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/MailMessage.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/MailMessage.java index 3411e95de5..c203a8c7c3 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/MailMessage.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/entity/MailMessage.java @@ -1,14 +1,15 @@ package net.firedevops.firemud.socialgroups.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data public class MailMessage { private Long id; private Long tenantId; - private Long senderAccountId; - private Long recipientAccountId; + private UUID senderAccountId; + private UUID recipientAccountId; private String subject; private String content; private Instant sentAt; diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/AccountFriendLinkRepository.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/AccountFriendLinkRepository.java index 05c5bbb32c..64c540f0a9 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/AccountFriendLinkRepository.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/AccountFriendLinkRepository.java @@ -5,6 +5,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.socialgroups.entity.AccountFriendLink; import net.firedevops.firemud.socialgroups.jooq.tables.records.AccountFriendLinksRecord; import org.jooq.DSLContext; @@ -24,7 +25,7 @@ public AccountFriendLinkRepository(DSLContext dsl) { } public List findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( - Long tenantId, Long accountId, String status) { + Long tenantId, UUID accountId, String status) { var reciprocal = ACCOUNT_FRIEND_LINKS.as("reciprocal_friend_link"); return dsl.selectFrom(ACCOUNT_FRIEND_LINKS) .where( @@ -52,7 +53,7 @@ public List findMutuallyAcceptedByTenantIdAndAccountIdAndStat } public List findByTenantIdAndAccountIdAndStatus( - Long tenantId, Long accountId, String status) { + Long tenantId, UUID accountId, String status) { return dsl.selectFrom(ACCOUNT_FRIEND_LINKS) .where( ACCOUNT_FRIEND_LINKS @@ -65,7 +66,7 @@ public List findByTenantIdAndAccountIdAndStatus( } public Optional findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - Long tenantId, Long accountId, Long friendAccountId, String status) { + Long tenantId, UUID accountId, UUID friendAccountId, String status) { return dsl.selectFrom(ACCOUNT_FRIEND_LINKS) .where( ACCOUNT_FRIEND_LINKS diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildMemberRepository.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildMemberRepository.java index 55515f1961..2954810d69 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildMemberRepository.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildMemberRepository.java @@ -4,6 +4,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.socialgroups.entity.GuildMember; import net.firedevops.firemud.socialgroups.jooq.tables.records.GuildMembersRecord; import org.jooq.DSLContext; @@ -22,7 +23,7 @@ public GuildMemberRepository(DSLContext dsl) { } public Optional findFirstByTenantIdAndGuildIdAndAccountId( - Long tenantId, Long guildId, Long accountId) { + Long tenantId, Long guildId, UUID accountId) { return dsl.selectFrom(GUILD_MEMBERS) .where( GUILD_MEMBERS diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java index 683f0359ce..25d6619900 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/security/SocialAccessGuard.java @@ -1,23 +1,23 @@ package net.firedevops.firemud.socialgroups.security; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.SessionContext; -import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import org.springframework.web.server.ResponseStatusException; @Component public class SocialAccessGuard { - public void requireAccountAccess(long tenantId, long accountId) { - if (!hasAccountAccess(tenantId, accountId)) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Account access required"); - } + public void requireAccountAccess(long tenantId, String accountId) { + SessionContext.requireAccountAccess( + tenantId, JwtClaims.requireAccountId(accountId, "accountId")); } - public boolean hasAccountAccess(long tenantId, long accountId) { - // Social still exposes legacy numeric account selectors. They cannot prove self access under - // the canonical Account UUID identity contract, so only the existing tenant-role gate applies - // until Social's account UUID migration is complete. - return accountId > 0L && SessionContext.hasTenantAccess(tenantId); + public boolean hasAccountAccess(long tenantId, String accountId) { + try { + return SessionContext.hasAccountAccess( + tenantId, JwtClaims.requireAccountId(accountId, "accountId")); + } catch (IllegalArgumentException ex) { + return false; + } } public void requireTenantAccess(long tenantId) { diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/ChatService.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/ChatService.java index 64387f548f..917687ffc2 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/ChatService.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/ChatService.java @@ -6,5 +6,5 @@ public interface ChatService { ChatMessageDto sendMessage(SendMessageRequestDto request); - java.util.List getRecentTells(Long tenantId, Long accountId); + java.util.List getRecentTells(Long tenantId, String accountId); } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/FriendService.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/FriendService.java index 4e2e2c378d..a89cc93404 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/FriendService.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/FriendService.java @@ -14,31 +14,32 @@ public interface FriendService { FriendLinkDto addFriend(AddFriendRequest request); - void removeFriend(long tenantId, long accountId, long friendAccountId); + void removeFriend(long tenantId, String accountId, String friendAccountId); - Optional getFriend(long tenantId, long accountId, long friendAccountId); + Optional getFriend(long tenantId, String accountId, String friendAccountId); - Optional getFriendByOrdinal(long tenantId, long accountId, int ordinal); + Optional getFriendByOrdinal(long tenantId, String accountId, int ordinal); - Optional removeFriendByOrdinal(long tenantId, long accountId, int ordinal); + Optional removeFriendByOrdinal( + long tenantId, String accountId, int ordinal); - FriendRosterViewDto listFriends(long tenantId, long accountId, FriendRosterFilter filter); + FriendRosterViewDto listFriends(long tenantId, String accountId, FriendRosterFilter filter); - FriendRosterSummaryDto getFriendRosterSummary(long tenantId, long accountId); + FriendRosterSummaryDto getFriendRosterSummary(long tenantId, String accountId); - default FriendRosterViewDto listFriends(long tenantId, long accountId) { + default FriendRosterViewDto listFriends(long tenantId, String accountId) { return listFriends(tenantId, accountId, FriendRosterFilter.ALL); } FriendPresenceViewDto listFriendPresence( - long tenantId, long accountId, FriendRosterFilter filter); + long tenantId, String accountId, FriendRosterFilter filter); - default FriendPresenceViewDto listFriendPresence(long tenantId, long accountId) { + default FriendPresenceViewDto listFriendPresence(long tenantId, String accountId) { return listFriendPresence(tenantId, accountId, FriendRosterFilter.ALL); } - FriendPresencePolicyViewDto getFriendPresencePolicy(long tenantId, long accountId); + FriendPresencePolicyViewDto getFriendPresencePolicy(long tenantId, String accountId); FriendPresencePolicyViewDto updateFriendPresencePolicy( - long tenantId, long accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy); + long tenantId, String accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy); } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/GuildService.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/GuildService.java index 58a7ffcb28..641fdfd0a1 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/GuildService.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/GuildService.java @@ -21,5 +21,5 @@ public interface GuildService { GuildMemberDto updateMemberRole(UpdateGuildMemberRoleRequest request); - void removeMember(long tenantId, long guildId, long accountId); + void removeMember(long tenantId, long guildId, String accountId); } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java index e93e9a88e3..3beed75449 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java @@ -6,7 +6,9 @@ import io.micrometer.core.instrument.MeterRegistry; import jakarta.annotation.PostConstruct; import java.time.Instant; +import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.socialgroups.client.LoggingAdminClient; import net.firedevops.firemud.socialgroups.client.ModerationPolicyClient; import net.firedevops.firemud.socialgroups.config.ChatProperties; @@ -85,7 +87,12 @@ void init() { @Timed(value = "chat.send") @Transactional public ChatMessageDto sendMessage(SendMessageRequestDto request) { - logger.info("Chat message from {}", request.senderAccountId()); + String senderAccountId = requireAccountId(request.senderAccountId(), "senderAccountId"); + String recipientAccountId = + request.recipientAccountId() == null + ? null + : requireAccountId(request.recipientAccountId(), "recipientAccountId"); + logger.info("Chat message from {}", senderAccountId); String effectId = normalizeEffectId(request.effectId()); if (effectId != null) { var existing = repository.findByTenantIdAndEffectId(request.tenantId(), effectId); @@ -93,22 +100,21 @@ public ChatMessageDto sendMessage(SendMessageRequestDto request) { return mapper.toDto(existing.orElseThrow()); } } - enforceChatPolicy(request.tenantId(), request.senderAccountId()); + enforceChatPolicy(request.tenantId(), senderAccountId); String filtered = profanityFilter.filter(request.content()); if (!filtered.equals(request.content())) { runAfterCommit( - () -> - safeReportModeration( - request.tenantId(), request.senderAccountId(), "Filtered profanity")); + () -> safeReportModeration(request.tenantId(), senderAccountId, "Filtered profanity")); } ChatMessage message = new ChatMessage(); message.setTenantId(request.tenantId()); - message.setSenderAccountId(request.senderAccountId()); + message.setSenderAccountId(accountUuid(senderAccountId)); message.setContent(filtered); message.setTimestamp(Instant.now()); message.setGuildId(request.guildId()); - message.setRecipientAccountId(request.recipientAccountId()); + message.setRecipientAccountId( + recipientAccountId == null ? null : accountUuid(recipientAccountId)); message.setCityId(request.cityId()); message.setEffectId(effectId); message.setType(request.type()); @@ -142,7 +148,7 @@ public ChatMessageDto sendMessage(SendMessageRequestDto request) { return mapper.toDto(saved); } - private void enforceChatPolicy(long tenantId, long accountId) { + private void enforceChatPolicy(long tenantId, String accountId) { var decision = moderationPolicyClient.evaluateChatSend(tenantId, accountId); if (decision.hasError() && (decision.getError().getCode() != null && !decision.getError().getCode().isBlank())) { @@ -158,7 +164,7 @@ private void enforceChatPolicy(long tenantId, long accountId) { } } - private void safeReportModeration(long tenantId, long accountId, String description) { + private void safeReportModeration(long tenantId, String accountId, String description) { try { loggingAdminClient.reportChatViolation(tenantId, accountId, description); } catch (RuntimeException e) { @@ -186,8 +192,9 @@ public void afterCommit() { @Override @Timed(value = "chat.tells") - public java.util.List getRecentTells(Long tenantId, Long accountId) { - String key = String.format("chat:tell:%d:%d", tenantId, accountId); + public java.util.List getRecentTells(Long tenantId, String accountId) { + String key = + String.format("chat:tell:%d:%s", tenantId, requireAccountId(accountId, "accountId")); try { java.util.List raw = redisTemplate.opsForList().range(key, 0, -1); return raw == null @@ -201,13 +208,13 @@ public java.util.List getRecentTells(Long tenantId, Long accountId) { private String historyKey(SendMessageRequestDto request) { if (request.type() == ChatType.SAY) { - return String.format("chat:say:%d:%d", request.tenantId(), request.senderAccountId()); + return String.format("chat:say:%d:%s", request.tenantId(), request.senderAccountId()); } if (request.type() == ChatType.WHISPER) { - return String.format("chat:whisper:%d:%d", request.tenantId(), request.recipientAccountId()); + return String.format("chat:whisper:%d:%s", request.tenantId(), request.recipientAccountId()); } if (request.type() == ChatType.TELL) { - return String.format("chat:tell:%d:%d", request.tenantId(), request.recipientAccountId()); + return String.format("chat:tell:%d:%s", request.tenantId(), request.recipientAccountId()); } if (request.type() == ChatType.GUILD) { return String.format("chat:guild:%d:%d", request.tenantId(), request.guildId()); @@ -215,7 +222,7 @@ private String historyKey(SendMessageRequestDto request) { if (request.type() == ChatType.CITY) { return String.format("chat:city:%d:%d", request.tenantId(), request.cityId()); } - return String.format("chat:account:%d:%d", request.tenantId(), request.recipientAccountId()); + return String.format("chat:account:%d:%s", request.tenantId(), request.recipientAccountId()); } private ChatProperties.ChatCacheSettings settingsFor(SendMessageRequestDto request) { @@ -240,4 +247,12 @@ private ChatProperties.ChatCacheSettings settingsFor(SendMessageRequestDto reque private String normalizeEffectId(String effectId) { return effectId == null || effectId.isBlank() ? null : effectId.trim(); } + + private String requireAccountId(String accountId, String fieldName) { + return JwtClaims.requireAccountId(accountId, fieldName); + } + + private UUID accountUuid(String accountId) { + return UUID.fromString(requireAccountId(accountId, "accountId")); + } } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java index 925c4c7cf5..86877b0eeb 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java @@ -6,8 +6,10 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.gamesession.v1.AccountPresenceActivityState; import net.firedevops.firemud.gamesession.v1.AccountPresenceEntry; @@ -46,19 +48,23 @@ public class FriendServiceImpl implements FriendService { @Transactional @Timed(value = "friend.add") public FriendLinkDto addFriend(AddFriendRequest request) { - validateNotSelfLink(request.accountId(), request.friendAccountId()); - logger.info( - "Adding account-scoped friend {} -> {}", request.accountId(), request.friendAccountId()); + String accountId = requireAccountId(request.accountId(), "accountId"); + String friendAccountId = requireAccountId(request.friendAccountId(), "friendAccountId"); + validateNotSelfLink(accountId, friendAccountId); + logger.info("Adding account-scoped friend {} -> {}", accountId, friendAccountId); return accountFriendLinkRepository .findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - request.tenantId(), request.accountId(), request.friendAccountId(), "active") + request.tenantId(), + accountUuid(accountId, "accountId"), + accountUuid(friendAccountId, "friendAccountId"), + "active") .map(this::toDto) .orElseGet( () -> { AccountFriendLink link = new AccountFriendLink(); link.setTenantId(request.tenantId()); - link.setAccountId(request.accountId()); - link.setFriendAccountId(request.friendAccountId()); + link.setAccountId(accountUuid(accountId, "accountId")); + link.setFriendAccountId(accountUuid(friendAccountId, "friendAccountId")); link.setStatus("active"); link.setCreatedAt(Instant.now()); return toDto(accountFriendLinkRepository.save(link)); @@ -68,30 +74,35 @@ public FriendLinkDto addFriend(AddFriendRequest request) { @Override @Transactional @Timed(value = "friend.remove") - public void removeFriend(long tenantId, long accountId, long friendAccountId) { + public void removeFriend(long tenantId, String accountId, String friendAccountId) { + accountId = requireAccountId(accountId, "accountId"); + friendAccountId = requireAccountId(friendAccountId, "friendAccountId"); validateNotSelfLink(accountId, friendAccountId); accountFriendLinkRepository .findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - tenantId, accountId, friendAccountId, "active") + tenantId, + accountUuid(accountId, "accountId"), + accountUuid(friendAccountId, "friendAccountId"), + "active") .ifPresent(accountFriendLinkRepository::delete); } @Override @Timed(value = "friend.get") public Optional getFriend( - long tenantId, long accountId, long friendAccountId) { + long tenantId, String accountId, String friendAccountId) { + accountId = requireAccountId(accountId, "accountId"); + friendAccountId = requireAccountId(friendAccountId, "friendAccountId"); + String requestedFriendId = friendAccountId; return listFriends(tenantId, accountId, FriendRosterFilter.ALL).friends().stream() - .filter( - entry -> - entry.friendAccountId() != null - && entry.friendAccountId().longValue() == friendAccountId) + .filter(entry -> requestedFriendId.equals(entry.friendAccountId())) .findFirst(); } @Override @Timed(value = "friend.get.ordinal") public Optional getFriendByOrdinal( - long tenantId, long accountId, int ordinal) { + long tenantId, String accountId, int ordinal) { validateOrdinal(ordinal); return listFriends(tenantId, accountId, FriendRosterFilter.ALL).friends().stream() .filter(entry -> entry.ordinal() == ordinal) @@ -102,14 +113,14 @@ public Optional getFriendByOrdinal( @Transactional @Timed(value = "friend.remove.ordinal") public Optional removeFriendByOrdinal( - long tenantId, long accountId, int ordinal) { + long tenantId, String accountId, int ordinal) { Optional friend = getFriendByOrdinal(tenantId, accountId, ordinal); friend.ifPresent(entry -> removeFriend(tenantId, accountId, entry.friendAccountId())); return friend; } - private void validateNotSelfLink(long accountId, long friendAccountId) { - if (accountId == friendAccountId) { + private void validateNotSelfLink(String accountId, String friendAccountId) { + if (accountId.equals(friendAccountId)) { throw new IllegalArgumentException("Cannot add or remove your own account as a friend"); } } @@ -134,41 +145,43 @@ private FriendLinkDto toDto(AccountFriendLink link) { return new FriendLinkDto( link.getId(), link.getTenantId(), - link.getAccountId(), - link.getFriendAccountId(), + link.getAccountId().toString(), + link.getFriendAccountId().toString(), link.getStatus(), link.getCreatedAt()); } @Override @Timed(value = "friend.list") - public FriendRosterViewDto listFriends(long tenantId, long accountId, FriendRosterFilter filter) { + public FriendRosterViewDto listFriends( + long tenantId, String accountId, FriendRosterFilter filter) { return loadFriendRoster(tenantId, accountId, filter).view(); } private FriendRosterSnapshot loadFriendRoster( - long tenantId, long accountId, FriendRosterFilter filter) { + long tenantId, String accountId, FriendRosterFilter filter) { + accountId = requireAccountId(accountId, "accountId"); FriendRosterFilter effectiveFilter = normalizeRosterFilter(filter); List links = accountFriendLinkRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( - tenantId, accountId, "active"); + tenantId, accountUuid(accountId, "accountId"), "active"); if (links.isEmpty()) { return new FriendRosterSnapshot( new FriendRosterViewDto(effectiveFilter, 0, 0, List.of()), Map.of()); } - List friendAccountIds = - links.stream().map(AccountFriendLink::getFriendAccountId).distinct().toList(); - Map visibilityPolicies = + List friendAccountIds = + links.stream().map(link -> link.getFriendAccountId().toString()).distinct().toList(); + Map visibilityPolicies = Optional.ofNullable(accountClient.getPresenceVisibilityPolicies(tenantId, friendAccountIds)) .orElseGet(Map::of); - List presenceAccountIds = + List presenceAccountIds = friendAccountIds.stream() .filter( friendAccountId -> canQueryPresence(visibilityPolicyFor(friendAccountId, visibilityPolicies))) .toList(); - Map byAccountId = + Map byAccountId = loadFriendPresenceByAccountId(tenantId, accountId, presenceAccountIds, visibilityPolicies); List roster = java.util.stream.IntStream.range(0, links.size()) @@ -186,7 +199,7 @@ private FriendRosterSnapshot loadFriendRoster( @Override @Timed(value = "friend.summary") - public FriendRosterSummaryDto getFriendRosterSummary(long tenantId, long accountId) { + public FriendRosterSummaryDto getFriendRosterSummary(long tenantId, String accountId) { FriendRosterSnapshot snapshot = loadFriendRoster(tenantId, accountId, FriendRosterFilter.ALL); FriendRosterViewDto roster = snapshot.view(); int onlineCount = 0; @@ -235,7 +248,7 @@ public FriendRosterSummaryDto getFriendRosterSummary(long tenantId, long account @Override @Timed(value = "friend.presence.list") public FriendPresenceViewDto listFriendPresence( - long tenantId, long accountId, FriendRosterFilter filter) { + long tenantId, String accountId, FriendRosterFilter filter) { FriendRosterViewDto roster = listFriends(tenantId, accountId, filter); return new FriendPresenceViewDto( roster.filter(), @@ -246,7 +259,8 @@ public FriendPresenceViewDto listFriendPresence( @Override @Timed(value = "friend.visibility.get") - public FriendPresencePolicyViewDto getFriendPresencePolicy(long tenantId, long accountId) { + public FriendPresencePolicyViewDto getFriendPresencePolicy(long tenantId, String accountId) { + accountId = requireAccountId(accountId, "accountId"); FriendPresenceVisibilityPolicyValue visibilityPolicy = accountClient .getPresenceVisibilityPolicy(tenantId, accountId) @@ -258,7 +272,8 @@ public FriendPresencePolicyViewDto getFriendPresencePolicy(long tenantId, long a @Override @Timed(value = "friend.visibility.update") public FriendPresencePolicyViewDto updateFriendPresencePolicy( - long tenantId, long accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy) { + long tenantId, String accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy) { + accountId = requireAccountId(accountId, "accountId"); validateVisibilityPolicy(visibilityPolicy); if (!accountClient.updatePresenceVisibilityPolicy(tenantId, accountId, visibilityPolicy)) { throw new IllegalStateException("Friend presence visibility update unavailable"); @@ -267,23 +282,24 @@ public FriendPresencePolicyViewDto updateFriendPresencePolicy( } private FriendRosterEntryDto toRosterEntry( - int ordinal, AccountFriendLink link, Map byAccountId) { + int ordinal, AccountFriendLink link, Map byAccountId) { return new FriendRosterEntryDto( ordinal, link.getId(), link.getTenantId(), - link.getAccountId(), - link.getFriendAccountId(), + link.getAccountId().toString(), + link.getFriendAccountId().toString(), link.getStatus(), link.getCreatedAt(), byAccountId.getOrDefault( - link.getFriendAccountId(), defaultPresence(link.getFriendAccountId()))); + link.getFriendAccountId().toString(), + defaultPresence(link.getFriendAccountId().toString()))); } private boolean matchesFilter( FriendRosterFilter filter, FriendRosterEntryDto entry, - Map visibilityPolicies) { + Map visibilityPolicies) { FriendPresenceDto presence = entry.presence(); return switch (filter) { case ALL -> true; @@ -311,11 +327,11 @@ private FriendRosterFilter normalizeRosterFilter(FriendRosterFilter filter) { return filter == FriendRosterFilter.HIDDEN_STAFF ? FriendRosterFilter.PRIVATE : filter; } - private Map loadFriendPresenceByAccountId( + private Map loadFriendPresenceByAccountId( long tenantId, - long accountId, - List friendAccountIds, - Map visibilityPolicies) { + String accountId, + List friendAccountIds, + Map visibilityPolicies) { if (friendAccountIds.isEmpty()) { return Map.of(); } @@ -328,9 +344,9 @@ private Map loadFriendPresenceByAccountId( throw new IllegalStateException(response.getError().getMessage()); } - Map byAccountId = new LinkedHashMap<>(); + Map byAccountId = new LinkedHashMap<>(); for (AccountPresenceEntry entry : response.getPresencesList()) { - long friendAccountId = requirePositivePresenceId(entry.getAccountId(), "accountId"); + String friendAccountId = requirePresenceAccountId(entry.getAccountId(), "accountId"); byAccountId.put( friendAccountId, mapPresence( @@ -347,7 +363,7 @@ private boolean canQueryPresence(FriendPresenceVisibilityPolicyValue visibilityP } private FriendPresenceDto mapPresence( - long friendAccountId, + String friendAccountId, AccountPresenceEntry entry, FriendPresenceVisibilityPolicyValue visibilityPolicy) { if (visibilityPolicy != FriendPresenceVisibilityPolicyValue.PUBLIC @@ -372,7 +388,7 @@ private FriendPresenceDto mapPresence( null); } - private FriendPresenceDto defaultPresence(long friendAccountId) { + private FriendPresenceDto defaultPresence(String friendAccountId) { return new FriendPresenceDto( friendAccountId, false, @@ -502,7 +518,7 @@ private Instant visibleLastSeenAt( } private FriendPresenceVisibilityPolicyValue visibilityPolicyFor( - long accountId, Map visibilityPolicies) { + String accountId, Map visibilityPolicies) { if (visibilityPolicies == null) { return FriendPresenceVisibilityPolicyValue.PRIVATE; } @@ -529,16 +545,24 @@ private Long parseOptionalPositivePresenceId(String value, String fieldName) { } } - private long requirePositivePresenceId(String value, String fieldName) { + private String requireAccountId(String value, String fieldName) { + return JwtClaims.requireAccountId(value, fieldName); + } + + private String requirePresenceAccountId(String value, String fieldName) { try { - return RequestIdValidation.requirePositiveLong(value, fieldName); + return requireAccountId(value, fieldName); } catch (IllegalArgumentException ex) { throw new IllegalStateException( "Malformed account presence " + fieldName + ": " + ex.getMessage(), ex); } } + private UUID accountUuid(String value, String fieldName) { + return UUID.fromString(requireAccountId(value, fieldName)); + } + private record FriendRosterSnapshot( FriendRosterViewDto view, - Map visibilityPolicies) {} + Map visibilityPolicies) {} } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java index 20af35a195..7f6d174f07 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java @@ -2,8 +2,10 @@ import io.micrometer.core.annotation.Timed; import java.time.Instant; +import java.util.UUID; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.socialgroups.client.LoggingAdminClient; import net.firedevops.firemud.socialgroups.dto.AddGuildMemberRequest; import net.firedevops.firemud.socialgroups.dto.AddGuildStorageItemRequest; @@ -53,17 +55,18 @@ public class GuildServiceImpl implements GuildService { @Transactional @Timed(value = "guild.create") public GuildDto createGuild(CreateGuildRequest request) { + String ownerAccountId = requireAccountId(request.ownerAccountId(), "ownerAccountId"); logger.info("Creating guild {}", request.name()); Guild guild = new Guild(); guild.setTenantId(request.tenantId()); - guild.setOwnerAccountId(request.ownerAccountId()); + guild.setOwnerAccountId(accountUuid(ownerAccountId)); guild.setName(request.name()); guild.setCreatedAt(Instant.now()); Guild saved = guildRepository.save(guild); runAfterCommit( () -> safeReportModeration( - request.tenantId(), request.ownerAccountId(), "Guild created: " + request.name())); + request.tenantId(), ownerAccountId, "Guild created: " + request.name())); return guildMapper.toDto(saved); } @@ -97,18 +100,19 @@ public GuildAllianceDto createAlliance(CreateAllianceRequest request) { @Transactional @Timed(value = "guild.addMember") public GuildMemberDto addMember(AddGuildMemberRequest request) { - logger.info("Adding member {} to guild {}", request.accountId(), request.guildId()); + String accountId = requireAccountId(request.accountId(), "accountId"); + logger.info("Adding member {} to guild {}", accountId, request.guildId()); GuildMember member = new GuildMember(); member.setTenantId(request.tenantId()); member.setGuildId(request.guildId()); - member.setAccountId(request.accountId()); + member.setAccountId(accountUuid(accountId)); member.setRole(request.role()); GuildMember saved = guildMemberRepository.save(member); member.setId(saved.getId()); runAfterCommit( () -> safeReportModeration( - request.tenantId(), request.accountId(), "Joined guild " + request.guildId())); + request.tenantId(), accountId, "Joined guild " + request.guildId())); return guildMemberMapper.toDto(member); } @@ -116,44 +120,43 @@ public GuildMemberDto addMember(AddGuildMemberRequest request) { @Transactional @Timed(value = "guild.updateMemberRole") public GuildMemberDto updateMemberRole(UpdateGuildMemberRoleRequest request) { + String accountId = requireAccountId(request.accountId(), "accountId"); logger.info( - "Updating member {} in guild {} to role {}", - request.accountId(), - request.guildId(), - request.role()); + "Updating member {} in guild {} to role {}", accountId, request.guildId(), request.role()); GuildMember member = guildMemberRepository .findFirstByTenantIdAndGuildIdAndAccountId( - request.tenantId(), request.guildId(), request.accountId()) + request.tenantId(), request.guildId(), accountUuid(accountId)) .orElseThrow(); member.setRole(request.role()); guildMemberRepository.save(member); runAfterCommit( () -> safeReportModeration( - request.tenantId(), - request.accountId(), - "Updated guild role to " + request.role())); + request.tenantId(), accountId, "Updated guild role to " + request.role())); return guildMemberMapper.toDto(member); } @Override @Transactional @Timed(value = "guild.removeMember") - public void removeMember(long tenantId, long guildId, long accountId) { + public void removeMember(long tenantId, long guildId, String accountId) { + String canonicalAccountId = requireAccountId(accountId, "accountId"); logger.info("Removing member {} from guild {}", accountId, guildId); GuildMember member = guildMemberRepository - .findFirstByTenantIdAndGuildIdAndAccountId(tenantId, guildId, accountId) + .findFirstByTenantIdAndGuildIdAndAccountId( + tenantId, guildId, accountUuid(canonicalAccountId)) .orElse(null); if (member == null) { return; } guildMemberRepository.delete(member); - runAfterCommit(() -> safeReportModeration(tenantId, accountId, "Left guild " + guildId)); + runAfterCommit( + () -> safeReportModeration(tenantId, canonicalAccountId, "Left guild " + guildId)); } - private void safeReportModeration(long tenantId, long accountId, String description) { + private void safeReportModeration(long tenantId, String accountId, String description) { try { loggingAdminClient.reportChatViolation(tenantId, accountId, description); } catch (RuntimeException ex) { @@ -178,4 +181,12 @@ public void afterCommit() { } }); } + + private String requireAccountId(String accountId, String fieldName) { + return JwtClaims.requireAccountId(accountId, fieldName); + } + + private UUID accountUuid(String accountId) { + return UUID.fromString(requireAccountId(accountId, "accountId")); + } } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java index 749e75c4f3..7fa60299a8 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java @@ -2,8 +2,10 @@ import io.micrometer.core.annotation.Timed; import java.time.Instant; +import java.util.UUID; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.socialgroups.dto.MailMessageDto; import net.firedevops.firemud.socialgroups.dto.SendMailRequest; import net.firedevops.firemud.socialgroups.entity.MailMessage; @@ -26,11 +28,15 @@ public class MailServiceImpl implements MailService { @Timed(value = "mail.send") @Transactional public MailMessageDto sendMail(SendMailRequest request) { - logger.info("Mail from {} to {}", request.senderAccountId(), request.recipientAccountId()); + String senderAccountId = + JwtClaims.requireAccountId(request.senderAccountId(), "senderAccountId"); + String recipientAccountId = + JwtClaims.requireAccountId(request.recipientAccountId(), "recipientAccountId"); + logger.info("Mail from {} to {}", senderAccountId, recipientAccountId); MailMessage msg = new MailMessage(); msg.setTenantId(request.tenantId()); - msg.setSenderAccountId(request.senderAccountId()); - msg.setRecipientAccountId(request.recipientAccountId()); + msg.setSenderAccountId(UUID.fromString(senderAccountId)); + msg.setRecipientAccountId(UUID.fromString(recipientAccountId)); msg.setSubject(request.subject()); msg.setContent(request.content()); msg.setSentAt(Instant.now()); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcService.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcService.java index 0423589704..40d15182b2 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcService.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcService.java @@ -7,7 +7,9 @@ import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.socialgroups.dto.AddFriendRequest; import net.firedevops.firemud.socialgroups.dto.CreateGuildRequest; import net.firedevops.firemud.socialgroups.dto.FriendPresenceDto; @@ -104,8 +106,7 @@ public void sendMessage( senderScope.accountId(), mapChatType(request), request.getChannelId(), - RequestIdValidation.parseOptionalPositiveLong( - request.getRecipientId(), "recipientId"), + parseOptionalAccountId(request.getRecipientId(), "recipientId"), RequestIdValidation.parseOptionalPositiveLong(request.getGuildId(), "guildId"), RequestIdValidation.parseOptionalPositiveLong(request.getCityId(), "cityId"), request.getContent(), @@ -189,8 +190,7 @@ public void addFriend( new AddFriendRequest( accountScope.tenantId(), accountScope.accountId(), - RequestIdValidation.requirePositiveLong( - request.getFriendAccountId(), "friendAccountId")); + JwtClaims.requireAccountId(request.getFriendAccountId(), "friendAccountId")); friendService.addFriend(dto); AddFriendResponse response = AddFriendResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); @@ -224,7 +224,7 @@ public void removeFriend( friendService.removeFriend( accountScope.tenantId(), accountScope.accountId(), - RequestIdValidation.requirePositiveLong(request.getFriendAccountId(), "friendAccountId")); + JwtClaims.requireAccountId(request.getFriendAccountId(), "friendAccountId")); responseObserver.onNext(RemoveFriendResponse.newBuilder().setSuccess(true).build()); responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { @@ -261,8 +261,8 @@ public void getFriend( try { AccountScope accountScope = requireAccountScope(request.getTenantId(), request.getAccountId(), "accountId"); - long friendAccountId = - RequestIdValidation.requirePositiveLong(request.getFriendAccountId(), "friendAccountId"); + String friendAccountId = + JwtClaims.requireAccountId(request.getFriendAccountId(), "friendAccountId"); FriendRosterEntryDto friend = friendService .getFriend(accountScope.tenantId(), accountScope.accountId(), friendAccountId) @@ -623,7 +623,7 @@ public void updateFriendPresencePolicy( private FriendPresenceEntry mapPresence(FriendPresenceDto presence) { FriendPresenceEntry.Builder entry = FriendPresenceEntry.newBuilder() - .setFriendAccountId(Long.toString(presence.friendAccountId())) + .setFriendAccountId(presence.friendAccountId()) .setOnline(presence.online()); if (presence.gameInstanceId() != null) { entry.setGameInstanceId(Long.toString(presence.gameInstanceId())); @@ -671,7 +671,7 @@ private FriendRosterEntry mapFriendRosterEntry(FriendRosterEntryDto friend) { FriendRosterEntry.Builder entry = FriendRosterEntry.newBuilder() .setOrdinal(friend.ordinal()) - .setFriendAccountId(Long.toString(friend.friendAccountId())) + .setFriendAccountId(friend.friendAccountId()) .setPresence(mapPresence(friend.presence())); if (friend.friendLinkId() != null) { entry.setFriendLinkId(Long.toString(friend.friendLinkId())); @@ -680,7 +680,7 @@ private FriendRosterEntry mapFriendRosterEntry(FriendRosterEntryDto friend) { entry.setTenantId(Long.toString(friend.tenantId())); } if (friend.accountId() != null) { - entry.setAccountId(Long.toString(friend.accountId())); + entry.setAccountId(friend.accountId()); } if (friend.status() != null && !friend.status().isBlank()) { entry.setStatus(friend.status()); @@ -770,12 +770,16 @@ public void sendMail( AccountScope senderScope = requireAccountScope( request.getTenantId(), request.getSenderAccountId(), "senderAccountId"); + String recipientAccountId = + JwtClaims.requireAccountId(request.getRecipientAccountId(), "recipientAccountId"); + if (!SessionContext.isCurrentAccount(senderScope.accountId())) { + throw new AuthorizationException("Mail sender must match the authenticated account"); + } SendMailRequest dto = new SendMailRequest( senderScope.tenantId(), senderScope.accountId(), - RequestIdValidation.requirePositiveLong( - request.getRecipientAccountId(), "recipientAccountId"), + recipientAccountId, request.getSubject(), request.getContent()); mailService.sendMail(dto); @@ -832,7 +836,7 @@ private net.firedevops.firemud.shared.v1.ErrorDetail internal(String operation, return GrpcAppErrors.internal(meterRegistry, logger, operation, ex); } - private void requireAccountAccess(long tenantId, long accountId) { + private void requireAccountAccess(long tenantId, String accountId) { if (socialAccessGuard.hasAccountAccess(tenantId, accountId)) { return; } @@ -842,12 +846,16 @@ private void requireAccountAccess(long tenantId, long accountId) { private AccountScope requireAccountScope( String tenantIdText, String accountIdText, String accountFieldName) { long tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); - long accountId = RequestIdValidation.requirePositiveLong(accountIdText, accountFieldName); + String accountId = JwtClaims.requireAccountId(accountIdText, accountFieldName); requireAccountAccess(tenantId, accountId); return new AccountScope(tenantId, accountId); } - private record AccountScope(long tenantId, long accountId) {} + private String parseOptionalAccountId(String value, String fieldName) { + return value == null || value.isBlank() ? null : JwtClaims.requireAccountId(value, fieldName); + } + + private record AccountScope(long tenantId, String accountId) {} private FriendPresenceActivityState mapActivityState( net.firedevops.firemud.socialgroups.dto.FriendPresenceActivityState activityState) { diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImpl.java index 4e6ccdc5d0..2f3524a79f 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImpl.java @@ -5,6 +5,7 @@ import java.util.Map; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.socialgroups.dto.VoiceTokenDto; import net.firedevops.firemud.socialgroups.dto.VoiceTokenRequestDto; @@ -27,11 +28,11 @@ public class VoiceChatServiceImpl implements VoiceChatService { @Override @Timed(value = "voice.token.create") public VoiceTokenDto createToken(VoiceTokenRequestDto request) { - logger.info("Issuing voice token for account {}", request.accountId()); + String accountId = JwtClaims.requireAccountId(request.accountId(), "accountId"); + logger.info("Issuing voice token for account {}", accountId); String token = jwtUtil.generateToken( - request.accountId().toString(), - Map.of("tenantId", request.tenantId(), "channelId", request.channelId())); + accountId, Map.of("tenantId", request.tenantId(), "channelId", request.channelId())); Instant expiresAt = Instant.ofEpochMilli(System.currentTimeMillis() + expirationMs); return new VoiceTokenDto(token, expiresAt); } diff --git a/services/social-groups-service/src/main/resources/db/migration/V10__canonical_account_uuid_identity.sql b/services/social-groups-service/src/main/resources/db/migration/V10__canonical_account_uuid_identity.sql new file mode 100644 index 0000000000..c6ef62d125 --- /dev/null +++ b/services/social-groups-service/src/main/resources/db/migration/V10__canonical_account_uuid_identity.sql @@ -0,0 +1,89 @@ +-- Account identity is canonical only when the owning Account service can prove it. +-- Social has no authoritative mapping from its retained numeric selectors to Account UUIDs. +-- Lock every affected table before checking any rows so concurrent writes cannot pass the gate. +-- [jooq ignore start] +LOCK TABLE guilds, + guild_members, + chat_messages, + mail_messages, + account_friend_links, + friend_links + IN ACCESS EXCLUSIVE MODE; +-- [jooq ignore stop] + +-- A populated table is evidence that requires Account-owned authoritative recovery. Refuse the +-- entire transaction unchanged; never cast, derive, map, or discard an Account identity here. +-- [jooq ignore start] +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM guilds) + OR EXISTS (SELECT 1 FROM guild_members) + OR EXISTS (SELECT 1 FROM chat_messages) + OR EXISTS (SELECT 1 FROM mail_messages) + OR EXISTS (SELECT 1 FROM account_friend_links) + OR EXISTS (SELECT 1 FROM friend_links) THEN + RAISE EXCEPTION 'Social Account UUID cutover requires all six affected tables to be empty; retained rows require Account-owned authoritative recovery before retry' + USING ERRCODE = '23514', + CONSTRAINT = 'social_account_uuid_requires_empty_tables'; + END IF; +END; +$$; +-- [jooq ignore stop] + +-- The locked empty-table precondition makes NULL a non-persisted cast expression. jOOQ's DDL +-- parser does not support PostgreSQL USING clauses, so keep only the actual conversions ignored +-- and mirror the resulting UUID column types below with parser-visible ALTER declarations. +-- [jooq ignore start] +ALTER TABLE guilds ALTER COLUMN owner_account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE guild_members ALTER COLUMN account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE chat_messages ALTER COLUMN sender_account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE chat_messages ALTER COLUMN recipient_account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE mail_messages ALTER COLUMN sender_account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE mail_messages ALTER COLUMN recipient_account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE account_friend_links ALTER COLUMN account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE account_friend_links ALTER COLUMN friend_account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE friend_links ALTER COLUMN account_id TYPE UUID USING CAST(NULL AS UUID); +ALTER TABLE friend_links ALTER COLUMN friend_account_id TYPE UUID USING CAST(NULL AS UUID); +-- [jooq ignore stop] + +ALTER TABLE guilds ALTER COLUMN owner_account_id TYPE UUID; +ALTER TABLE guild_members ALTER COLUMN account_id TYPE UUID; +ALTER TABLE chat_messages ALTER COLUMN sender_account_id TYPE UUID; +ALTER TABLE chat_messages ALTER COLUMN recipient_account_id TYPE UUID; +ALTER TABLE mail_messages ALTER COLUMN sender_account_id TYPE UUID; +ALTER TABLE mail_messages ALTER COLUMN recipient_account_id TYPE UUID; +ALTER TABLE account_friend_links ALTER COLUMN account_id TYPE UUID; +ALTER TABLE account_friend_links ALTER COLUMN friend_account_id TYPE UUID; +ALTER TABLE friend_links ALTER COLUMN account_id TYPE UUID; +ALTER TABLE friend_links ALTER COLUMN friend_account_id TYPE UUID; + +ALTER TABLE guilds + ADD CONSTRAINT guilds_owner_account_id_non_nil_check + CHECK (owner_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE guild_members + ADD CONSTRAINT guild_members_account_id_non_nil_check + CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE chat_messages + ADD CONSTRAINT chat_messages_sender_account_id_non_nil_check + CHECK (sender_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE chat_messages + ADD CONSTRAINT chat_messages_recipient_account_id_non_nil_check + CHECK (recipient_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE mail_messages + ADD CONSTRAINT mail_messages_sender_account_id_non_nil_check + CHECK (sender_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE mail_messages + ADD CONSTRAINT mail_messages_recipient_account_id_non_nil_check + CHECK (recipient_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE account_friend_links + ADD CONSTRAINT account_friend_links_account_id_non_nil_check + CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE account_friend_links + ADD CONSTRAINT account_friend_links_friend_account_id_non_nil_check + CHECK (friend_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE friend_links + ADD CONSTRAINT friend_links_account_id_non_nil_check + CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE friend_links + ADD CONSTRAINT friend_links_friend_account_id_non_nil_check + CHECK (friend_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); diff --git a/services/social-groups-service/src/main/resources/openapi.yaml b/services/social-groups-service/src/main/resources/openapi.yaml index 559a7e19ea..76cca712a2 100644 --- a/services/social-groups-service/src/main/resources/openapi.yaml +++ b/services/social-groups-service/src/main/resources/openapi.yaml @@ -2,11 +2,11 @@ openapi: 3.0.3 info: title: Social Groups Service API description: >- - API for friend lists and guild chat. Current REST DTOs use Java Long - tenantId values, serialized as JSON integer/int64 values in this contract. - This is an explicit migration gap from the canonical UUID tenant identity; - the wire type must not change here without converging the DTO, controller, - persistence, and authorization boundaries together. + API for friend lists and guild chat. Account identities use canonical + lowercase, non-nil UUID strings. Tenant, guild, character, and local record + identifiers retain their distinct integer/int64 representations. The + existing canonical tenant-identity migration gap is not resolved by this + Account-only convergence. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 @@ -29,11 +29,11 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid friendAccountId: - type: integer - format: int64 + type: string + format: uuid required: - tenantId - accountId @@ -48,11 +48,11 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid friendAccountId: - type: integer - format: int64 + type: string + format: uuid status: type: string createdAt: @@ -62,8 +62,8 @@ components: type: object properties: friendAccountId: - type: integer - format: int64 + type: string + format: uuid online: type: boolean gameInstanceId: @@ -141,8 +141,8 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid visibilityPolicy: type: string enum: [PUBLIC, FRIENDS_ONLY, PRIVATE, HIDDEN_STAFF] @@ -162,11 +162,11 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid friendAccountId: - type: integer - format: int64 + type: string + format: uuid status: type: string createdAt: @@ -236,11 +236,11 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid recipientAccountId: - type: integer - format: int64 + type: string + format: uuid subject: type: string content: @@ -261,11 +261,11 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid recipientAccountId: - type: integer - format: int64 + type: string + format: uuid subject: type: string content: @@ -283,16 +283,16 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid type: type: string enum: [SAY, WHISPER, TELL, GUILD, CITY, ACCOUNT] channelId: type: string recipientAccountId: - type: integer - format: int64 + type: string + format: uuid guildId: type: integer format: int64 @@ -340,8 +340,8 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid content: type: string timestamp: @@ -354,8 +354,8 @@ components: type: integer format: int64 recipientAccountId: - type: integer - format: int64 + type: string + format: uuid type: type: string effectId: @@ -442,8 +442,8 @@ components: type: integer format: int64 ownerAccountId: - type: integer - format: int64 + type: string + format: uuid name: type: string required: @@ -462,8 +462,8 @@ components: name: type: string ownerAccountId: - type: integer - format: int64 + type: string + format: uuid createdAt: type: string format: date-time @@ -474,8 +474,8 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid channelId: type: string required: @@ -500,8 +500,8 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid role: type: string required: @@ -519,8 +519,8 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid role: type: string required: @@ -541,8 +541,8 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid role: type: string paths: @@ -579,8 +579,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: filter required: false @@ -643,8 +643,8 @@ paths: name: friendAccountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: tenantId required: true @@ -655,8 +655,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend roster entry @@ -677,8 +677,8 @@ paths: name: friendAccountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: tenantId required: true @@ -689,8 +689,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend link removed @@ -716,8 +716,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend roster entry @@ -749,8 +749,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Removed friend roster entry @@ -778,8 +778,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend roster summary @@ -805,8 +805,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: filter required: false @@ -854,8 +854,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend presence visibility policy diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialAccountUuidMigrationIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialAccountUuidMigrationIntegrationTest.java new file mode 100644 index 0000000000..46f21c6bd6 --- /dev/null +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialAccountUuidMigrationIntegrationTest.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.socialgroups; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class SocialAccountUuidMigrationIntegrationTest { + private static final String HISTORY_TABLE = "flyway_schema_history_social_uuid"; + private static final List AFFECTED_TABLES = + List.of( + "guilds", + "guild_members", + "chat_messages", + "mail_messages", + "account_friend_links", + "friend_links"); + private static final Map> ACCOUNT_COLUMNS = + Map.of( + "guilds", List.of("owner_account_id"), + "guild_members", List.of("account_id"), + "chat_messages", List.of("sender_account_id", "recipient_account_id"), + "mail_messages", List.of("sender_account_id", "recipient_account_id"), + "account_friend_links", List.of("account_id", "friend_account_id"), + "friend_links", List.of("account_id", "friend_account_id")); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshAndEmptyV9UpgradeConvergeAllAccountColumnsWithoutChangingOtherIdentityTypes() + throws Exception { + Database fresh = newDatabase(); + flyway(fresh, null).migrate(); + assertIdentityTypes(fresh, "uuid"); + + Database upgraded = newDatabase(); + flyway(upgraded, "9").migrate(); + assertIdentityTypes(upgraded, "bigint"); + List constraintsBefore = constraints(upgraded); + List historyBefore = rows(upgraded, HISTORY_TABLE, "installed_rank"); + flyway(upgraded, null).migrate(); + assertIdentityTypes(upgraded, "uuid"); + assertThat(constraints(upgraded)).containsAll(constraintsBefore); + assertThat(rows(upgraded, HISTORY_TABLE, "installed_rank").subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + // Full runtime migration discovery adds V10 and Saga V1000–V1002 after V9. + assertThat(rows(upgraded, HISTORY_TABLE, "installed_rank")).hasSize(historyBefore.size() + 4); + } + + @ParameterizedTest + @ValueSource( + strings = { + "guilds", + "guild_members", + "chat_messages", + "mail_messages", + "account_friend_links", + "friend_links" + }) + void anyRetainedAffectedTableRefusesWithoutChangingRowsSchemaOrMigrationHistory(String table) + throws Exception { + Database database = newDatabase(); + flyway(database, "9").migrate(); + try (Connection connection = database.dataSource().getConnection()) { + insertRetainedRow(connection, database, table); + } + Map> before = evidence(database); + List constraintsBefore = constraints(database); + + assertThatThrownBy(() -> flyway(database, null).migrate()) + .satisfies(SocialAccountUuidMigrationIntegrationTest::assertRetainedRefusal); + + assertThat(evidence(database)).isEqualTo(before); + assertThat(constraints(database)).isEqualTo(constraintsBefore); + assertIdentityTypes(database, "bigint"); + } + + @Test + void concurrentWriterCommitsBeforeEmptyCheckAndItsEvidenceIsPreserved() throws Exception { + Database database = newDatabase(); + flyway(database, "9").migrate(); + List historyBefore = rows(database, HISTORY_TABLE, "installed_rank"); + Connection writer = database.dataSource().getConnection(); + writer.setAutoCommit(false); + insertRetainedRow(writer, database, "mail_messages"); + List writtenEvidence = rows(writer, database, "mail_messages", "id"); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future migration = executor.submit(() -> flyway(database, null).migrate()); + assertThat(awaitExclusiveLockWait(database, "mail_messages", Duration.ofSeconds(10))) + .isTrue(); + assertThat(migration.isDone()).isFalse(); + writer.commit(); + assertThatThrownBy(() -> migration.get(20, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .satisfies(SocialAccountUuidMigrationIntegrationTest::assertRetainedRefusal); + } finally { + try { + writer.rollback(); + } finally { + writer.close(); + executor.shutdownNow(); + } + } + assertThat(rows(database, "mail_messages", "id")).isEqualTo(writtenEvidence); + assertThat(rows(database, HISTORY_TABLE, "installed_rank")).isEqualTo(historyBefore); + assertIdentityTypes(database, "bigint"); + } + + private static void assertRetainedRefusal(Throwable failure) { + Throwable cause = failure; + while (cause != null && !(cause instanceof SQLException)) { + cause = cause.getCause(); + } + if (cause == null) { + throw new AssertionError("Migration refusal lacked the expected SQL cause", failure); + } + SQLException sql = (SQLException) cause; + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains("Account", "recovery"); + } + + private static boolean awaitExclusiveLockWait(Database database, String table, Duration timeout) + throws Exception { + long deadline = System.nanoTime() + timeout.toNanos(); + try (Connection connection = database.dataSource().getConnection(); + var query = + connection.prepareStatement( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE relation = ?::regclass AND mode = 'AccessExclusiveLock' AND NOT granted)")) { + query.setString(1, qualified(database, table)); + while (System.nanoTime() < deadline) { + try (ResultSet result = query.executeQuery()) { + if (result.next() && result.getBoolean(1)) { + return true; + } + } + Thread.sleep(25L); + } + return false; + } + } + + private static void insertRetainedRow(Connection connection, Database database, String table) + throws SQLException { + String values = + switch (table) { + case "guilds" -> "(id,tenant_id,name,owner_account_id) VALUES(1,11,'Retained guild',42)"; + case "guild_members" -> { + insertRetainedRow(connection, database, "guilds"); + yield "(id,tenant_id,guild_id,account_id,role) VALUES(1,11,1,42,'member')"; + } + case "chat_messages" -> + "(id,tenant_id,sender_account_id,recipient_account_id,content) VALUES(1,11,42,43,'unchanged retained chat')"; + case "mail_messages" -> + "(id,tenant_id,sender_account_id,recipient_account_id,subject,content) VALUES(1,11,42,43,'retained','unchanged mail evidence')"; + case "account_friend_links", "friend_links" -> + "(id,tenant_id,account_id,friend_account_id,status) VALUES(1,11,42,43,'ACTIVE')"; + default -> throw new IllegalArgumentException("Unknown proof table"); + }; + try (Statement statement = connection.createStatement()) { + statement.execute("INSERT INTO " + qualified(database, table) + " " + values); + } + } + + private static Map> evidence(Database database) throws SQLException { + Map> snapshot = new LinkedHashMap<>(); + for (String table : AFFECTED_TABLES) { + snapshot.put(table, rows(database, table, "id")); + } + snapshot.put(HISTORY_TABLE, rows(database, HISTORY_TABLE, "installed_rank")); + return Map.copyOf(snapshot); + } + + private static List rows(Database database, String table, String order) + throws SQLException { + try (Connection connection = database.dataSource().getConnection()) { + return rows(connection, database, table, order); + } + } + + private static List rows( + Connection connection, Database database, String table, String order) throws SQLException { + try (Statement query = connection.createStatement(); + ResultSet result = + query.executeQuery( + "SELECT to_jsonb(t)::text FROM " + + qualified(database, table) + + " t ORDER BY t." + + order)) { + List rows = new ArrayList<>(); + while (result.next()) { + rows.add(result.getString(1)); + } + return List.copyOf(rows); + } + } + + private static List constraints(Database database) throws SQLException { + try (Connection connection = database.dataSource().getConnection(); + var query = + connection.prepareStatement( + "SELECT c.relname || ':' || x.conname || ':' || pg_get_constraintdef(x.oid) FROM pg_constraint x JOIN pg_class c ON c.oid = x.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? ORDER BY c.relname, x.conname")) { + query.setString(1, database.schema()); + try (ResultSet result = query.executeQuery()) { + List constraints = new ArrayList<>(); + while (result.next()) { + constraints.add(result.getString(1)); + } + return List.copyOf(constraints); + } + } + } + + private static void assertIdentityTypes(Database database, String expectedAccountType) + throws SQLException { + try (Connection connection = database.dataSource().getConnection(); + var query = + connection.prepareStatement( + "SELECT udt_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?")) { + for (String table : AFFECTED_TABLES) { + List columns = new ArrayList<>(ACCOUNT_COLUMNS.get(table)); + columns.addAll(List.of("id", "tenant_id")); + for (String column : columns) { + query.setString(1, database.schema()); + query.setString(2, table); + query.setString(3, column); + try (ResultSet result = query.executeQuery()) { + assertThat(result.next()).as("%s.%s", table, column).isTrue(); + String expected = + ACCOUNT_COLUMNS.get(table).contains(column) ? expectedAccountType : "bigint"; + assertThat(result.getString(1)) + .as("%s.%s", table, column) + .isEqualTo(expected.equals("bigint") ? "int8" : expected); + } + } + } + } + } + + private static Flyway flyway(Database database, String target) { + var config = + Flyway.configure() + .dataSource(database.dataSource()) + .schemas(database.schema()) + .defaultSchema(database.schema()) + .table(HISTORY_TABLE) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", database.schema())); + if (target != null) { + config.target(MigrationVersion.fromVersion(target)); + } + return config.load(); + } + + private static Database newDatabase() { + return new Database( + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()), + "social_uuid_" + UUID.randomUUID().toString().replace("-", "")); + } + + private static String qualified(Database database, String table) { + return '"' + database.schema() + "\".\"" + table + '"'; + } + + private record Database(DataSource dataSource, String schema) {} +} diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java index 54f54e73dd..3bafeb1c74 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java @@ -69,6 +69,9 @@ @Import(NoGrpcServerTestConfiguration.class) class SocialGroupsApplicationIntegrationTest { private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; + private static final String FRIEND_UUID_3 = "d52755da-396f-4fd1-80c5-1f1bcb8b1234"; + private static final String FRIEND_UUID_4 = "e63866eb-4a70-4fe2-91d6-202cdc9c2345"; + private static final String FRIEND_UUID_5 = "f74977fc-5b81-40f3-a2e7-313dedad3456"; private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); private static final JwtUtil JWT_UTIL = new JwtUtil("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 3600000L); @@ -114,14 +117,14 @@ void setUpClients() { TEST_ACCOUNT_CLIENT, TEST_SOCIAL_ACCESS_GUARD); Mockito.when( - TEST_MODERATION_POLICY_CLIENT.evaluateChatSend(Mockito.anyLong(), Mockito.anyLong())) + TEST_MODERATION_POLICY_CLIENT.evaluateChatSend(Mockito.anyLong(), Mockito.anyString())) .thenReturn(EvaluateModerationPolicyResponse.newBuilder().setAllowed(true).build()); Mockito.when( TEST_ACCOUNT_CLIENT.getPresenceVisibilityPolicies( Mockito.anyLong(), Mockito.anyCollection())) .thenAnswer( invocation -> { - java.util.Collection accountIds = invocation.getArgument(1); + java.util.Collection accountIds = invocation.getArgument(1); return accountIds.stream() .collect( java.util.stream.Collectors.toMap( @@ -130,7 +133,7 @@ void setUpClients() { net.firedevops.firemud.socialgroups.dto .FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)); }); - Mockito.when(TEST_ACCOUNT_CLIENT.getPresenceVisibilityPolicy(1L, 2L)) + Mockito.when(TEST_ACCOUNT_CLIENT.getPresenceVisibilityPolicy(1L, ACCOUNT_UUID)) .thenReturn( java.util.Optional.of( net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue @@ -159,7 +162,12 @@ void friendRosterRejectsMalformedTenantIdAsInvalidArgument() throws Exception { String token = privilegedAccountToken(); HttpResponse response = - send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=bad&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends?tenantId=bad&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); @@ -176,7 +184,7 @@ void friendRosterRejectsMalformedFilterAsInvalidArgument() throws Exception { token, "http://localhost:" + port - + "/friends?tenantId=1&accountId=2&filter=NOT_A_FILTER")); + + "/friends?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123&filter=NOT_A_FILTER")); assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); @@ -187,7 +195,15 @@ void friendRosterRejectsMalformedFilterAsInvalidArgument() throws Exception { void duplicateEffectIdReturnsExistingChatMessageWithoutRepublishing() { SendMessageRequestDto request = new SendMessageRequestDto( - 1L, 2L, ChatType.SAY, null, 2L, null, null, "hello there", "fx-comm-42"); + 1L, + ACCOUNT_UUID, + ChatType.SAY, + null, + ACCOUNT_UUID, + null, + null, + "hello there", + "fx-comm-42"); ChatMessageDto first = chatService.sendMessage(request); ChatMessageDto replay = chatService.sendMessage(request); @@ -196,7 +212,7 @@ void duplicateEffectIdReturnsExistingChatMessageWithoutRepublishing() { assertThat(chatMessageRepository.findByTenantIdAndEffectId(1L, "fx-comm-42")) .hasValueSatisfying(message -> assertThat(message.getId()).isEqualTo(first.id())); - List redisRange = redisTemplate.opsForList().range("chat:say:1:2", 0, -1); + List redisRange = redisTemplate.opsForList().range("chat:say:1:" + ACCOUNT_UUID, 0, -1); List cachedMessages = new ArrayList<>(redisRange == null ? List.of() : redisRange); assertThat(cachedMessages).containsExactly("hello there"); } @@ -212,18 +228,20 @@ void friendRosterAndPresenceEndpointsReturnCanonicalEmbeddedPresence() throws Ex .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build()); assertThat(addResponse.statusCode()).isEqualTo(200); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "d52755da-396f-4fd1-80c5-1f1bcb8b1234"); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, ACCOUNT_UUID, List.of(FRIEND_UUID_3))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId("d52755da-396f-4fd1-80c5-1f1bcb8b1234") .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -245,9 +263,15 @@ void friendRosterAndPresenceEndpointsReturnCanonicalEmbeddedPresence() throws Ex .build()); HttpResponse rosterResponse = - send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(rosterResponse.statusCode()).isEqualTo(200); - assertThat(rosterResponse.body()).contains("\"friendAccountId\":3"); + assertThat(rosterResponse.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); assertThat(rosterResponse.body()).contains("\"status\":\"active\""); assertThat(rosterResponse.body()).contains("\"presence\""); assertThat(rosterResponse.body()).contains("\"characterName\":\"Sora\""); @@ -256,26 +280,40 @@ void friendRosterAndPresenceEndpointsReturnCanonicalEmbeddedPresence() throws Ex HttpResponse presenceResponse = send( authedGet( - token, "http://localhost:" + port + "/friends/presence?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/presence?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(presenceResponse.statusCode()).isEqualTo(200); - assertThat(presenceResponse.body()).contains("\"friendAccountId\":3"); + assertThat(presenceResponse.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); assertThat(presenceResponse.body()).contains("\"worldSlug\":\"demo\""); assertThat(presenceResponse.body()).contains("\"characterName\":\"Sora\""); HttpResponse detailResponse = - send(authedGet(token, "http://localhost:" + port + "/friends/3?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends/d52755da-396f-4fd1-80c5-1f1bcb8b1234?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(detailResponse.statusCode()).isEqualTo(200); assertThat(detailResponse.body()).contains("\"friendLinkId\""); - assertThat(detailResponse.body()).contains("\"friendAccountId\":3"); + assertThat(detailResponse.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); assertThat(detailResponse.body()).contains("\"characterName\":\"Sora\""); HttpResponse ordinalDetailResponse = send( authedGet( - token, "http://localhost:" + port + "/friends/entry/1?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/entry/1?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(ordinalDetailResponse.statusCode()).isEqualTo(200); assertThat(ordinalDetailResponse.body()).contains("\"ordinal\":1"); - assertThat(ordinalDetailResponse.body()).contains("\"friendAccountId\":3"); + assertThat(ordinalDetailResponse.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); } @Test @@ -288,19 +326,27 @@ void friendRosterEndpointFallsBackToOfflineWhenPresenceIsUnavailable() throws Ex .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "d52755da-396f-4fd1-80c5-1f1bcb8b1234"); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, ACCOUNT_UUID, List.of(FRIEND_UUID_3))) .thenReturn(QueryAccountPresenceResponse.newBuilder().build()); HttpResponse rosterResponse = - send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(rosterResponse.statusCode()).isEqualTo(200); - assertThat(rosterResponse.body()).contains("\"friendAccountId\":3"); + assertThat(rosterResponse.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); assertThat(rosterResponse.body()).contains("\"online\":false"); } @@ -314,10 +360,11 @@ void friendRosterEndpointSupportsCanonicalOnlineFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "d52755da-396f-4fd1-80c5-1f1bcb8b1234"); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -325,32 +372,45 @@ void friendRosterEndpointSupportsCanonicalOnlineFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":4} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"e63866eb-4a70-4fe2-91d6-202cdc9c2345"} """)) .build()); - acceptFriendLink(1L, 2L, 4L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "e63866eb-4a70-4fe2-91d6-202cdc9c2345"); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L, 4L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, ACCOUNT_UUID, List.of(FRIEND_UUID_3, FRIEND_UUID_4))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId("d52755da-396f-4fd1-80c5-1f1bcb8b1234") + .setOnline(true) + .build()) .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("4").setOnline(false).build()) + AccountPresenceEntry.newBuilder() + .setAccountId("e63866eb-4a70-4fe2-91d6-202cdc9c2345") + .setOnline(false) + .build()) .build()); HttpResponse response = send( authedGet( token, - "http://localhost:" + port + "/friends?tenantId=1&accountId=2&filter=ONLINE")); + "http://localhost:" + + port + + "/friends?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123&filter=ONLINE")); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body()).contains("\"filter\":\"ONLINE\""); assertThat(response.body()).contains("\"totalCount\":2"); assertThat(response.body()).contains("\"matchCount\":1"); - assertThat(response.body()).contains("\"friendAccountId\":3"); - assertThat(response.body()).doesNotContain("\"friendAccountId\":4"); + assertThat(response.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); + assertThat(response.body()) + .doesNotContain("\"friendAccountId\":\"e63866eb-4a70-4fe2-91d6-202cdc9c2345\""); } @Test @@ -363,10 +423,11 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "d52755da-396f-4fd1-80c5-1f1bcb8b1234"); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -374,17 +435,20 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":4} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"e63866eb-4a70-4fe2-91d6-202cdc9c2345"} """)) .build()); - acceptFriendLink(1L, 2L, 4L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "e63866eb-4a70-4fe2-91d6-202cdc9c2345"); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L, 4L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, ACCOUNT_UUID, List.of(FRIEND_UUID_3, FRIEND_UUID_4))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId("d52755da-396f-4fd1-80c5-1f1bcb8b1234") .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -392,7 +456,7 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId("e63866eb-4a70-4fe2-91d6-202cdc9c2345") .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -404,14 +468,18 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { send( authedGet( token, - "http://localhost:" + port + "/friends?tenantId=1&accountId=2&filter=SHARED")); + "http://localhost:" + + port + + "/friends?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123&filter=SHARED")); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body()).contains("\"filter\":\"SHARED\""); assertThat(response.body()).contains("\"totalCount\":2"); assertThat(response.body()).contains("\"matchCount\":1"); - assertThat(response.body()).contains("\"friendAccountId\":3"); - assertThat(response.body()).doesNotContain("\"friendAccountId\":4"); + assertThat(response.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); + assertThat(response.body()) + .doesNotContain("\"friendAccountId\":\"e63866eb-4a70-4fe2-91d6-202cdc9c2345\""); } @Test @@ -424,10 +492,11 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "d52755da-396f-4fd1-80c5-1f1bcb8b1234"); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -435,19 +504,25 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":4} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"e63866eb-4a70-4fe2-91d6-202cdc9c2345"} """)) .build()); - acceptFriendLink(1L, 2L, 4L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "e63866eb-4a70-4fe2-91d6-202cdc9c2345"); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L, 4L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, ACCOUNT_UUID, List.of(FRIEND_UUID_3, FRIEND_UUID_4))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId("d52755da-396f-4fd1-80c5-1f1bcb8b1234") + .setOnline(true) + .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId("e63866eb-4a70-4fe2-91d6-202cdc9c2345") .setOnline(false) .setLastSeenAtMs(1_744_353_730_000L) .build()) @@ -456,7 +531,10 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { HttpResponse response = send( authedGet( - token, "http://localhost:" + port + "/friends/summary?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/summary?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body()).contains("\"totalCount\":2"); @@ -473,77 +551,154 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { @Test void friendEndpointsRequireReciprocalActiveLinksWithinRequestedTenant() throws Exception { String token = privilegedAccountToken(); - saveFriendLink(1L, 2L, 3L, "active"); - saveFriendLink(1L, 2L, 4L, "active"); - saveFriendLink(1L, 4L, 2L, "inactive"); - saveFriendLink(1L, 2L, 5L, "active"); - saveFriendLink(1L, 5L, 2L, "active"); + saveFriendLink( + 1L, + "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", + "d52755da-396f-4fd1-80c5-1f1bcb8b1234", + "active"); + saveFriendLink( + 1L, + "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", + "e63866eb-4a70-4fe2-91d6-202cdc9c2345", + "active"); + saveFriendLink( + 1L, + "e63866eb-4a70-4fe2-91d6-202cdc9c2345", + "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", + "inactive"); + saveFriendLink( + 1L, + "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", + "f74977fc-5b81-40f3-a2e7-313dedad3456", + "active"); + saveFriendLink( + 1L, + "f74977fc-5b81-40f3-a2e7-313dedad3456", + "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", + "active"); HttpResponse tenantOneRoster = - send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(tenantOneRoster.statusCode()).isEqualTo(200); assertThat(tenantOneRoster.body()).contains("\"totalCount\":1"); - assertThat(tenantOneRoster.body()).contains("\"friendAccountId\":5"); - assertThat(tenantOneRoster.body()).doesNotContain("\"friendAccountId\":3"); - assertThat(tenantOneRoster.body()).doesNotContain("\"friendAccountId\":4"); + assertThat(tenantOneRoster.body()) + .contains("\"friendAccountId\":\"f74977fc-5b81-40f3-a2e7-313dedad3456\""); + assertThat(tenantOneRoster.body()) + .doesNotContain("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); + assertThat(tenantOneRoster.body()) + .doesNotContain("\"friendAccountId\":\"e63866eb-4a70-4fe2-91d6-202cdc9c2345\""); HttpResponse tenantOnePresence = send( authedGet( - token, "http://localhost:" + port + "/friends/presence?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/presence?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(tenantOnePresence.statusCode()).isEqualTo(200); - assertThat(tenantOnePresence.body()).contains("\"friendAccountId\":5"); - assertThat(tenantOnePresence.body()).doesNotContain("\"friendAccountId\":3"); - assertThat(tenantOnePresence.body()).doesNotContain("\"friendAccountId\":4"); + assertThat(tenantOnePresence.body()) + .contains("\"friendAccountId\":\"f74977fc-5b81-40f3-a2e7-313dedad3456\""); + assertThat(tenantOnePresence.body()) + .doesNotContain("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); + assertThat(tenantOnePresence.body()) + .doesNotContain("\"friendAccountId\":\"e63866eb-4a70-4fe2-91d6-202cdc9c2345\""); HttpResponse reciprocalDetail = - send(authedGet(token, "http://localhost:" + port + "/friends/5?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends/f74977fc-5b81-40f3-a2e7-313dedad3456?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(reciprocalDetail.statusCode()).isEqualTo(200); - assertThat(reciprocalDetail.body()).contains("\"friendAccountId\":5"); + assertThat(reciprocalDetail.body()) + .contains("\"friendAccountId\":\"f74977fc-5b81-40f3-a2e7-313dedad3456\""); HttpResponse reciprocalOrdinal = send( authedGet( - token, "http://localhost:" + port + "/friends/entry/1?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/entry/1?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(reciprocalOrdinal.statusCode()).isEqualTo(200); - assertThat(reciprocalOrdinal.body()).contains("\"friendAccountId\":5"); + assertThat(reciprocalOrdinal.body()) + .contains("\"friendAccountId\":\"f74977fc-5b81-40f3-a2e7-313dedad3456\""); HttpResponse tenantOneSummary = send( authedGet( - token, "http://localhost:" + port + "/friends/summary?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/summary?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(tenantOneSummary.statusCode()).isEqualTo(200); assertThat(tenantOneSummary.body()).contains("\"totalCount\":1"); HttpResponse oneWayDetail = - send(authedGet(token, "http://localhost:" + port + "/friends/3?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends/d52755da-396f-4fd1-80c5-1f1bcb8b1234?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(oneWayDetail.statusCode()).isEqualTo(404); HttpResponse inactiveReciprocalDetail = - send(authedGet(token, "http://localhost:" + port + "/friends/4?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends/e63866eb-4a70-4fe2-91d6-202cdc9c2345?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(inactiveReciprocalDetail.statusCode()).isEqualTo(404); HttpResponse wrongTenantRoster = - send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=2&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends?tenantId=2&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(wrongTenantRoster.statusCode()).isEqualTo(200); assertThat(wrongTenantRoster.body()).contains("\"totalCount\":0"); HttpResponse wrongTenantPresence = send( authedGet( - token, "http://localhost:" + port + "/friends/presence?tenantId=2&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/presence?tenantId=2&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(wrongTenantPresence.statusCode()).isEqualTo(200); - assertThat(wrongTenantPresence.body()).doesNotContain("\"friendAccountId\":5"); + assertThat(wrongTenantPresence.body()) + .doesNotContain("\"friendAccountId\":\"f74977fc-5b81-40f3-a2e7-313dedad3456\""); HttpResponse wrongTenantDetail = - send(authedGet(token, "http://localhost:" + port + "/friends/5?tenantId=2&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends/f74977fc-5b81-40f3-a2e7-313dedad3456?tenantId=2&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(wrongTenantDetail.statusCode()).isEqualTo(404); HttpResponse wrongTenantOrdinal = send( authedGet( - token, "http://localhost:" + port + "/friends/entry/1?tenantId=2&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/entry/1?tenantId=2&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(wrongTenantOrdinal.statusCode()).isEqualTo(404); HttpResponse wrongTenantSummary = send( authedGet( - token, "http://localhost:" + port + "/friends/summary?tenantId=2&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/summary?tenantId=2&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(wrongTenantSummary.statusCode()).isEqualTo(200); assertThat(wrongTenantSummary.body()).contains("\"totalCount\":0"); } @@ -558,7 +713,7 @@ void addFriendIsIdempotentForExistingActiveAccountLink() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build(); @@ -567,18 +722,21 @@ void addFriendIsIdempotentForExistingActiveAccountLink() throws Exception { assertThat(firstResponse.statusCode()).isEqualTo(200); assertThat(secondResponse.statusCode()).isEqualTo(200); - assertThat(accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus(1L, 2L, "active")) + assertThat( + accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus( + 1L, java.util.UUID.fromString("c41744c9-285e-4ed0-9fb4-0f0acb7a0123"), "active")) .hasSize(1); assertThat( accountFriendLinkRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( - 1L, 2L, "active")) + 1L, java.util.UUID.fromString("c41744c9-285e-4ed0-9fb4-0f0acb7a0123"), "active")) .isEmpty(); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "d52755da-396f-4fd1-80c5-1f1bcb8b1234"); assertThat( accountFriendLinkRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( - 1L, 2L, "active")) + 1L, java.util.UUID.fromString("c41744c9-285e-4ed0-9fb4-0f0acb7a0123"), "active")) .hasSize(1); } @@ -593,13 +751,15 @@ void addFriendRejectsSelfLink() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":2} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123"} """)) .build()); assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("Cannot add or remove your own account as a friend"); - assertThat(accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus(1L, 2L, "active")) + assertThat( + accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus( + 1L, java.util.UUID.fromString("c41744c9-285e-4ed0-9fb4-0f0acb7a0123"), "active")) .isEmpty(); } @@ -613,7 +773,7 @@ void removeFriendDeletesExistingActiveAccountLinkAndIsIdempotent() throws Except .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build(); @@ -622,21 +782,29 @@ void removeFriendDeletesExistingActiveAccountLinkAndIsIdempotent() throws Except HttpResponse firstDelete = send( HttpRequest.newBuilder( - URI.create("http://localhost:" + port + "/friends/3?tenantId=1&accountId=2")) + URI.create( + "http://localhost:" + + port + + "/friends/d52755da-396f-4fd1-80c5-1f1bcb8b1234?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .DELETE() .build()); HttpResponse secondDelete = send( HttpRequest.newBuilder( - URI.create("http://localhost:" + port + "/friends/3?tenantId=1&accountId=2")) + URI.create( + "http://localhost:" + + port + + "/friends/d52755da-396f-4fd1-80c5-1f1bcb8b1234?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .DELETE() .build()); assertThat(firstDelete.statusCode()).isEqualTo(200); assertThat(secondDelete.statusCode()).isEqualTo(200); - assertThat(accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus(1L, 2L, "active")) + assertThat( + accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus( + 1L, java.util.UUID.fromString("c41744c9-285e-4ed0-9fb4-0f0acb7a0123"), "active")) .isEmpty(); } @@ -650,24 +818,30 @@ void removeFriendByOrdinalDeletesCanonicalRosterEntry() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","friendAccountId":"d52755da-396f-4fd1-80c5-1f1bcb8b1234"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink( + 1L, "c41744c9-285e-4ed0-9fb4-0f0acb7a0123", "d52755da-396f-4fd1-80c5-1f1bcb8b1234"); HttpResponse deleteResponse = send( HttpRequest.newBuilder( URI.create( - "http://localhost:" + port + "/friends/entry/1?tenantId=1&accountId=2")) + "http://localhost:" + + port + + "/friends/entry/1?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .DELETE() .build()); assertThat(deleteResponse.statusCode()).isEqualTo(200); - assertThat(deleteResponse.body()).contains("\"friendAccountId\":3"); - assertThat(accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus(1L, 2L, "active")) + assertThat(deleteResponse.body()) + .contains("\"friendAccountId\":\"d52755da-396f-4fd1-80c5-1f1bcb8b1234\""); + assertThat( + accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus( + 1L, java.util.UUID.fromString("c41744c9-285e-4ed0-9fb4-0f0acb7a0123"), "active")) .isEmpty(); } @@ -678,7 +852,10 @@ void friendVisibilityEndpointsExposeCanonicalPolicyReadAndWrite() throws Excepti HttpResponse getResponse = send( authedGet( - token, "http://localhost:" + port + "/friends/visibility?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/visibility?tenantId=1&accountId=c41744c9-285e-4ed0-9fb4-0f0acb7a0123")); assertThat(getResponse.statusCode()).isEqualTo(200); assertThat(getResponse.body()).contains("\"currentPolicy\":\"FRIENDS_ONLY\""); @@ -686,7 +863,7 @@ void friendVisibilityEndpointsExposeCanonicalPolicyReadAndWrite() throws Excepti Mockito.when( TEST_ACCOUNT_CLIENT.updatePresenceVisibilityPolicy( 1L, - 2L, + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue .PRIVATE)) .thenReturn(true); @@ -699,7 +876,7 @@ void friendVisibilityEndpointsExposeCanonicalPolicyReadAndWrite() throws Excepti .PUT( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"visibilityPolicy":"PRIVATE"} + {"tenantId":1,"accountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","visibilityPolicy":"PRIVATE"} """)) .build()); @@ -714,21 +891,22 @@ private static HttpRequest authedGet(String token, String uri) { .build(); } - private void acceptFriendLink(long tenantId, long accountId, long friendAccountId) { + private void acceptFriendLink(long tenantId, String accountId, String friendAccountId) { AccountFriendLink reciprocal = new AccountFriendLink(); reciprocal.setTenantId(tenantId); - reciprocal.setAccountId(friendAccountId); - reciprocal.setFriendAccountId(accountId); + reciprocal.setAccountId(java.util.UUID.fromString(friendAccountId)); + reciprocal.setFriendAccountId(java.util.UUID.fromString(accountId)); reciprocal.setStatus("active"); reciprocal.setCreatedAt(java.time.Instant.now()); accountFriendLinkRepository.save(reciprocal); } - private void saveFriendLink(long tenantId, long accountId, long friendAccountId, String status) { + private void saveFriendLink( + long tenantId, String accountId, String friendAccountId, String status) { AccountFriendLink link = new AccountFriendLink(); link.setTenantId(tenantId); - link.setAccountId(accountId); - link.setFriendAccountId(friendAccountId); + link.setAccountId(java.util.UUID.fromString(accountId)); + link.setFriendAccountId(java.util.UUID.fromString(friendAccountId)); link.setStatus(status); link.setCreatedAt(java.time.Instant.now()); accountFriendLinkRepository.save(link); diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java index b75de99956..6702c10ee3 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java @@ -1,10 +1,13 @@ package net.firedevops.firemud.socialgroups.client; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; @@ -13,12 +16,17 @@ import java.lang.reflect.Field; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.TimeUnit; -import java.util.stream.LongStream; +import java.util.stream.Stream; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetProfileResponse; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesRequest; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse; import net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry; +import net.firedevops.firemud.account.v1.UpdateProfileRequest; +import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -26,9 +34,14 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; class AccountClientTest { + private static final String ACCOUNT_ID = "cc51ef2c-9a14-4c56-98bd-af7f8e4c60c1"; + private static final String OTHER_ACCOUNT_ID = "816018fe-bf4b-4946-9bb7-3a7073edc1a8"; @Test void batchesPresenceVisibilityPolicyReadsAtTheAccountServiceLimit() throws Exception { @@ -52,21 +65,25 @@ void batchesPresenceVisibilityPolicyReadsAtTheAccountServiceLimit() throws Excep .build(); }); AccountClient client = newClient(stub); - List accountIds = LongStream.rangeClosed(1L, 101L).boxed().toList(); + List accountIds = + Stream.generate(() -> UUID.randomUUID().toString()).limit(101).toList(); - Map policies = + Map policies = client.getPresenceVisibilityPolicies(11L, accountIds); assertThat(policies) .hasSize(101) - .containsEntry(1L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY) - .containsEntry(101L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); + .containsEntry(accountIds.getFirst(), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY) + .containsEntry(accountIds.getLast(), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); ArgumentCaptor requests = ArgumentCaptor.forClass(ListPresenceVisibilityPoliciesRequest.class); verify(stub, times(2)).listPresenceVisibilityPolicies(requests.capture()); assertThat(requests.getAllValues()) .extracting(ListPresenceVisibilityPoliciesRequest::getAccountIdsCount) .containsExactly(100, 1); + assertThat(requests.getAllValues()) + .extracting(request -> List.copyOf(request.getAccountIdsList())) + .containsExactly(accountIds.subList(0, 100), accountIds.subList(100, 101)); assertThat(requests.getAllValues()) .extracting(ListPresenceVisibilityPoliciesRequest::getTenantId) .containsOnly("11"); @@ -113,11 +130,189 @@ void recordsApplicationErrorsFromPresenceVisibilityPolicyReads() throws Exceptio MeterRegistry meterRegistry = new SimpleMeterRegistry(); AccountClient client = newClient(stub, meterRegistry); - assertThat(client.getPresenceVisibilityPolicies(11L, List.of(1L))).isEmpty(); + assertThat(client.getPresenceVisibilityPolicies(11L, List.of(ACCOUNT_ID))).isEmpty(); assertThat(meterRegistry.counter("grpc.app_error", "code", "UNAVAILABLE").count()) .isEqualTo(1.0d); } + @ParameterizedTest + @ValueSource( + strings = { + "42", + "", + " cc51ef2c-9a14-4c56-98bd-af7f8e4c60c1", + "CC51EF2C-9A14-4C56-98BD-AF7F8E4C60C1", + "00000000-0000-0000-0000-000000000000" + }) + void rejectsNoncanonicalAccountBeforeProfileOrBatchCall(String accountId) throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + AccountClient client = newClient(stub); + + assertThatThrownBy(() -> client.getPresenceVisibilityPolicy(11L, accountId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.getPresenceVisibilityPolicies(11L, List.of(accountId))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.updatePresenceVisibilityPolicy( + 11L, accountId, FriendPresenceVisibilityPolicyValue.PRIVATE)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + } + + @Test + void verifiesProfileAccountAndTenantBeforeReturningPolicy() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = profileStub(profileJson(ACCOUNT_ID, "11")); + AccountClient client = newClient(stub); + + assertThat(client.getPresenceVisibilityPolicy(11L, ACCOUNT_ID)) + .contains(FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); + ArgumentCaptor request = ArgumentCaptor.forClass(GetProfileRequest.class); + verify(stub).getProfile(request.capture()); + assertThat(request.getValue().getAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(request.getValue().getTenantId()).isEqualTo("11"); + } + + @ParameterizedTest + @MethodSource("untrustedProfiles") + void refusesMissingMalformedOrMismatchedProfileIdentity(String profileJson) throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = profileStub(profileJson); + AccountClient client = newClient(stub); + + assertThat(client.getPresenceVisibilityPolicy(11L, ACCOUNT_ID)).isEmpty(); + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PRIVATE)) + .isFalse(); + verify(stub, never()).updateProfile(any()); + } + + private static Stream untrustedProfiles() { + return Stream.of( + "{\"presenceVisibilityPolicy\":\"PUBLIC\"}", + profileJson(OTHER_ACCOUNT_ID, "11"), + profileJson("42", "11"), + profileJson(ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT), "11"), + profileJson(ACCOUNT_ID, "12"), + profileJson(ACCOUNT_ID, "\"11\""), + profileJson(ACCOUNT_ID, "18446744073709551627")); + } + + @Test + void updateRequiresExactAccountAndTenantEcho() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = profileStub(profileJson(ACCOUNT_ID, "11")); + AccountClient client = newClient(stub); + when(stub.updateProfile(any())) + .thenReturn( + UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(ACCOUNT_ID) + .setTenantId("11") + .build(), + UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(OTHER_ACCOUNT_ID) + .setTenantId("11") + .build(), + UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(ACCOUNT_ID) + .setTenantId("12") + .build(), + UpdateProfileResponse.newBuilder().setSuccess(true).build()); + + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PRIVATE)) + .isTrue(); + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PRIVATE)) + .isFalse(); + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PRIVATE)) + .isFalse(); + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PRIVATE)) + .isFalse(); + ArgumentCaptor requests = + ArgumentCaptor.forClass(UpdateProfileRequest.class); + verify(stub, times(4)).updateProfile(requests.capture()); + assertThat(requests.getAllValues()) + .extracting(UpdateProfileRequest::getAccountId) + .containsOnly(ACCOUNT_ID); + assertThat(requests.getAllValues()) + .extracting(UpdateProfileRequest::getTenantId) + .containsOnly("11"); + } + + @Test + void ignoresNumericUnexpectedAndUnknownBatchPolicyEntries() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.listPresenceVisibilityPolicies(any())) + .thenReturn( + ListPresenceVisibilityPoliciesResponse.newBuilder() + .addPolicies( + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId("42") + .setPolicy("PUBLIC")) + .addPolicies( + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(OTHER_ACCOUNT_ID) + .setPolicy("PUBLIC")) + .addPolicies( + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(ACCOUNT_ID) + .setPolicy("UNKNOWN")) + .build()); + + assertThat(newClient(stub).getPresenceVisibilityPolicies(11L, List.of(ACCOUNT_ID))).isEmpty(); + } + + @Test + void laterBatchFailureDiscardsEarlierPartialVisibility() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + List accounts = Stream.generate(() -> UUID.randomUUID().toString()).limit(101).toList(); + when(stub.listPresenceVisibilityPolicies(any())) + .thenReturn( + ListPresenceVisibilityPoliciesResponse.newBuilder() + .addPolicies( + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(accounts.getFirst()) + .setPolicy("PUBLIC")) + .build(), + ListPresenceVisibilityPoliciesResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE")) + .build()); + + assertThat(newClient(stub).getPresenceVisibilityPolicies(11L, accounts)).isEmpty(); + verify(stub, times(2)).listPresenceVisibilityPolicies(any()); + } + + private static String profileJson(String accountId, String tenantJson) { + return "{\"accountId\":\"" + + accountId + + "\",\"tenantId\":" + + tenantJson + + ",\"displayName\":\"Player\",\"bio\":\"Bio\",\"presenceVisibilityPolicy\":\"FRIENDS_ONLY\"}"; + } + + private static AccountServiceGrpc.AccountServiceBlockingStub profileStub(String profileJson) { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.getProfile(any())) + .thenReturn(GetProfileResponse.newBuilder().setProfileJson(profileJson).build()); + return stub; + } + private static AccountClient newClient(AccountServiceGrpc.AccountServiceBlockingStub stub) throws Exception { return newClient(stub, new SimpleMeterRegistry()); diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java index 7355725e1e..cb60b9faa6 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java @@ -23,11 +23,13 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.QueryAccountPresenceRequest; import net.firedevops.firemud.loggingadmin.v1.CreateReportRequest; import net.firedevops.firemud.loggingadmin.v1.CreateReportResponse; import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyRequest; @@ -37,6 +39,8 @@ import org.springframework.beans.factory.ObjectProvider; class SocialInternalGrpcClientAuthTest { + private static final String ACCOUNT_ID = "cc51ef2c-9a14-4c56-98bd-af7f8e4c60c1"; + private static final String FRIEND_ID = "816018fe-bf4b-4946-9bb7-3a7073edc1a8"; private static final Metadata.Key AUTH_HEADER = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); @@ -125,12 +129,92 @@ void loggingAdminClientPropagatesApplicationErrors() throws Exception { runtimeIdentityProvider()); client.init(); - assertThatThrownBy(() -> client.reportChatViolation(7L, 42L, "Filtered profanity")) + assertThatThrownBy(() -> client.reportChatViolation(7L, ACCOUNT_ID, "Filtered profanity")) .isInstanceOf(IllegalStateException.class) .hasMessage("Chat violation report failed: UNAVAILABLE: Report creation unavailable") .hasMessageNotContaining("Filtered profanity"); } + @Test + void socialRequestsCarryUuidIdentitiesWithoutNumericAliases() throws Exception { + CapturingChannel channel = new CapturingChannel(); + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())).thenReturn(channel); + LoggingAdminClient reports = + new LoggingAdminClient( + new ServiceEndpointsProperties(), + plaintextGrpcProperties(), + factory, + jwtUtil, + runtimeIdentityProvider()); + reports.init(); + reports.reportChatViolation(7L, ACCOUNT_ID, "Filtered profanity"); + CreateReportRequest report = (CreateReportRequest) channel.lastRequest; + assertThat(report.getReporterAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(report.getTargetAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(report.getTenantId()).isEqualTo("7"); + assertInternalSocialServiceToken(channel); + + ModerationPolicyClient policies = + new ModerationPolicyClient( + new ServiceEndpointsProperties(), + plaintextGrpcProperties(), + factory, + jwtUtil, + runtimeIdentityProvider()); + policies.init(); + policies.evaluateChatSend(7L, ACCOUNT_ID); + EvaluateModerationPolicyRequest policy = (EvaluateModerationPolicyRequest) channel.lastRequest; + assertThat(policy.getAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(policy.getTenantId()).isEqualTo("7"); + assertInternalSocialServiceToken(channel); + + GameSessionClient presence = + new GameSessionClient( + new ServiceEndpointsProperties(), + plaintextGrpcProperties(), + factory, + BlockingGrpcStubCustomizer.noop()); + presence.init(); + presence.queryAccountPresence(7L, ACCOUNT_ID, List.of(FRIEND_ID)); + QueryAccountPresenceRequest request = (QueryAccountPresenceRequest) channel.lastRequest; + assertThat(request.getViewerAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(request.getAccountIdsList()).containsExactly(FRIEND_ID); + assertThat(request.getTenantId()).isEqualTo("7"); + } + + @Test + void malformedSocialAccountSelectorsFailBeforeAnyRpc() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + LoggingAdminClient reports = + new LoggingAdminClient( + endpoints, plaintextGrpcProperties(), factory, jwtUtil, runtimeIdentityProvider()); + ModerationPolicyClient policies = + new ModerationPolicyClient( + endpoints, plaintextGrpcProperties(), factory, jwtUtil, runtimeIdentityProvider()); + GameSessionClient presence = + new GameSessionClient( + endpoints, plaintextGrpcProperties(), factory, BlockingGrpcStubCustomizer.noop()); + for (String accountId : + List.of( + "42", + "", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT), + " " + ACCOUNT_ID)) { + assertThatThrownBy(() -> reports.reportChatViolation(7L, accountId, "Filtered profanity")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> policies.evaluateChatSend(7L, accountId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> presence.queryAccountPresence(7L, accountId, List.of(FRIEND_ID))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> presence.queryAccountPresence(7L, ACCOUNT_ID, List.of(accountId))) + .isInstanceOf(IllegalArgumentException.class); + } + org.mockito.Mockito.verifyNoInteractions(factory); + } + @Test void moderationPolicyClientUsesUnknownServiceFallbackWhenRuntimeIdentityUnavailable() { CapturingChannel channel = new CapturingChannel(); @@ -192,6 +276,7 @@ private void assertInternalServiceToken(CapturingChannel channel, String expecte private static final class CapturingChannel extends ManagedChannel { private String lastAuthorization; + private Object lastRequest; private final byte[] responseBytes; private CapturingChannel() { @@ -229,7 +314,9 @@ public void cancel(String message, Throwable cause) {} public void halfClose() {} @Override - public void sendMessage(ReqT message) {} + public void sendMessage(ReqT message) { + lastRequest = message; + } }; } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java index 7d0797c978..6f922f8df3 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/ChatControllerTest.java @@ -46,7 +46,7 @@ void sendMessageRejectsZeroTenantIdBeforeAccessCheckAndDispatch() throws Excepti ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of())); String body = """ - {"tenantId":0,"senderAccountId":2,"type":"SAY","content":"hello"} + {"tenantId":0,"senderAccountId":"c41744c9-285e-4ed0-9fb4-0f0acb7a0123","type":"SAY","content":"hello"} """; mockMvc diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java index c14e80bd3a..2899306d91 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java @@ -45,6 +45,8 @@ @WithFiremudHttpAuthTestProperties class FriendControllerTest { private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; + private static final String ACCOUNT_ID = ACCOUNT_UUID; + private static final String FRIEND_ID = "d52755da-396f-4fd1-80c5-1f1bcb8b1234"; @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -55,8 +57,8 @@ class FriendControllerTest { @Test void addFriendReturnsDto() throws Exception { - AddFriendRequest request = new AddFriendRequest(1L, 2L, 3L); - FriendLinkDto response = new FriendLinkDto(1L, 1L, 2L, 3L, "active", null); + AddFriendRequest request = new AddFriendRequest(1L, ACCOUNT_ID, FRIEND_ID); + FriendLinkDto response = new FriendLinkDto(1L, 1L, ACCOUNT_ID, FRIEND_ID, "active", null); when(friendService.addFriend(request)).thenReturn(response); String token = accountToken(); @@ -68,12 +70,12 @@ void addFriendReturnsDto() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(2L)); + .andExpect(jsonPath("$.data.accountId").value(ACCOUNT_ID)); } @Test void addFriendRejectsSelfLinkAsBadRequest() throws Exception { - AddFriendRequest request = new AddFriendRequest(1L, 2L, 2L); + AddFriendRequest request = new AddFriendRequest(1L, ACCOUNT_ID, ACCOUNT_ID); when(friendService.addFriend(request)) .thenThrow( new IllegalArgumentException("Cannot add or remove your own account as a friend")); @@ -94,7 +96,7 @@ void addFriendRejectsSelfLinkAsBadRequest() throws Exception { @Test void addFriendRejectsZeroTenantIdBeforeAccessCheck() throws Exception { - AddFriendRequest request = new AddFriendRequest(0L, 2L, 3L); + AddFriendRequest request = new AddFriendRequest(0L, ACCOUNT_ID, FRIEND_ID); String token = accountToken(); mockMvc @@ -116,9 +118,9 @@ void removeFriendReturnsSuccess() throws Exception { String token = accountToken(); mockMvc .perform( - delete("/friends/3") + delete("/friends/" + FRIEND_ID) .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); @@ -130,13 +132,13 @@ void removeFriendRejectsSelfLinkAsBadRequest() throws Exception { org.mockito.Mockito.doThrow( new IllegalArgumentException("Cannot add or remove your own account as a friend")) .when(friendService) - .removeFriend(1L, 2L, 2L); + .removeFriend(1L, ACCOUNT_ID, ACCOUNT_ID); mockMvc .perform( - delete("/friends/2") + delete("/friends/" + ACCOUNT_ID) .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status").value("ERROR")) @@ -153,30 +155,30 @@ void removeFriendRejectsMalformedFriendAccountIdBeforeAccessCheck() throws Excep .perform( delete("/friends/not-a-number") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("friendAccountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("Malformed claim: friendAccountId")); verifyNoInteractions(friendService, socialAccessGuard); } @Test void getFriendReturnsCanonicalRosterEntry() throws Exception { - when(friendService.getFriend(1L, 2L, 3L)) + when(friendService.getFriend(1L, ACCOUNT_ID, FRIEND_ID)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", java.time.Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + FRIEND_ID, true, 9L, "SHARED", @@ -194,32 +196,32 @@ void getFriendReturnsCanonicalRosterEntry() throws Exception { String token = accountToken(); mockMvc .perform( - get("/friends/3") + get("/friends/" + FRIEND_ID) .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data.friendLinkId").value(7L)) - .andExpect(jsonPath("$.data.friendAccountId").value(3L)) + .andExpect(jsonPath("$.data.friendAccountId").value(FRIEND_ID)) .andExpect(jsonPath("$.data.presence.characterName").value("Ben")); } @Test void getFriendByOrdinalReturnsCanonicalRosterEntry() throws Exception { - when(friendService.getFriendByOrdinal(1L, 2L, 1)) + when(friendService.getFriendByOrdinal(1L, ACCOUNT_ID, 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", java.time.Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + FRIEND_ID, true, 9L, "SHARED", @@ -239,12 +241,12 @@ void getFriendByOrdinalReturnsCanonicalRosterEntry() throws Exception { .perform( get("/friends/entry/1") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data.ordinal").value(1)) - .andExpect(jsonPath("$.data.friendAccountId").value(3L)); + .andExpect(jsonPath("$.data.friendAccountId").value(FRIEND_ID)); } @Test @@ -255,7 +257,7 @@ void getFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Excepti .perform( get("/friends/entry/not-a-number") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) @@ -267,7 +269,9 @@ void getFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Excepti @Test void listFriendPresenceReturnsPresenceList() throws Exception { when(friendService.listFriendPresence( - 1L, 2L, net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) + 1L, + ACCOUNT_ID, + net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new net.firedevops.firemud.socialgroups.dto.FriendPresenceViewDto( net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY, @@ -275,7 +279,7 @@ void listFriendPresenceReturnsPresenceList() throws Exception { 1, List.of( new FriendPresenceDto( - 3L, + FRIEND_ID, true, 9L, "demo", @@ -293,7 +297,7 @@ void listFriendPresenceReturnsPresenceList() throws Exception { .perform( get("/friends/presence") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .param("filter", "FRIENDS_ONLY") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -301,7 +305,7 @@ void listFriendPresenceReturnsPresenceList() throws Exception { .andExpect(jsonPath("$.data.filter").value("FRIENDS_ONLY")) .andExpect(jsonPath("$.data.totalCount").value(2)) .andExpect(jsonPath("$.data.matchCount").value(1)) - .andExpect(jsonPath("$.data.presences[0].friendAccountId").value(3L)) + .andExpect(jsonPath("$.data.presences[0].friendAccountId").value(FRIEND_ID)) .andExpect(jsonPath("$.data.presences[0].online").value(true)) .andExpect(jsonPath("$.data.presences[0].worldSlug").value("demo")) .andExpect(jsonPath("$.data.presences[0].realmSlug").value("production")); @@ -309,7 +313,7 @@ void listFriendPresenceReturnsPresenceList() throws Exception { @Test void getFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { - when(friendService.getFriendPresencePolicy(1L, 2L)) + when(friendService.getFriendPresencePolicy(1L, ACCOUNT_ID)) .thenReturn(new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.PRIVATE)); String token = accountToken(); @@ -317,7 +321,7 @@ void getFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { .perform( get("/friends/visibility") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) @@ -336,7 +340,7 @@ void getFriendPresencePolicyRejectsMalformedAccountIdBeforeAccessCheck() throws .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("Malformed claim: accountId")); verifyNoInteractions(friendService, socialAccessGuard); } @@ -345,9 +349,9 @@ void getFriendPresencePolicyRejectsMalformedAccountIdBeforeAccessCheck() throws void updateFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { UpdateFriendPresencePolicyRequest request = new UpdateFriendPresencePolicyRequest( - 1L, 2L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); + 1L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); when(friendService.updateFriendPresencePolicy( - 1L, 2L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)) + 1L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)) .thenReturn( new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)); @@ -367,9 +371,9 @@ void updateFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { void updateFriendPresencePolicyRejectsReservedHiddenStaff() throws Exception { UpdateFriendPresencePolicyRequest request = new UpdateFriendPresencePolicyRequest( - 1L, 2L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF); + 1L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF); when(friendService.updateFriendPresencePolicy( - 1L, 2L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)) + 1L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)) .thenThrow( new IllegalArgumentException( "Friend presence visibility policy HIDDEN_STAFF is reserved")); @@ -391,7 +395,9 @@ void updateFriendPresencePolicyRejectsReservedHiddenStaff() throws Exception { @Test void listFriendsReturnsRosterList() throws Exception { when(friendService.listFriends( - 1L, 2L, net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) + 1L, + ACCOUNT_ID, + net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new net.firedevops.firemud.socialgroups.dto.FriendRosterViewDto( net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY, @@ -402,12 +408,12 @@ void listFriendsReturnsRosterList() throws Exception { 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", java.time.Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + FRIEND_ID, true, 9L, "SHARED", @@ -427,7 +433,7 @@ void listFriendsReturnsRosterList() throws Exception { .perform( get("/friends") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .param("filter", "FRIENDS_ONLY") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -435,7 +441,7 @@ void listFriendsReturnsRosterList() throws Exception { .andExpect(jsonPath("$.data.filter").value("FRIENDS_ONLY")) .andExpect(jsonPath("$.data.totalCount").value(1)) .andExpect(jsonPath("$.data.friends[0].friendLinkId").value(7L)) - .andExpect(jsonPath("$.data.friends[0].friendAccountId").value(3L)) + .andExpect(jsonPath("$.data.friends[0].friendAccountId").value(FRIEND_ID)) .andExpect(jsonPath("$.data.friends[0].status").value("active")) .andExpect(jsonPath("$.data.friends[0].presence.online").value(true)) .andExpect(jsonPath("$.data.friends[0].presence.worldSlug").value("demo")); @@ -449,7 +455,7 @@ void listFriendsRejectsZeroTenantIdBeforeAccessCheck() throws Exception { .perform( get("/friends") .param("tenantId", "0") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) @@ -460,7 +466,7 @@ void listFriendsRejectsZeroTenantIdBeforeAccessCheck() throws Exception { @Test void getFriendRosterSummaryReturnsCanonicalCounts() throws Exception { - when(friendService.getFriendRosterSummary(1L, 2L)) + when(friendService.getFriendRosterSummary(1L, ACCOUNT_ID)) .thenReturn(new FriendRosterSummaryDto(4, 1, 3, 2, 1, 2, 1, 0, 0, 2, 1, 1)); String token = accountToken(); @@ -468,7 +474,7 @@ void getFriendRosterSummaryReturnsCanonicalCounts() throws Exception { .perform( get("/friends/summary") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) @@ -488,31 +494,31 @@ void getFriendRosterSummaryReturnsCanonicalCounts() throws Exception { @Test void removeFriendByOrdinalReturnsRemovedEntry() throws Exception { - when(friendService.removeFriendByOrdinal(1L, 2L, 1)) + when(friendService.removeFriendByOrdinal(1L, ACCOUNT_ID, 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", java.time.Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, false, null, null, null, null, null, null, null, null, null, null, null, - null, null)))); + FRIEND_ID, false, null, null, null, null, null, null, null, null, null, + null, null, null, null)))); String token = accountToken(); mockMvc .perform( delete("/friends/entry/1") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.friendAccountId").value(3L)); + .andExpect(jsonPath("$.data.friendAccountId").value(FRIEND_ID)); } @Test @@ -523,7 +529,7 @@ void removeFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Exce .perform( delete("/friends/entry/not-a-number") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", ACCOUNT_ID) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java index 323090b2b6..43ee629360 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/GuildControllerTest.java @@ -55,9 +55,9 @@ void clear() { @Test void createGuildAllowsScopedTenantAdmin() throws Exception { - CreateGuildRequest request = new CreateGuildRequest(1L, 2L, "guild"); + CreateGuildRequest request = new CreateGuildRequest(1L, ACCOUNT_UUID, "guild"); when(guildService.createGuild(request)) - .thenReturn(new GuildDto(1L, 1L, "guild", 2L, Instant.now())); + .thenReturn(new GuildDto(1L, 1L, "guild", ACCOUNT_UUID, Instant.now())); String token = jwtUtil.generateToken( ACCOUNT_UUID, @@ -76,7 +76,7 @@ void createGuildAllowsScopedTenantAdmin() throws Exception { @Test void createGuildRejectsCrossTenantScopedAdmin() throws Exception { - CreateGuildRequest request = new CreateGuildRequest(1L, 2L, "guild"); + CreateGuildRequest request = new CreateGuildRequest(1L, ACCOUNT_UUID, "guild"); String token = jwtUtil.generateToken( ACCOUNT_UUID, @@ -93,7 +93,7 @@ void createGuildRejectsCrossTenantScopedAdmin() throws Exception { @Test void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { - CreateGuildRequest request = new CreateGuildRequest(0L, 2L, "guild"); + CreateGuildRequest request = new CreateGuildRequest(0L, ACCOUNT_UUID, "guild"); String token = jwtUtil.generateToken( ACCOUNT_UUID, @@ -115,7 +115,7 @@ void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void addMemberRejectsZeroGuildIdBeforeDispatch() throws Exception { - AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 0L, 2L, "member"); + AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 0L, ACCOUNT_UUID, "member"); String token = jwtUtil.generateToken( ACCOUNT_UUID, diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java index c481e99446..d0b67cf06e 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/MailControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.controller; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -33,6 +34,7 @@ @WithFiremudHttpAuthTestProperties class MailControllerTest { private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; + private static final String RECIPIENT_UUID = "d52755da-396f-4fd1-80c5-1f1bcb8b1234"; @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -41,8 +43,9 @@ class MailControllerTest { @MockitoBean private MailService mailService; @Test - void sendMailFailsClosedForCanonicalSubjectWithLegacyNumericSenderSelector() throws Exception { - SendMailRequest request = new SendMailRequest(1L, 2L, 3L, "hello", "test body"); + void sendMailAllowsCanonicalAuthenticatedSenderAndRecipient() throws Exception { + SendMailRequest request = + new SendMailRequest(1L, ACCOUNT_UUID, RECIPIENT_UUID, "hello", "test body"); String token = accountToken(); mockMvc .perform( @@ -50,18 +53,13 @@ void sendMailFailsClosedForCanonicalSubjectWithLegacyNumericSenderSelector() thr .contentType(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .content(objectMapper.writeValueAsString(request))) - .andExpect(status().isServiceUnavailable()) - .andExpect(jsonPath("$.status").value("ERROR")) - .andExpect( - jsonPath("$.error.message") - .value( - "Mail sender authorization is unavailable until Social account UUID migration is complete")); + .andExpect(status().isOk()); - verifyNoInteractions(mailService); + verify(mailService).sendMail(request); } @Test - void sendMailRejectsZeroSenderAccountIdBeforeAccessCheckAndDispatch() throws Exception { + void sendMailRejectsLegacyNumericSenderSelectorBeforeDispatch() throws Exception { String token = accountToken(); mockMvc @@ -70,19 +68,18 @@ void sendMailRejectsZeroSenderAccountIdBeforeAccessCheckAndDispatch() throws Exc .contentType(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .content( - """ - {"tenantId":1,"senderAccountId":0,"recipientAccountId":3,"subject":"hello","content":"test body"} - """)) + "{\"tenantId\":1,\"senderAccountId\":\"2\",\"recipientAccountId\":\"%s\",\"subject\":\"hello\",\"content\":\"test body\"}" + .formatted(RECIPIENT_UUID))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status").value("ERROR")) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("senderAccountId must be positive")); + .andExpect(jsonPath("$.error.message").value("Malformed claim: senderAccountId")); verifyNoInteractions(mailService); } @Test - void tenantRoleCannotEnableMailWhileSenderIdentityIsNumeric() throws Exception { + void tenantRoleCannotSendMailAsAnotherAccount() throws Exception { String token = jwtUtil.generateToken( ACCOUNT_UUID, @@ -97,14 +94,11 @@ void tenantRoleCannotEnableMailWhileSenderIdentityIsNumeric() throws Exception { .contentType(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .content( - """ - {"tenantId":1,"senderAccountId":3,"recipientAccountId":4,"subject":"hello","content":"test body"} - """)) - .andExpect(status().isServiceUnavailable()) + "{\"tenantId\":1,\"senderAccountId\":\"%s\",\"recipientAccountId\":\"%s\",\"subject\":\"hello\",\"content\":\"test body\"}" + .formatted(RECIPIENT_UUID, ACCOUNT_UUID))) + .andExpect(status().isForbidden()) .andExpect( - jsonPath("$.error.message") - .value( - "Mail sender authorization is unavailable until Social account UUID migration is complete")); + jsonPath("$.error.message").value("Mail sender must match the authenticated account")); verifyNoInteractions(mailService); } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java index 1d23fcb6d0..5a138f7493 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/VoiceChatControllerTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.socialgroups.controller; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -47,7 +48,8 @@ class VoiceChatControllerTest { void createTokenReturnsToken() throws Exception { when(service.createToken(any())).thenReturn(new VoiceTokenDto("abc", Instant.now())); String token = accountToken(); - String body = "{\"tenantId\":1,\"accountId\":2,\"channelId\":\"guild-1\"}"; + String body = + "{\"tenantId\":1,\"accountId\":\"" + ACCOUNT_UUID + "\",\"channelId\":\"guild-1\"}"; mockMvc .perform( @@ -60,9 +62,12 @@ void createTokenReturnsToken() throws Exception { } @Test - void createTokenRejectsZeroAccountIdBeforeAccessCheckAndDispatch() throws Exception { + void createTokenRejectsLegacyNumericAccountIdAtAccessCheckBeforeDispatch() throws Exception { String token = accountToken(); - String body = "{\"tenantId\":1,\"accountId\":0,\"channelId\":\"guild-1\"}"; + String body = "{\"tenantId\":1,\"accountId\":\"0\",\"channelId\":\"guild-1\"}"; + org.mockito.Mockito.doThrow(new IllegalArgumentException("Malformed claim: accountId")) + .when(socialAccessGuard) + .requireAccountAccess(1L, "0"); mockMvc .perform( @@ -73,9 +78,10 @@ void createTokenRejectsZeroAccountIdBeforeAccessCheckAndDispatch() throws Except .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status").value("ERROR")) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.message").value("Malformed claim: accountId")); - verifyNoInteractions(service, socialAccessGuard); + verify(socialAccessGuard).requireAccountAccess(1L, "0"); + verifyNoInteractions(service); } private String accountToken() { diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java index 6c67a30275..17cd9a4199 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/security/SocialAccessGuardTest.java @@ -12,6 +12,7 @@ class SocialAccessGuardTest { private static final String ACCOUNT_UUID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; + private static final String OTHER_ACCOUNT_UUID = "d52755da-396f-4fd1-80c5-1f1bcb8b1234"; private final SocialAccessGuard guard = new SocialAccessGuard(); @@ -24,20 +25,29 @@ void tearDown() { void hasAccountAccessRejectsMalformedCurrentAccountClaim() { SessionContext.setContext("not-a-number", List.of(), Map.of()); - assertFalse(guard.hasAccountAccess(1L, 42L)); + assertFalse(guard.hasAccountAccess(1L, ACCOUNT_UUID)); } @Test - void canonicalCurrentAccountCannotAuthorizeLegacyNumericSelector() { + void canonicalCurrentAccountAuthorizesExactUuidSelector() { SessionContext.setContext(ACCOUNT_UUID, List.of(), Map.of()); - assertFalse(guard.hasAccountAccess(1L, 42L)); + assertTrue(guard.hasAccountAccess(1L, ACCOUNT_UUID)); + assertFalse(guard.hasAccountAccess(1L, OTHER_ACCOUNT_UUID)); } @Test - void hasAccountAccessPreservesTenantAdminAuthorizationForLegacySelector() { + void hasAccountAccessPreservesTenantAdminAuthorizationForUuidSelector() { SessionContext.setContext(ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); - assertTrue(guard.hasAccountAccess(1L, 42L)); + assertTrue(guard.hasAccountAccess(1L, OTHER_ACCOUNT_UUID)); + } + + @Test + void hasAccountAccessRejectsMalformedAccountSelector() { + SessionContext.setContext(ACCOUNT_UUID, List.of(), Map.of("1", List.of("tenantAdmin"))); + + assertFalse(guard.hasAccountAccess(1L, "00000000-0000-0000-0000-000000000000")); + assertFalse(guard.hasAccountAccess(1L, "42")); } } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java index dd87d2f35b..2b4ad5ee03 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java @@ -11,6 +11,7 @@ import java.time.Instant; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.socialgroups.client.LoggingAdminClient; import net.firedevops.firemud.socialgroups.client.ModerationPolicyClient; import net.firedevops.firemud.socialgroups.config.ChatProperties; @@ -30,6 +31,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; class ChatServiceImplTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String RECIPIENT_ID = "00000000-0000-4000-8000-000000000003"; private ChatMessageRepository repository; private ProfanityFilter profanityFilter; private LoggingAdminClient loggingAdminClient; @@ -50,7 +53,7 @@ void setup() { listOps = mockListOperations(); when(redisTemplate.opsForList()).thenReturn(listOps); when(profanityFilter.filter(any())).thenAnswer(i -> i.getArgument(0)); - when(moderationPolicyClient.evaluateChatSend(anyLong(), anyLong())) + when(moderationPolicyClient.evaluateChatSend(anyLong(), anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -80,15 +83,17 @@ void setup() { @Test void sendMessageCachesMessageAndIncrementsMetrics() { SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.SAY, null, 1L, null, null, "hello", null); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.SAY, null, RECIPIENT_ID, null, null, "hello", null); ChatMessageDto dto = service.sendMessage(req); assertEquals(1L, dto.id()); - verify(listOps).leftPush("chat:say:1:2", "hello"); + verify(listOps).leftPush("chat:say:1:" + ACCOUNT_ID, "hello"); verify(redisTemplate) - .expire("chat:say:1:2", Duration.ofSeconds(props.getSays().historyTtlSeconds())); - verify(listOps).trim("chat:say:1:2", 0, props.getSays().maxMessages() - 1); + .expire( + "chat:say:1:" + ACCOUNT_ID, Duration.ofSeconds(props.getSays().historyTtlSeconds())); + verify(listOps).trim("chat:say:1:" + ACCOUNT_ID, 0, props.getSays().maxMessages() - 1); assertEquals(1.0, meterRegistry.get("chat_messages_published_total").counter().count(), 0.001); assertEquals(0.0, meterRegistry.get("chat_redis_errors_total").counter().count(), 0.001); } @@ -98,7 +103,8 @@ void sendMessageDefersRedisWritesUntilCommit() { TransactionSynchronizationManager.initSynchronization(); try { SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.SAY, null, 1L, null, null, "hello", null); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.SAY, null, RECIPIENT_ID, null, null, "hello", null); ChatMessageDto dto = service.sendMessage(req); @@ -112,10 +118,11 @@ void sendMessageDefersRedisWritesUntilCommit() { synchronization.afterCommit(); } - verify(listOps).leftPush("chat:say:1:2", "hello"); + verify(listOps).leftPush("chat:say:1:" + ACCOUNT_ID, "hello"); verify(redisTemplate) - .expire("chat:say:1:2", Duration.ofSeconds(props.getSays().historyTtlSeconds())); - verify(listOps).trim("chat:say:1:2", 0, props.getSays().maxMessages() - 1); + .expire( + "chat:say:1:" + ACCOUNT_ID, Duration.ofSeconds(props.getSays().historyTtlSeconds())); + verify(listOps).trim("chat:say:1:" + ACCOUNT_ID, 0, props.getSays().maxMessages() - 1); } finally { TransactionSynchronizationManager.clearSynchronization(); } @@ -126,7 +133,8 @@ void redisFailureIncrementsErrorMetric() { doThrow(new RuntimeException("fail")).when(listOps).leftPush(any(), any()); SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.SAY, null, 1L, null, null, "hi", null); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.SAY, null, RECIPIENT_ID, null, null, "hi", null); service.sendMessage(req); assertEquals(1.0, meterRegistry.get("chat_redis_errors_total").counter().count(), 0.001); @@ -136,23 +144,25 @@ void redisFailureIncrementsErrorMetric() { void profanityReportsModerationAfterCommitPath() { when(profanityFilter.filter("badword")).thenReturn("cleaned"); SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.SAY, null, 1L, null, null, "badword", null); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.SAY, null, RECIPIENT_ID, null, null, "badword", null); service.sendMessage(req); - verify(loggingAdminClient).reportChatViolation(1L, 2L, "Filtered profanity"); + verify(loggingAdminClient).reportChatViolation(1L, ACCOUNT_ID, "Filtered profanity"); } @Test void moderationPolicyDeniesChatBeforePersistence() { - when(moderationPolicyClient.evaluateChatSend(1L, 2L)) + when(moderationPolicyClient.evaluateChatSend(1L, ACCOUNT_ID)) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(false) .setAction("chat_mute") .build()); SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.SAY, null, 1L, null, null, "hello", null); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.SAY, null, RECIPIENT_ID, null, null, "hello", null); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> service.sendMessage(req)); @@ -164,13 +174,16 @@ void moderationPolicyDeniesChatBeforePersistence() { @Test void whisperCachesSeparatelyFromTell() { SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.WHISPER, null, 7L, null, null, "quiet", null); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.WHISPER, null, RECIPIENT_ID, null, null, "quiet", null); service.sendMessage(req); - verify(listOps).leftPush("chat:whisper:1:7", "quiet"); + verify(listOps).leftPush("chat:whisper:1:" + RECIPIENT_ID, "quiet"); verify(redisTemplate) - .expire("chat:whisper:1:7", Duration.ofSeconds(props.getWhispers().historyTtlSeconds())); + .expire( + "chat:whisper:1:" + RECIPIENT_ID, + Duration.ofSeconds(props.getWhispers().historyTtlSeconds())); } @Test @@ -178,7 +191,7 @@ void sendMessageReturnsExistingMessageForDuplicateEffectId() { ChatMessage existing = new ChatMessage(); existing.setId(22L); existing.setTenantId(1L); - existing.setSenderAccountId(2L); + existing.setSenderAccountId(UUID.fromString(ACCOUNT_ID)); existing.setType(ChatType.SAY); existing.setContent("hello"); existing.setTimestamp(Instant.parse("2026-04-21T00:00:00Z")); @@ -188,7 +201,15 @@ void sendMessageReturnsExistingMessageForDuplicateEffectId() { ChatMessageDto dto = service.sendMessage( new SendMessageRequestDto( - 1L, 2L, ChatType.SAY, null, 1L, null, null, "hello", "fx-comm-1")); + 1L, + ACCOUNT_ID, + ChatType.SAY, + null, + RECIPIENT_ID, + null, + null, + "hello", + "fx-comm-1")); assertEquals(22L, dto.id()); assertEquals("fx-comm-1", dto.effectId()); diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java index 89bd596d65..50f6b55162 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java @@ -15,6 +15,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamesession.v1.AccountPresenceActivityState; import net.firedevops.firemud.gamesession.v1.AccountPresenceEntry; import net.firedevops.firemud.gamesession.v1.QueryAccountPresenceResponse; @@ -33,6 +34,13 @@ import org.mockito.Mockito; class FriendServiceImplTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String FRIEND_ID = "00000000-0000-4000-8000-000000000003"; + private static final String OTHER_ID = "00000000-0000-4000-8000-000000000004"; + private static final UUID ACCOUNT_UUID = UUID.fromString(ACCOUNT_ID); + private static final UUID FRIEND_UUID = UUID.fromString(FRIEND_ID); + private static final UUID OTHER_UUID = UUID.fromString(OTHER_ID); + private AccountFriendLinkRepository accountRepository; private GameSessionClient gameSessionClient; private AccountClient accountClient; @@ -46,14 +54,14 @@ void setUp() { when(accountClient.getPresenceVisibilityPolicies(anyLong(), anyCollection())) .thenAnswer( invocation -> { - Collection accountIds = invocation.getArgument(1); + Collection accountIds = invocation.getArgument(1); return friendsOnlyPolicies(accountIds); }); service = new FriendServiceImpl(accountRepository, gameSessionClient, accountClient); } - private static Map friendsOnlyPolicies( - Collection accountIds) { + private static Map friendsOnlyPolicies( + Collection accountIds) { return accountIds.stream() .collect( java.util.stream.Collectors.toUnmodifiableMap( @@ -63,9 +71,9 @@ private static Map friendsOnlyPolicie @Test void addFriendCreatesAccountScopedLink() { - AddFriendRequest request = new AddFriendRequest(11L, 2L, 3L); + AddFriendRequest request = new AddFriendRequest(11L, ACCOUNT_ID, FRIEND_ID); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, ACCOUNT_UUID, FRIEND_UUID, "active")) .thenReturn(java.util.Optional.empty()); when(accountRepository.save(any(AccountFriendLink.class))) .thenAnswer( @@ -78,23 +86,23 @@ void addFriendCreatesAccountScopedLink() { FriendLinkDto result = service.addFriend(request); assertEquals(11L, result.tenantId()); - assertEquals(2L, result.accountId()); - assertEquals(3L, result.friendAccountId()); + assertEquals(ACCOUNT_ID, result.accountId()); + assertEquals(FRIEND_ID, result.friendAccountId()); assertNotNull(result.createdAt()); } @Test void addFriendReusesExistingActiveAccountScopedLink() { - AddFriendRequest request = new AddFriendRequest(11L, 2L, 3L); + AddFriendRequest request = new AddFriendRequest(11L, ACCOUNT_ID, FRIEND_ID); AccountFriendLink existing = new AccountFriendLink(); existing.setId(7L); existing.setTenantId(11L); - existing.setAccountId(2L); - existing.setFriendAccountId(3L); + existing.setAccountId(ACCOUNT_UUID); + existing.setFriendAccountId(FRIEND_UUID); existing.setStatus("active"); existing.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, ACCOUNT_UUID, FRIEND_UUID, "active")) .thenReturn(java.util.Optional.of(existing)); FriendLinkDto result = service.addFriend(request); @@ -106,7 +114,7 @@ void addFriendReusesExistingActiveAccountScopedLink() { @Test void addFriendRejectsSelfLink() { - AddFriendRequest request = new AddFriendRequest(11L, 2L, 2L); + AddFriendRequest request = new AddFriendRequest(11L, ACCOUNT_ID, ACCOUNT_ID); IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> service.addFriend(request)); @@ -114,7 +122,10 @@ void addFriendRejectsSelfLink() { assertEquals("Cannot add or remove your own account as a friend", error.getMessage()); Mockito.verify(accountRepository, Mockito.never()) .findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString()); + Mockito.anyLong(), + Mockito.any(UUID.class), + Mockito.any(UUID.class), + Mockito.anyString()); } @Test @@ -122,14 +133,14 @@ void removeFriendDeletesExistingActiveAccountScopedLink() { AccountFriendLink existing = new AccountFriendLink(); existing.setId(7L); existing.setTenantId(11L); - existing.setAccountId(2L); - existing.setFriendAccountId(3L); + existing.setAccountId(ACCOUNT_UUID); + existing.setFriendAccountId(FRIEND_UUID); existing.setStatus("active"); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, ACCOUNT_UUID, FRIEND_UUID, "active")) .thenReturn(java.util.Optional.of(existing)); - service.removeFriend(11L, 2L, 3L); + service.removeFriend(11L, ACCOUNT_ID, FRIEND_ID); Mockito.verify(accountRepository).delete(existing); } @@ -137,10 +148,10 @@ void removeFriendDeletesExistingActiveAccountScopedLink() { @Test void removeFriendIsIdempotentWhenActiveLinkDoesNotExist() { when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, ACCOUNT_UUID, FRIEND_UUID, "active")) .thenReturn(java.util.Optional.empty()); - service.removeFriend(11L, 2L, 3L); + service.removeFriend(11L, ACCOUNT_ID, FRIEND_ID); Mockito.verify(accountRepository, Mockito.never()).delete(any(AccountFriendLink.class)); } @@ -149,29 +160,30 @@ void removeFriendIsIdempotentWhenActiveLinkDoesNotExist() { void listFriendsUsesOnlyMutuallyAcceptedLinks() { AccountFriendLink oneSided = new AccountFriendLink(); oneSided.setTenantId(11L); - oneSided.setAccountId(2L); - oneSided.setFriendAccountId(3L); + oneSided.setAccountId(ACCOUNT_UUID); + oneSided.setFriendAccountId(FRIEND_UUID); oneSided.setStatus("active"); AccountFriendLink mutual = new AccountFriendLink(); mutual.setTenantId(11L); - mutual.setAccountId(2L); - mutual.setFriendAccountId(4L); + mutual.setAccountId(ACCOUNT_UUID); + mutual.setFriendAccountId(OTHER_UUID); mutual.setStatus("active"); - when(accountRepository.findByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findByTenantIdAndAccountIdAndStatus(11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(oneSided)); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(mutual)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(4L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(OTHER_ID))) .thenReturn(QueryAccountPresenceResponse.newBuilder().build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.ALL); assertEquals(1, result.totalCount()); - assertEquals(4L, result.friends().getFirst().friendAccountId()); + assertEquals(OTHER_ID, result.friends().getFirst().friendAccountId()); Mockito.verify(accountRepository) - .findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active"); + .findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, ACCOUNT_UUID, "active"); Mockito.verify(accountRepository, Mockito.never()) - .findByTenantIdAndAccountIdAndStatus(11L, 2L, "active"); + .findByTenantIdAndAccountIdAndStatus(11L, ACCOUNT_UUID, "active"); } @Test @@ -179,33 +191,37 @@ void getFriendRosterSummaryReturnsCanonicalCounts() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(ACCOUNT_UUID); + sora.setFriendAccountId(FRIEND_UUID); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); AccountFriendLink nyx = new AccountFriendLink(); nyx.setId(8L); nyx.setTenantId(11L); - nyx.setAccountId(2L); - nyx.setFriendAccountId(4L); + nyx.setAccountId(ACCOUNT_UUID); + nyx.setFriendAccountId(OTHER_UUID); nyx.setStatus("active"); nyx.setCreatedAt(Instant.parse("2026-04-10T01:02:04Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sora, nyx)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID, OTHER_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(FRIEND_ID) + .setOnline(true) + .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(OTHER_ID) .setOnline(false) .setLastSeenAtMs(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) .build()) .build()); - FriendRosterSummaryDto result = service.getFriendRosterSummary(11L, 2L); + FriendRosterSummaryDto result = service.getFriendRosterSummary(11L, ACCOUNT_ID); assertEquals(2, result.totalCount()); assertEquals(1, result.onlineCount()); @@ -226,28 +242,29 @@ void getFriendByOrdinalReturnsCanonicalRosterEntry() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(ACCOUNT_UUID); + sora.setFriendAccountId(FRIEND_UUID); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setCharacterName("Ben") .build()) .build()); - var result = service.getFriendByOrdinal(11L, 2L, 1); + var result = service.getFriendByOrdinal(11L, ACCOUNT_ID, 1); assertTrue(result.isPresent()); assertEquals(1, result.orElseThrow().ordinal()); - assertEquals(3L, result.orElseThrow().friendAccountId()); + assertEquals(FRIEND_ID, result.orElseThrow().friendAccountId()); assertEquals("Ben", result.orElseThrow().presence().characterName()); } @@ -256,22 +273,23 @@ void removeFriendByOrdinalRemovesCanonicalRosterEntry() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(ACCOUNT_UUID); + sora.setFriendAccountId(FRIEND_UUID); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sora)); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, ACCOUNT_UUID, FRIEND_UUID, "active")) .thenReturn(java.util.Optional.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn(QueryAccountPresenceResponse.newBuilder().build()); - var result = service.removeFriendByOrdinal(11L, 2L, 1); + var result = service.removeFriendByOrdinal(11L, ACCOUNT_ID, 1); assertTrue(result.isPresent()); - assertEquals(3L, result.orElseThrow().friendAccountId()); + assertEquals(FRIEND_ID, result.orElseThrow().friendAccountId()); Mockito.verify(accountRepository).delete(sora); } @@ -280,15 +298,17 @@ void listFriendsFallsBackToOfflineDefaultsWhenPresenceClientReturnsNull() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(ACCOUNT_UUID); + sora.setFriendAccountId(FRIEND_UUID); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))).thenReturn(null); + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) + .thenReturn(null); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.ALL); assertEquals(1, result.totalCount()); assertEquals(false, result.friends().getFirst().presence().online()); @@ -301,13 +321,14 @@ void listFriendsRejectsMalformedPresenceAccountId() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(ACCOUNT_UUID); + sora.setFriendAccountId(FRIEND_UUID); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( @@ -317,10 +338,10 @@ void listFriendsRejectsMalformedPresenceAccountId() { IllegalStateException error = assertThrows( IllegalStateException.class, - () -> service.listFriends(11L, 2L, FriendRosterFilter.ALL)); + () -> service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.ALL)); assertEquals( - "Malformed account presence accountId: accountId must be numeric", error.getMessage()); + "Malformed account presence accountId: Malformed claim: accountId", error.getMessage()); } @Test @@ -328,13 +349,14 @@ void listFriendPresenceRejectsMalformedPresenceAccountId() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(ACCOUNT_UUID); + sora.setFriendAccountId(FRIEND_UUID); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( @@ -342,20 +364,21 @@ void listFriendPresenceRejectsMalformedPresenceAccountId() { .build()); IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.listFriendPresence(11L, 2L)); + assertThrows( + IllegalStateException.class, () -> service.listFriendPresence(11L, ACCOUNT_ID)); assertEquals( - "Malformed account presence accountId: accountId must be numeric", error.getMessage()); + "Malformed account presence accountId: Malformed claim: accountId", error.getMessage()); } @Test void listFriendPresenceDropsNonPositiveVisibleIds() { - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setGameInstanceId("0") .setCharacterId("-7") @@ -364,37 +387,38 @@ void listFriendPresenceDropsNonPositiveVisibleIds() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(ACCOUNT_UUID); + sora.setFriendAccountId(FRIEND_UUID); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sora)); - var result = service.listFriendPresence(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriendPresence(11L, ACCOUNT_ID, FriendRosterFilter.ALL); assertEquals(1, result.presences().size()); - assertEquals(3L, result.presences().getFirst().friendAccountId()); + assertEquals(FRIEND_ID, result.presences().getFirst().friendAccountId()); assertEquals(null, result.presences().getFirst().gameInstanceId()); assertEquals(null, result.presences().getFirst().characterId()); } @Test void getFriendPresencePolicyReturnsCanonicalAccountPolicy() { - when(accountClient.getPresenceVisibilityPolicy(11L, 2L)) + when(accountClient.getPresenceVisibilityPolicy(11L, ACCOUNT_ID)) .thenReturn(Optional.of(FriendPresenceVisibilityPolicyValue.PRIVATE)); - var result = service.getFriendPresencePolicy(11L, 2L); + var result = service.getFriendPresencePolicy(11L, ACCOUNT_ID); assertEquals(FriendPresenceVisibilityPolicyValue.PRIVATE, result.currentPolicy()); } @Test void getFriendPresencePolicyRedactsLegacyHiddenStaff() { - when(accountClient.getPresenceVisibilityPolicy(11L, 2L)) + when(accountClient.getPresenceVisibilityPolicy(11L, ACCOUNT_ID)) .thenReturn(Optional.of(FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); - var result = service.getFriendPresencePolicy(11L, 2L); + var result = service.getFriendPresencePolicy(11L, ACCOUNT_ID); assertEquals(FriendPresenceVisibilityPolicyValue.PRIVATE, result.currentPolicy()); } @@ -406,7 +430,7 @@ void updateFriendPresencePolicyRejectsHiddenStaff() { IllegalArgumentException.class, () -> service.updateFriendPresencePolicy( - 11L, 2L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); assertEquals("Friend presence visibility policy HIDDEN_STAFF is reserved", error.getMessage()); } @@ -414,11 +438,12 @@ void updateFriendPresencePolicyRejectsHiddenStaff() { @Test void updateFriendPresencePolicyWritesCanonicalAccountPolicy() { when(accountClient.updatePresenceVisibilityPolicy( - 11L, 2L, FriendPresenceVisibilityPolicyValue.PUBLIC)) + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PUBLIC)) .thenReturn(true); var result = - service.updateFriendPresencePolicy(11L, 2L, FriendPresenceVisibilityPolicyValue.PUBLIC); + service.updateFriendPresencePolicy( + 11L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PUBLIC); assertEquals(FriendPresenceVisibilityPolicyValue.PUBLIC, result.currentPolicy()); } @@ -426,12 +451,17 @@ void updateFriendPresencePolicyWritesCanonicalAccountPolicy() { @Test void removeFriendRejectsSelfLink() { IllegalArgumentException error = - assertThrows(IllegalArgumentException.class, () -> service.removeFriend(11L, 2L, 2L)); + assertThrows( + IllegalArgumentException.class, + () -> service.removeFriend(11L, ACCOUNT_ID, ACCOUNT_ID)); assertEquals("Cannot add or remove your own account as a friend", error.getMessage()); Mockito.verify(accountRepository, Mockito.never()) .findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString()); + Mockito.anyLong(), + Mockito.any(UUID.class), + Mockito.any(UUID.class), + Mockito.anyString()); } @Test @@ -439,18 +469,19 @@ void getFriendReturnsCanonicalRosterEntryWithEmbeddedPresence() { AccountFriendLink link = new AccountFriendLink(); link.setId(7L); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(ACCOUNT_UUID); + link.setFriendAccountId(FRIEND_UUID); link.setStatus("active"); link.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(link)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -466,11 +497,11 @@ void getFriendReturnsCanonicalRosterEntryWithEmbeddedPresence() { .build()) .build()); - var result = service.getFriend(11L, 2L, 3L); + var result = service.getFriend(11L, ACCOUNT_ID, FRIEND_ID); assertTrue(result.isPresent()); assertEquals(7L, result.orElseThrow().friendLinkId()); - assertEquals(3L, result.orElseThrow().friendAccountId()); + assertEquals(FRIEND_ID, result.orElseThrow().friendAccountId()); assertEquals(true, result.orElseThrow().presence().online()); assertEquals("Ben", result.orElseThrow().presence().characterName()); } @@ -479,19 +510,20 @@ void getFriendReturnsCanonicalRosterEntryWithEmbeddedPresence() { void listFriendPresenceReturnsOrderedSnapshotsFromGameSession() { AccountFriendLink link = new AccountFriendLink(); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(ACCOUNT_UUID); + link.setFriendAccountId(FRIEND_UUID); link.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(link)); - when(accountClient.getPresenceVisibilityPolicies(11L, List.of(3L))) - .thenReturn(Map.of(3L, FriendPresenceVisibilityPolicyValue.PUBLIC)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(accountClient.getPresenceVisibilityPolicies(11L, List.of(FRIEND_ID))) + .thenReturn(Map.of(FRIEND_ID, FriendPresenceVisibilityPolicyValue.PUBLIC)); + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setGameInstanceId("9") .setWorldSlug("demo") @@ -510,13 +542,13 @@ void listFriendPresenceReturnsOrderedSnapshotsFromGameSession() { .build()) .build()); - var result = service.listFriendPresence(11L, 2L); + var result = service.listFriendPresence(11L, ACCOUNT_ID); assertEquals(FriendRosterFilter.ALL, result.filter()); assertEquals(1, result.totalCount()); assertEquals(1, result.matchCount()); assertEquals(1, result.presences().size()); - assertEquals(3L, result.presences().get(0).friendAccountId()); + assertEquals(FRIEND_ID, result.presences().get(0).friendAccountId()); assertEquals(true, result.presences().get(0).online()); assertEquals("demo", result.presences().get(0).worldSlug()); assertEquals("Demo World", result.presences().get(0).worldDisplayName()); @@ -533,18 +565,19 @@ void listFriendsReturnsRosterEntriesWithEmbeddedPresence() { AccountFriendLink link = new AccountFriendLink(); link.setId(7L); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(ACCOUNT_UUID); + link.setFriendAccountId(FRIEND_UUID); link.setStatus("active"); link.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(link)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -566,15 +599,15 @@ void listFriendsReturnsRosterEntriesWithEmbeddedPresence() { .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.ALL); assertEquals(FriendRosterFilter.ALL, result.filter()); assertEquals(1, result.totalCount()); assertEquals(1, result.matchCount()); assertEquals(7L, result.friends().get(0).friendLinkId()); assertEquals(11L, result.friends().get(0).tenantId()); - assertEquals(2L, result.friends().get(0).accountId()); - assertEquals(3L, result.friends().get(0).friendAccountId()); + assertEquals(ACCOUNT_ID, result.friends().get(0).accountId()); + assertEquals(FRIEND_ID, result.friends().get(0).friendAccountId()); assertEquals("active", result.friends().get(0).status()); assertEquals(Instant.parse("2026-04-10T01:02:03Z"), result.friends().get(0).createdAt()); assertEquals(true, result.friends().get(0).presence().online()); @@ -588,34 +621,41 @@ void listFriendsFiltersOnlineWithoutRenumberingCanonicalOrdinals() { AccountFriendLink onlineLink = new AccountFriendLink(); onlineLink.setId(7L); onlineLink.setTenantId(11L); - onlineLink.setAccountId(2L); - onlineLink.setFriendAccountId(3L); + onlineLink.setAccountId(ACCOUNT_UUID); + onlineLink.setFriendAccountId(FRIEND_UUID); onlineLink.setStatus("active"); AccountFriendLink offlineLink = new AccountFriendLink(); offlineLink.setId(8L); offlineLink.setTenantId(11L); - offlineLink.setAccountId(2L); - offlineLink.setFriendAccountId(4L); + offlineLink.setAccountId(ACCOUNT_UUID); + offlineLink.setFriendAccountId(OTHER_UUID); offlineLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(onlineLink, offlineLink)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID, OTHER_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(FRIEND_ID) + .setOnline(true) + .build()) .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("4").setOnline(false).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(OTHER_ID) + .setOnline(false) + .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ONLINE); + var result = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.ONLINE); assertEquals(FriendRosterFilter.ONLINE, result.filter()); assertEquals(2, result.totalCount()); assertEquals(1, result.matchCount()); assertEquals(1, result.friends().size()); assertEquals(1, result.friends().get(0).ordinal()); - assertEquals(3L, result.friends().get(0).friendAccountId()); + assertEquals(FRIEND_ID, result.friends().get(0).friendAccountId()); } @Test @@ -623,39 +663,43 @@ void listFriendsFiltersVisibilityPolicyWithoutRenumberingCanonicalOrdinals() { AccountFriendLink friendsOnlyLink = new AccountFriendLink(); friendsOnlyLink.setId(7L); friendsOnlyLink.setTenantId(11L); - friendsOnlyLink.setAccountId(2L); - friendsOnlyLink.setFriendAccountId(3L); + friendsOnlyLink.setAccountId(ACCOUNT_UUID); + friendsOnlyLink.setFriendAccountId(FRIEND_UUID); friendsOnlyLink.setStatus("active"); AccountFriendLink privateLink = new AccountFriendLink(); privateLink.setId(8L); privateLink.setTenantId(11L); - privateLink.setAccountId(2L); - privateLink.setFriendAccountId(4L); + privateLink.setAccountId(ACCOUNT_UUID); + privateLink.setFriendAccountId(OTHER_UUID); privateLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(friendsOnlyLink, privateLink)); - when(accountClient.getPresenceVisibilityPolicies(11L, List.of(3L, 4L))) + when(accountClient.getPresenceVisibilityPolicies(11L, List.of(FRIEND_ID, OTHER_ID))) .thenReturn( Map.of( - 3L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY, - 4L, FriendPresenceVisibilityPolicyValue.PRIVATE)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + FRIEND_ID, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY, + OTHER_ID, FriendPresenceVisibilityPolicyValue.PRIVATE)); + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(FRIEND_ID) + .setOnline(true) + .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.FRIENDS_ONLY); + var result = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.FRIENDS_ONLY); assertEquals(FriendRosterFilter.FRIENDS_ONLY, result.filter()); assertEquals(2, result.totalCount()); assertEquals(1, result.matchCount()); assertEquals(1, result.friends().size()); assertEquals(1, result.friends().get(0).ordinal()); - assertEquals(3L, result.friends().get(0).friendAccountId()); + assertEquals(FRIEND_ID, result.friends().get(0).friendAccountId()); assertEquals("FRIENDS_ONLY", result.friends().get(0).presence().visibilityPolicy()); - Mockito.verify(gameSessionClient).queryAccountPresence(11L, 2L, List.of(3L)); + Mockito.verify(gameSessionClient).queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID)); } @Test @@ -663,23 +707,24 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { AccountFriendLink sharedLink = new AccountFriendLink(); sharedLink.setId(7L); sharedLink.setTenantId(11L); - sharedLink.setAccountId(2L); - sharedLink.setFriendAccountId(3L); + sharedLink.setAccountId(ACCOUNT_UUID); + sharedLink.setFriendAccountId(FRIEND_UUID); sharedLink.setStatus("active"); AccountFriendLink isolatedLink = new AccountFriendLink(); isolatedLink.setId(8L); isolatedLink.setTenantId(11L); - isolatedLink.setAccountId(2L); - isolatedLink.setFriendAccountId(4L); + isolatedLink.setAccountId(ACCOUNT_UUID); + isolatedLink.setFriendAccountId(OTHER_UUID); isolatedLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(sharedLink, isolatedLink)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID, OTHER_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -687,7 +732,7 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(OTHER_ID) .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -695,14 +740,14 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.SHARED); + var result = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.SHARED); assertEquals(FriendRosterFilter.SHARED, result.filter()); assertEquals(2, result.totalCount()); assertEquals(1, result.matchCount()); assertEquals(1, result.friends().size()); assertEquals(1, result.friends().get(0).ordinal()); - assertEquals(3L, result.friends().get(0).friendAccountId()); + assertEquals(FRIEND_ID, result.friends().get(0).friendAccountId()); assertEquals("SHARED", result.friends().get(0).presence().playableStateScope()); } @@ -710,27 +755,28 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { AccountFriendLink privateLink = new AccountFriendLink(); privateLink.setTenantId(11L); - privateLink.setAccountId(2L); - privateLink.setFriendAccountId(3L); + privateLink.setAccountId(ACCOUNT_UUID); + privateLink.setFriendAccountId(FRIEND_UUID); privateLink.setStatus("active"); AccountFriendLink hiddenLink = new AccountFriendLink(); hiddenLink.setTenantId(11L); - hiddenLink.setAccountId(2L); - hiddenLink.setFriendAccountId(4L); + hiddenLink.setAccountId(ACCOUNT_UUID); + hiddenLink.setFriendAccountId(OTHER_UUID); hiddenLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(privateLink, hiddenLink)); - when(accountClient.getPresenceVisibilityPolicies(11L, List.of(3L, 4L))) + when(accountClient.getPresenceVisibilityPolicies(11L, List.of(FRIEND_ID, OTHER_ID))) .thenReturn( Map.of( - 3L, FriendPresenceVisibilityPolicyValue.PRIVATE, - 4L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + FRIEND_ID, FriendPresenceVisibilityPolicyValue.PRIVATE, + OTHER_ID, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID, OTHER_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setGameInstanceId("9") .setWorldSlug("demo") @@ -746,7 +792,7 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(OTHER_ID) .setOnline(true) .setGameInstanceId("10") .setCharacterId("100") @@ -757,7 +803,7 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { .build()) .build()); - var result = service.listFriendPresence(11L, 2L); + var result = service.listFriendPresence(11L, ACCOUNT_ID); assertEquals(2, result.totalCount()); assertEquals(2, result.matchCount()); @@ -790,17 +836,17 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { assertEquals(null, result.presences().get(1).lastSeenAt()); assertNull(result.presences().get(1).recentDisposition()); - var privateFiltered = service.listFriends(11L, 2L, FriendRosterFilter.PRIVATE); + var privateFiltered = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.PRIVATE); assertEquals(2, privateFiltered.totalCount()); assertEquals(2, privateFiltered.matchCount()); assertEquals(1, privateFiltered.friends().getFirst().ordinal()); - assertEquals(3L, privateFiltered.friends().getFirst().friendAccountId()); + assertEquals(FRIEND_ID, privateFiltered.friends().getFirst().friendAccountId()); assertNull(privateFiltered.friends().getFirst().presence().visibilityPolicy()); assertEquals(2, privateFiltered.friends().get(1).ordinal()); - assertEquals(4L, privateFiltered.friends().get(1).friendAccountId()); + assertEquals(OTHER_ID, privateFiltered.friends().get(1).friendAccountId()); assertNull(privateFiltered.friends().get(1).presence().visibilityPolicy()); - var hiddenStaffFiltered = service.listFriends(11L, 2L, FriendRosterFilter.HIDDEN_STAFF); + var hiddenStaffFiltered = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.HIDDEN_STAFF); assertEquals(FriendRosterFilter.PRIVATE, hiddenStaffFiltered.filter()); assertEquals(2, hiddenStaffFiltered.totalCount()); assertEquals(2, hiddenStaffFiltered.matchCount()); @@ -809,9 +855,9 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { hiddenStaffFiltered.friends().stream() .allMatch(entry -> entry.presence().visibilityPolicy() == null)); Mockito.verify(gameSessionClient, Mockito.never()) - .queryAccountPresence(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); + .queryAccountPresence(Mockito.anyLong(), Mockito.anyString(), Mockito.any()); - var summary = service.getFriendRosterSummary(11L, 2L); + var summary = service.getFriendRosterSummary(11L, ACCOUNT_ID); assertEquals(2, summary.totalCount()); assertEquals(0, summary.onlineCount()); assertEquals(2, summary.offlineCount()); @@ -828,18 +874,19 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { void listFriendPresenceFailsClosedWhenAccountPolicyBatchIsUnavailable() { AccountFriendLink link = new AccountFriendLink(); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(ACCOUNT_UUID); + link.setFriendAccountId(FRIEND_UUID); link.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, ACCOUNT_UUID, "active")) .thenReturn(List.of(link)); - when(accountClient.getPresenceVisibilityPolicies(11L, List.of(3L))).thenReturn(null); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(accountClient.getPresenceVisibilityPolicies(11L, List.of(FRIEND_ID))).thenReturn(null); + when(gameSessionClient.queryAccountPresence(11L, ACCOUNT_ID, List.of(FRIEND_ID))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(FRIEND_ID) .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -861,11 +908,11 @@ void listFriendPresenceFailsClosedWhenAccountPolicyBatchIsUnavailable() { .build()) .build()); - var result = service.listFriendPresence(11L, 2L); + var result = service.listFriendPresence(11L, ACCOUNT_ID); assertEquals(1, result.totalCount()); assertEquals(1, result.matchCount()); - assertEquals(3L, result.presences().get(0).friendAccountId()); + assertEquals(FRIEND_ID, result.presences().get(0).friendAccountId()); assertNull(result.presences().get(0).visibilityPolicy()); assertEquals(false, result.presences().get(0).online()); assertEquals(null, result.presences().get(0).gameInstanceId()); @@ -881,14 +928,14 @@ void listFriendPresenceFailsClosedWhenAccountPolicyBatchIsUnavailable() { assertEquals(null, result.presences().get(0).lastSeenAt()); assertNull(result.presences().get(0).recentDisposition()); Mockito.verify(gameSessionClient, Mockito.never()) - .queryAccountPresence(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); + .queryAccountPresence(Mockito.anyLong(), Mockito.anyString(), Mockito.any()); - var privateFiltered = service.listFriends(11L, 2L, FriendRosterFilter.PRIVATE); + var privateFiltered = service.listFriends(11L, ACCOUNT_ID, FriendRosterFilter.PRIVATE); assertEquals(1, privateFiltered.matchCount()); - assertEquals(3L, privateFiltered.friends().getFirst().friendAccountId()); + assertEquals(FRIEND_ID, privateFiltered.friends().getFirst().friendAccountId()); assertNull(privateFiltered.friends().getFirst().presence().visibilityPolicy()); - var summary = service.getFriendRosterSummary(11L, 2L); + var summary = service.getFriendRosterSummary(11L, ACCOUNT_ID); assertEquals(1, summary.privateCount()); assertEquals(0, summary.unspecifiedVisibilityCount()); } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java index 04016de09a..ff8b29d34d 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.UUID; import net.firedevops.firemud.socialgroups.dto.AddGuildMemberRequest; import net.firedevops.firemud.socialgroups.dto.GuildMemberDto; import net.firedevops.firemud.socialgroups.dto.UpdateGuildMemberRoleRequest; @@ -17,6 +18,8 @@ import org.mockito.Mockito; class GuildServiceImplTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000003"; + private static final UUID ACCOUNT_UUID = UUID.fromString(ACCOUNT_ID); private GuildMemberRepository repository; private net.firedevops.firemud.socialgroups.client.LoggingAdminClient loggingAdminClient; private GuildServiceImpl service; @@ -41,19 +44,19 @@ void setUp() { @Test void addMemberReturnsDto() throws Exception { - AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 2L, 3L, "member"); + AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 2L, ACCOUNT_ID, "member"); GuildMember saved = new GuildMember(); saved.setId(1L); saved.setTenantId(1L); saved.setGuildId(2L); - saved.setAccountId(3L); + saved.setAccountId(ACCOUNT_UUID); saved.setRole("member"); when(repository.save(any(GuildMember.class))).thenReturn(saved); GuildMemberDto dto = service.addMember(request); - assertEquals(3L, dto.accountId()); + assertEquals(ACCOUNT_ID, dto.accountId()); assertEquals("member", dto.role()); - verify(loggingAdminClient).reportChatViolation(1L, 3L, "Joined guild 2"); + verify(loggingAdminClient).reportChatViolation(1L, ACCOUNT_ID, "Joined guild 2"); } @Test @@ -62,17 +65,17 @@ void updateMemberRoleUsesRepositoryLookup() throws Exception { member.setId(5L); member.setTenantId(1L); member.setGuildId(2L); - member.setAccountId(3L); + member.setAccountId(ACCOUNT_UUID); member.setRole("member"); - when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, 3L)) + when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, ACCOUNT_UUID)) .thenReturn(java.util.Optional.of(member)); GuildMemberDto dto = - service.updateMemberRole(new UpdateGuildMemberRoleRequest(1L, 2L, 3L, "officer")); + service.updateMemberRole(new UpdateGuildMemberRoleRequest(1L, 2L, ACCOUNT_ID, "officer")); assertEquals("officer", dto.role()); - verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, 3L); - verify(loggingAdminClient).reportChatViolation(1L, 3L, "Updated guild role to officer"); + verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, ACCOUNT_UUID); + verify(loggingAdminClient).reportChatViolation(1L, ACCOUNT_ID, "Updated guild role to officer"); } @Test @@ -81,15 +84,15 @@ void removeMemberUsesRepositoryLookup() throws Exception { member.setId(5L); member.setTenantId(1L); member.setGuildId(2L); - member.setAccountId(3L); + member.setAccountId(ACCOUNT_UUID); member.setRole("member"); - when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, 3L)) + when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, ACCOUNT_UUID)) .thenReturn(java.util.Optional.of(member)); - service.removeMember(1L, 2L, 3L); + service.removeMember(1L, 2L, ACCOUNT_ID); - verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, 3L); + verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, ACCOUNT_UUID); verify(repository).delete(member); - verify(loggingAdminClient).reportChatViolation(1L, 3L, "Left guild 2"); + verify(loggingAdminClient).reportChatViolation(1L, ACCOUNT_ID, "Left guild 2"); } } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java index 010d307788..b51b392d34 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.when; import java.time.Instant; +import java.util.UUID; import net.firedevops.firemud.socialgroups.dto.MailMessageDto; import net.firedevops.firemud.socialgroups.dto.SendMailRequest; import net.firedevops.firemud.socialgroups.entity.MailMessage; @@ -16,6 +17,8 @@ import org.mockito.Mockito; class MailServiceImplTest { + private static final String SENDER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String RECIPIENT_ACCOUNT_ID = "00000000-0000-4000-8000-000000000003"; private MailMessageRepository repository; private MailServiceImpl service; @@ -28,12 +31,13 @@ void setUp() { @Test void sendMailReturnsDto() { - SendMailRequest request = new SendMailRequest(1L, 2L, 3L, "hello", "body"); + SendMailRequest request = + new SendMailRequest(1L, SENDER_ACCOUNT_ID, RECIPIENT_ACCOUNT_ID, "hello", "body"); MailMessage saved = new MailMessage(); saved.setId(1L); saved.setTenantId(1L); - saved.setSenderAccountId(2L); - saved.setRecipientAccountId(3L); + saved.setSenderAccountId(UUID.fromString(SENDER_ACCOUNT_ID)); + saved.setRecipientAccountId(UUID.fromString(RECIPIENT_ACCOUNT_ID)); saved.setSubject("hello"); saved.setContent("body"); saved.setSentAt(Instant.now()); @@ -41,6 +45,6 @@ void sendMailReturnsDto() { MailMessageDto result = service.sendMail(request); assertEquals("hello", result.subject()); - assertEquals(3L, result.recipientAccountId()); + assertEquals(RECIPIENT_ACCOUNT_ID, result.recipientAccountId()); } } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java index f03f931e28..c35bfa37c5 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java @@ -43,6 +43,10 @@ import org.mockito.Mockito; class SocialGroupsGrpcServiceTest { + private static final String ACCOUNT_ID = "c41744c9-285e-4ed0-9fb4-0f0acb7a0123"; + private static final String FRIEND_ID = "d52755da-396f-4fd1-80c5-1f1bcb8b1234"; + private static final String RECIPIENT_ID = "e63866eb-4a70-4fe2-91d6-202cdc9c2345"; + @Test void pingReturnsPong() { PingService ping = Mockito.mock(PingService.class); @@ -84,7 +88,7 @@ void createGuildErrorReturnsErrorDetail() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -93,7 +97,7 @@ void createGuildErrorReturnsErrorDetail() { service.createGuild( net.firedevops.firemud.socialgroups.v1.CreateGuildRequest.newBuilder() .setTenantId("1") - .setOwnerAccountId("2") + .setOwnerAccountId(ACCOUNT_ID) .setName("test") .build(), new StreamObserver<>() { @@ -122,7 +126,7 @@ void createGuildRuntimeFailureReturnsInternalErrorDetail() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -131,7 +135,7 @@ void createGuildRuntimeFailureReturnsInternalErrorDetail() { service.createGuild( net.firedevops.firemud.socialgroups.v1.CreateGuildRequest.newBuilder() .setTenantId("1") - .setOwnerAccountId("2") + .setOwnerAccountId(ACCOUNT_ID) .setName("test") .build(), new StreamObserver<>() { @@ -159,7 +163,7 @@ void sendMessageMapsWhisperProtoToDomainEnum() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -168,9 +172,9 @@ void sendMessageMapsWhisperProtoToDomainEnum() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(ACCOUNT_ID) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_WHISPER) - .setRecipientId("7") + .setRecipientId(RECIPIENT_ID) .setContent("quiet") .build(), new StreamObserver<>() { @@ -188,7 +192,8 @@ public void onCompleted() {} verify(chat) .sendMessage( - new SendMessageRequestDto(1L, 2L, ChatType.WHISPER, "", 7L, null, null, "quiet", null)); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.WHISPER, "", RECIPIENT_ID, null, null, "quiet", null)); assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); } @@ -201,7 +206,7 @@ void sendMessageMapsEffectIdToDomainRequest() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -209,7 +214,7 @@ void sendMessageMapsEffectIdToDomainRequest() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(ACCOUNT_ID) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY) .setContent("hello") .setEffectId("fx-comm-2") @@ -228,7 +233,7 @@ public void onCompleted() {} verify(chat) .sendMessage( new SendMessageRequestDto( - 1L, 2L, ChatType.SAY, "", null, null, null, "hello", "fx-comm-2")); + 1L, ACCOUNT_ID, ChatType.SAY, "", null, null, null, "hello", "fx-comm-2")); } @Test @@ -239,7 +244,7 @@ void sendMessageRejectsZeroRecipientIdBeforeDispatch() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -248,7 +253,7 @@ void sendMessageRejectsZeroRecipientIdBeforeDispatch() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(ACCOUNT_ID) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_TELL) .setRecipientId("0") .setContent("hello") @@ -269,7 +274,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(false, ref.get().getSuccess()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("recipientId must be positive", ref.get().getError().getMessage()); + assertEquals("Malformed claim: recipientId", ref.get().getError().getMessage()); verifyNoInteractions(chat); } @@ -281,7 +286,7 @@ void sendMessageTreatsBlankOptionalIdsAsAbsent() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -290,7 +295,7 @@ void sendMessageTreatsBlankOptionalIdsAsAbsent() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(ACCOUNT_ID) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY) .setRecipientId(" ") .setGuildId(" ") @@ -312,7 +317,8 @@ public void onCompleted() {} verify(chat) .sendMessage( - new SendMessageRequestDto(1L, 2L, ChatType.SAY, "", null, null, null, "hello", null)); + new SendMessageRequestDto( + 1L, ACCOUNT_ID, ChatType.SAY, "", null, null, null, "hello", null)); assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); } @@ -325,8 +331,8 @@ void listFriendPresenceMapsDtosToProtoEntries() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); - Mockito.when(friend.listFriendPresence(1L, 2L, FriendRosterFilter.FRIENDS_ONLY)) + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); + Mockito.when(friend.listFriendPresence(1L, ACCOUNT_ID, FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new net.firedevops.firemud.socialgroups.dto.FriendPresenceViewDto( FriendRosterFilter.FRIENDS_ONLY, @@ -334,7 +340,7 @@ void listFriendPresenceMapsDtosToProtoEntries() { 1, List.of( new FriendPresenceDto( - 3L, + FRIEND_ID, true, 9L, "demo", @@ -354,7 +360,7 @@ void listFriendPresenceMapsDtosToProtoEntries() { service.listFriendPresence( net.firedevops.firemud.socialgroups.v1.ListFriendPresenceRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .setFilter( net.firedevops.firemud.socialgroups.v1.FriendRosterFilter .FRIEND_ROSTER_FILTER_FRIENDS_ONLY) @@ -374,7 +380,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(1, ref.get().getPresencesCount()); - assertEquals("3", ref.get().getPresences(0).getFriendAccountId()); + assertEquals(FRIEND_ID, ref.get().getPresences(0).getFriendAccountId()); assertEquals(true, ref.get().getPresences(0).getOnline()); assertEquals( net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_FRIENDS_ONLY, @@ -402,20 +408,20 @@ void getFriendMapsRosterDtoToProtoEntry() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); - Mockito.when(friend.getFriend(1L, 2L, 3L)) + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); + Mockito.when(friend.getFriend(1L, ACCOUNT_ID, FRIEND_ID)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + FRIEND_ID, true, 9L, "SHARED", @@ -438,8 +444,8 @@ void getFriendMapsRosterDtoToProtoEntry() { service.getFriend( net.firedevops.firemud.socialgroups.v1.GetFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("3") + .setAccountId(ACCOUNT_ID) + .setFriendAccountId(FRIEND_ID) .build(), new StreamObserver<>() { @Override @@ -455,7 +461,7 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("3", ref.get().getFriend().getFriendAccountId()); + assertEquals(FRIEND_ID, ref.get().getFriend().getFriendAccountId()); assertEquals("7", ref.get().getFriend().getFriendLinkId()); assertEquals("Ben", ref.get().getFriend().getPresence().getCharacterName()); } @@ -468,7 +474,7 @@ void removeFriendInvokesServiceAndReturnsSuccess() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -477,8 +483,8 @@ void removeFriendInvokesServiceAndReturnsSuccess() { service.removeFriend( net.firedevops.firemud.socialgroups.v1.RemoveFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("3") + .setAccountId(ACCOUNT_ID) + .setFriendAccountId(FRIEND_ID) .build(), new StreamObserver<>() { @Override @@ -493,7 +499,7 @@ public void onError(Throwable t) {} public void onCompleted() {} }); - verify(friend).removeFriend(1L, 2L, 3L); + verify(friend).removeFriend(1L, ACCOUNT_ID, FRIEND_ID); assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); } @@ -509,7 +515,7 @@ void addFriendIllegalArgumentReturnsErrorDetail() { new IllegalArgumentException("Cannot add or remove your own account as a friend")); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -519,8 +525,8 @@ void addFriendIllegalArgumentReturnsErrorDetail() { service.addFriend( net.firedevops.firemud.socialgroups.v1.AddFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("2") + .setAccountId(ACCOUNT_ID) + .setFriendAccountId(ACCOUNT_ID) .build(), new StreamObserver<>() { @Override @@ -550,10 +556,10 @@ void removeFriendIllegalArgumentReturnsErrorDetail() { Mockito.doThrow( new IllegalArgumentException("Cannot add or remove your own account as a friend")) .when(friend) - .removeFriend(1L, 2L, 2L); + .removeFriend(1L, ACCOUNT_ID, ACCOUNT_ID); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -562,8 +568,8 @@ void removeFriendIllegalArgumentReturnsErrorDetail() { service.removeFriend( net.firedevops.firemud.socialgroups.v1.RemoveFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("2") + .setAccountId(ACCOUNT_ID) + .setFriendAccountId(ACCOUNT_ID) .build(), new StreamObserver<>() { @Override @@ -592,8 +598,8 @@ void listFriendsMapsDtosToProtoEntries() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); - Mockito.when(friend.listFriends(1L, 2L, FriendRosterFilter.FRIENDS_ONLY)) + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); + Mockito.when(friend.listFriends(1L, ACCOUNT_ID, FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new FriendRosterViewDto( FriendRosterFilter.FRIENDS_ONLY, @@ -604,12 +610,12 @@ void listFriendsMapsDtosToProtoEntries() { 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + FRIEND_ID, true, 9L, "SHARED", @@ -631,7 +637,7 @@ void listFriendsMapsDtosToProtoEntries() { service.listFriends( net.firedevops.firemud.socialgroups.v1.ListFriendsRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .setFilter( net.firedevops.firemud.socialgroups.v1.FriendRosterFilter .FRIEND_ROSTER_FILTER_FRIENDS_ONLY) @@ -658,7 +664,7 @@ public void onCompleted() {} assertEquals(1, ref.get().getMatchCount()); assertEquals(1, ref.get().getFriends(0).getOrdinal()); assertEquals("7", ref.get().getFriends(0).getFriendLinkId()); - assertEquals("3", ref.get().getFriends(0).getFriendAccountId()); + assertEquals(FRIEND_ID, ref.get().getFriends(0).getFriendAccountId()); assertEquals("active", ref.get().getFriends(0).getStatus()); assertEquals( Instant.parse("2026-04-10T01:02:03Z").toEpochMilli(), @@ -679,8 +685,8 @@ void getFriendRosterSummaryMapsCanonicalCounts() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); - Mockito.when(friend.getFriendRosterSummary(1L, 2L)) + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); + Mockito.when(friend.getFriendRosterSummary(1L, ACCOUNT_ID)) .thenReturn(new FriendRosterSummaryDto(4, 1, 3, 2, 1, 2, 1, 0, 0, 2, 1, 1)); SocialGroupsGrpcService service = new SocialGroupsGrpcService( @@ -690,7 +696,7 @@ void getFriendRosterSummaryMapsCanonicalCounts() { service.getFriendRosterSummary( net.firedevops.firemud.socialgroups.v1.GetFriendRosterSummaryRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .build(), new StreamObserver<>() { @Override @@ -728,21 +734,21 @@ void getFriendByOrdinalMapsCanonicalEntry() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); - Mockito.when(friend.getFriendByOrdinal(1L, 2L, 1)) + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); + Mockito.when(friend.getFriendByOrdinal(1L, ACCOUNT_ID, 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, true, null, null, null, null, null, null, null, null, "Ben", null, null, - null, null)))); + FRIEND_ID, true, null, null, null, null, null, null, null, null, "Ben", + null, null, null, null)))); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -751,7 +757,7 @@ void getFriendByOrdinalMapsCanonicalEntry() { service.getFriendByOrdinal( net.firedevops.firemud.socialgroups.v1.GetFriendByOrdinalRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .setOrdinal(1) .build(), new StreamObserver<>() { @@ -769,7 +775,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(1, ref.get().getFriend().getOrdinal()); - assertEquals("3", ref.get().getFriend().getFriendAccountId()); + assertEquals(FRIEND_ID, ref.get().getFriend().getFriendAccountId()); } @Test @@ -780,21 +786,21 @@ void removeFriendByOrdinalMapsRemovedCanonicalEntry() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); - Mockito.when(friend.removeFriendByOrdinal(1L, 2L, 1)) + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); + Mockito.when(friend.removeFriendByOrdinal(1L, ACCOUNT_ID, 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + ACCOUNT_ID, + FRIEND_ID, "active", Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, false, null, null, null, null, null, null, null, null, null, null, null, - null, null)))); + FRIEND_ID, false, null, null, null, null, null, null, null, null, null, + null, null, null, null)))); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -803,7 +809,7 @@ void removeFriendByOrdinalMapsRemovedCanonicalEntry() { service.removeFriendByOrdinal( net.firedevops.firemud.socialgroups.v1.RemoveFriendByOrdinalRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .setOrdinal(1) .build(), new StreamObserver<>() { @@ -821,7 +827,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); - assertEquals("3", ref.get().getRemovedFriend().getFriendAccountId()); + assertEquals(FRIEND_ID, ref.get().getRemovedFriend().getFriendAccountId()); } @Test @@ -832,8 +838,8 @@ void getFriendPresencePolicyMapsCanonicalPolicy() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); - Mockito.when(friend.getFriendPresencePolicy(1L, 2L)) + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); + Mockito.when(friend.getFriendPresencePolicy(1L, ACCOUNT_ID)) .thenReturn(new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.PRIVATE)); SocialGroupsGrpcService service = new SocialGroupsGrpcService( @@ -843,7 +849,7 @@ void getFriendPresencePolicyMapsCanonicalPolicy() { service.getFriendPresencePolicy( net.firedevops.firemud.socialgroups.v1.GetFriendPresencePolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .build(), new StreamObserver<>() { @Override @@ -881,7 +887,7 @@ void getFriendPresencePolicyRejectsMalformedTenantIdBeforeAccessCheck() { service.getFriendPresencePolicy( net.firedevops.firemud.socialgroups.v1.GetFriendPresencePolicyRequest.newBuilder() .setTenantId("abc") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .build(), new StreamObserver<>() { @Override @@ -910,9 +916,10 @@ void updateFriendPresencePolicyMapsCanonicalPolicy() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); Mockito.when( - friend.updateFriendPresencePolicy(1L, 2L, FriendPresenceVisibilityPolicyValue.PUBLIC)) + friend.updateFriendPresencePolicy( + 1L, ACCOUNT_ID, FriendPresenceVisibilityPolicyValue.PUBLIC)) .thenReturn(new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.PUBLIC)); SocialGroupsGrpcService service = new SocialGroupsGrpcService( @@ -922,7 +929,7 @@ void updateFriendPresencePolicyMapsCanonicalPolicy() { service.updateFriendPresencePolicy( net.firedevops.firemud.socialgroups.v1.UpdateFriendPresencePolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_ID) .setVisibilityPolicy( net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) @@ -956,7 +963,7 @@ void sendMailRejectsZeroRecipientAccountIdBeforeDispatch() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(true); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -965,7 +972,7 @@ void sendMailRejectsZeroRecipientAccountIdBeforeDispatch() { service.sendMail( net.firedevops.firemud.socialgroups.v1.SendMailRequest.newBuilder() .setTenantId("1") - .setSenderAccountId("2") + .setSenderAccountId(ACCOUNT_ID) .setRecipientAccountId("0") .setSubject("hi") .setContent("body") @@ -986,7 +993,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(false, ref.get().getSuccess()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("recipientAccountId must be positive", ref.get().getError().getMessage()); + assertEquals("Malformed claim: recipientAccountId", ref.get().getError().getMessage()); verifyNoInteractions(mail); } @@ -998,7 +1005,7 @@ void sendMailReturnsPermissionDeniedForUnauthorizedSender() { FriendService friend = Mockito.mock(FriendService.class); MailService mail = Mockito.mock(MailService.class); SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); - Mockito.when(accessGuard.hasAccountAccess(1L, 2L)).thenReturn(false); + Mockito.when(accessGuard.hasAccountAccess(1L, ACCOUNT_ID)).thenReturn(false); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -1007,8 +1014,8 @@ void sendMailReturnsPermissionDeniedForUnauthorizedSender() { service.sendMail( net.firedevops.firemud.socialgroups.v1.SendMailRequest.newBuilder() .setTenantId("1") - .setSenderAccountId("2") - .setRecipientAccountId("3") + .setSenderAccountId(ACCOUNT_ID) + .setRecipientAccountId(FRIEND_ID) .setSubject("hi") .setContent("body") .build(), diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImplTest.java index a2bbf00809..3937342d67 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/VoiceChatServiceImplTest.java @@ -20,7 +20,8 @@ void setup() { @Test void createTokenReturnsToken() { - VoiceTokenRequestDto request = new VoiceTokenRequestDto(1L, 2L, "guild-1"); + VoiceTokenRequestDto request = + new VoiceTokenRequestDto(1L, "00000000-0000-4000-8000-000000000002", "guild-1"); VoiceTokenDto dto = service.createToken(request);